【问题标题】:How to create new column in a data.table when the name of column must be a string [duplicate]当列名必须是字符串时如何在data.table中创建新列[重复]
【发布时间】:2016-07-06 04:49:13
【问题描述】:

当列名必须是字符串或字符时,如何在 data.table 中创建新列?

例如:

library(data.table)
DT = data.table(v1=c(1,2,3), v2=2:4)
new_var <- "v3"
DT[, new_var:=v2+5]

我明白了

DT
#>    v1 v2 new_var
#> 1:  1  2       7
#> 2:  2  3       8
#> 3:  3  4       9

但是,我想要

#>    v1 v2      v3
#> 1:  1  2       7
#> 2:  2  3       8
#> 3:  3  4       9

【问题讨论】:

    标签: r data.table


    【解决方案1】:

    我可以这样做,将变量名括在括号内:

    DT = data.table(v1=c(1,2,3), v2=2:4)
    new_var <- "v3"
    DT[, eval(new_var):=v2+5]
    # or
    DT[, (new_var):=v2+5]
    DT
    #>    v1 v2      v3
    #> 1:  1  2       7
    #> 2:  2  3       8
    #> 3:  3  4       9
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2020-06-10
      • 1970-01-01
      • 2020-05-04
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-07-16
      相关资源
      最近更新 更多