2

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 Answers2

4

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
Anoushiravan R
  • 21,622
  • 3
  • 18
  • 41
2

we could use parse_number

library(dplyr)
library(readr)
datos %>%
  mutate(porcentaje = parse_number(porcentaje)
UseR10085
  • 7,120
  • 3
  • 24
  • 54
TarJae
  • 72,363
  • 6
  • 19
  • 66