本文介绍了当列名必须为字符串时,如何在data.table中创建新列的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
当列名必须为字符串或字符时,如何在data.table中创建新列?
How to create new column in a data.table when the name of column must be a string or character?
例如:
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
推荐答案
我可以这样做,将变量名放在方括号内:
I can be done this way, by enclosing the variable name within brackets:
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
这篇关于当列名必须为字符串时,如何在data.table中创建新列的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!