【问题标题】:Convert percent to numeric on data frame in R? [duplicate]在R中的数据框中将百分比转换为数字? [复制]
【发布时间】:2021-08-09 04:09:54
【问题描述】:

您好,感谢您阅读我的文章

我试图将 df 的列转换为数值,但它不起作用,现在有人知道为什么了吗? 代码如下:

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

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

【问题讨论】:

    标签: r dataframe


    【解决方案1】:

    您可以使用以下解决方案:

    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
    

    【讨论】:

      【解决方案2】:

      我们可以使用parse_number

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

      【讨论】:

        猜你喜欢
        • 2012-01-09
        • 1970-01-01
        • 1970-01-01
        • 2019-05-02
        • 1970-01-01
        • 1970-01-01
        • 2021-09-25
        • 1970-01-01
        • 2013-09-01
        相关资源
        最近更新 更多