Convert percent to numeric on data frame in R?

Viewed 127

Hi and thanks for reading me

Im trying to convert the columns of a df in to numeric values, but it doesnt work, anyone nows why? The code is the following:

datos <- data.frame(dato1 = c(1,2,3),
                    porcentaje = c("1%", "2%", "3%")
                    )

datos <- datos |> 
  as.numeric(as.numeric(sub("%", "", datos$porcentaje)))
2 Answers

You can use the following solution:

datos <- transform(datos, 
                   porcentaje = as.numeric(gsub("[%]", "", datos$porcentaje)))

> str(datos)
'data.frame':   3 obs. of  2 variables:
 $ dato1     : num  1 2 3
 $ porcentaje: num  1 2 3

we could use parse_number

library(dplyr)
library(readr)
datos %>%
  mutate(porcentaje = parse_number(porcentaje)
Related