[英]Passing a string as a column name in data.table
I am trying to create a function to eliminate repetition in my code but am having issues using the eval function to pass a string as a column name using data.table.我正在尝试创建一个函数来消除我的代码中的重复,但是在使用 eval 函数使用 data.table 将字符串作为列名传递时遇到问题。 Sample code:
示例代码:
sample = data.table(a = 1:10,b=1:10)
sample
example = 'test_string'
working = sample[,.(test_string=a+b)]
working
notworking = sample[,.(eval(example)=a+b)]
notworking1 = sample[,eval(as.name(example):=a+b)]
notworking2 = sample[,eval(example):=a+b]
Any advice would help任何建议都会有所帮助
We need to just wrap it in brackets for evaluating it我们只需要将它包裹在括号中以评估它
sample[, (example) := a + b]
-output -输出
> sample
a b test_string
<int> <int> <int>
1: 1 1 2
2: 2 2 4
3: 3 3 6
4: 4 4 8
5: 5 5 10
6: 6 6 12
7: 7 7 14
8: 8 8 16
9: 9 9 18
10: 10 10 20
If we don't need to create a column in the original data ( :=
), use setNames
如果我们不需要在原始数据(
:=
)中创建列,请使用setNames
sample[, setNames(.(a + b), example)]
test_string
<int>
1: 2
2: 4
3: 6
4: 8
5: 10
6: 12
7: 14
8: 16
9: 18
10: 20
or setnames
或
setnames
setnames(sample[, .(a + b)], example)[]
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.