【问题标题】:Use variable name to calculate or modify columns in a data.table [duplicate]使用变量名计算或修改 data.table 中的列 [重复]
【发布时间】:2021-03-20 01:35:38
【问题描述】:

我有以下data.table:

name = c("Bob","Mary","Jane","Kim")
weight = c(60,65,45,55)
height = c(170,165,140,135)
dft = data.table(name,weight,height)

我想将 weight 更改为等于 height + 13 。我知道有很多方法可以做到这一点,例如

dft[, weight := height + 13

dft[, "weight" := height + 13

但是,由于我有一个庞大的数据集,其列名类似于V1, V2,....,V1000,我希望使用列名来输入修改。然而,在上面的例子中,

dft[, "weight" := "height" + 13

不工作。

所以我想知道如何使用 "height" 来修改weight。谢谢

【问题讨论】:

    标签: r data.table


    【解决方案1】:

    你可以使用:

    library(data.table)
    name = c("Bob","Mary","Jane","Kim")
    weight = c(60,65,45,55)
    height = c(170,165,140,135)
    dft = data.table(name,weight,height)
    
    col1 <- 'weight'
    col2 <- 'height'
    
    dft[, (col1) := get(col2) + 13]
    dft
    
    #   name weight height
    #1:  Bob    183    170
    #2: Mary    178    165
    #3: Jane    153    140
    #4:  Kim    148    135
    

    【讨论】:

      【解决方案2】:

      我发现data.table 在很多方面都很糟糕。

      在基础 R 中,您只需要:

      df[, 'height'] + 13 -> df[, 'weight' ]
      

      【讨论】:

        猜你喜欢
        • 2012-09-18
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2018-08-01
        • 2020-10-21
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多