在R中使用变量在data.table中传递列名 [英] pass column name in data.table using variable in R
问题描述
可能重复:
可变选择/分配给data.table中的字段
在下面的示例中,我创建了一个数据表,其列名为'x'和'v'
In following example, I am creating a data table having column name ‘x’ and ‘v’
library('data.table')
DT = data.table(x=c("b","b","b","a","a"),v=rnorm(5)) DT$
DT$v DT$x
'x':
DT[,x]
[1] "b" "b" "b" "a" "a"
但是如果我想通过一个变量访问, t工作
But if I want to access by passing through a variable, it doesn’t work
temp="x"
DT[,temp]
[1] "x"
将有多个列,我必须为其中几个选择值。这些列名将通过R模块提供。
There would be multiple columns and I will have to select values for only couple of them. These column names I will be provide by passing through a R module.
没关系,我得到了
我得到它..
它应该是
I got it.. it shoud be
DT[,get(temp)]
推荐答案
使用quote()和eval()函数将变量传递给j。当您这样做时,不需要对列名称加双引号,因为quote() - 编译的字符串将在DT []中进行计算。
Use the quote() and eval() functions to pass a variable to j. You don't need double-quotes on the column names when you do it this way, because the quote()-ed string will be evaluated inside the DT[]
temp <- quote(x)
DT[,eval(temp)]
# [1] "b" "b" "b" "a" "a"
使用单个列名称,结果是一个向量。如果你想要一个data.table结果或多个列,使用列表形式
With a single column name, the result is a vector. If you want a data.table result, or several columns, use list form
temp <- quote(list(x,v))
DT[,eval(temp)]
# x v
# 1: b 1.52566586
# 2: b 0.66057253
# 3: b -1.29654641
# 4: a -1.71998260
# 5: a 0.03159933
这篇关于在R中使用变量在data.table中传递列名的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!