How to convert character of percentage into numeric in R

Frank Wang picture Frank Wang · Nov 30, 2011 · Viewed 53.5k times · Source

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?

Answer

Paul Hiemstra picture Paul Hiemstra · Nov 30, 2011

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.