Search code examples
rcharacternumericr-faq

How to convert character of percent into numeric in R


I have data with percent signs (%) that I want to convert into numeric. I run into a problem when converting character of percentage to numeric. E.g. I want to convert "10%" into 10%, but

as.numeric("10%")

returns NA. Do you have any ideas?


Solution

  • 10% is per definition not a numeric vector. Therefore, the answer NA is correct. You can convert a character vector containing these numbers to numeric in this fashion:

    percent_vec = paste(1:100, "%", sep = "")
    as.numeric(sub("%", "", percent_vec))
    

    This works by using sub to replace the % character by nothing.