How to convert character of percentage into numeric in R How to convert character of percentage into numeric in R r r

How to convert character of percentage into numeric in R


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.


Remove the "%", convert to numeric, then divide by 100.

x <- c("10%","5%")as.numeric(sub("%","",x))/100# [1] 0.10 0.05


If you're a tidyverse user (and actually also if not) there's now a parse_number function in the readr package:

readr::parse_number("10%")

The advantage is generalization to other common string formats such as:

parse_number("10.5%")parse_number("$1,234.5")