【问题标题】:How do I write a function that changes the structure and replaces values? [duplicate]如何编写更改结构和替换值的函数? [复制]
【发布时间】:2019-12-19 15:30:58
【问题描述】:

我的数据集存在一些结构性问题,我正在尝试编写一个名为“convert_number”的函数,它将完成以下任务: - 更改列中的数字,使“,”为“。” - 将该列转换为双精度 该函数还应该能够调用不同的列,因为我要更改大约 10 个。

我有一些想法,但都没有奏效。我想要一些新鲜的大脑,有人有什么建议吗?提前谢谢你

【问题讨论】:

  • 试试as.numeric(sub(",", ".", df1$colnm))

标签: r function numeric gsub


【解决方案1】:

你可以使用以下,

f1 <- function(x){
    x1 <- as.numeric(sub(',', '.', x))
    return(x1)
    }

然后您可以将其应用于任何列,即

df[your_cols] <- lapply(df[your_cols], f1)

【讨论】:

    【解决方案2】:

    如果我们有兴趣在将, 更改为. 后将列转换为数字,则一种选择是

    colsofinterest <- names(df1)[1:10]
    df1[colsofinterest] <- lapply(df1[colsofinterest], function(x) 
               as.numeric(sub(",", ".", x)))
    

    更简单的选择是在读取数据集时,指定dec,它会自动将类型更改为double

    df1 <- read.csv('file.csv', dec = ",")
    

    或在dplyr

    library(dplyr)
    df1 %>%
       mutate_at(vars(colsofinterest), ~ as.numeric(str_replace(., ",", ".")))
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2013-11-07
      • 2020-02-16
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多