使用变量在 data.table 中传递列名 [英] Pass column name in data.table using variable
问题描述
在下面的示例中,我正在创建一个列名为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))
我可以通过以下方式访问x"列的值:
I can access values of column ‘x’ by :
DT[ , x]
# [1] "b" "b" "b" "a" "a"
但是如果我想通过一个变量来访问,那就不行了
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.
没关系,我明白了,应该是:
Never mind, I got it, it should be:
DT[ , get(temp)]
推荐答案
使用 quote()
和 eval()
函数将变量传递给 j代码>.当你这样做时,你不需要在列名上加双引号,因为
quote()
-ed 字符串将在 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
这篇关于使用变量在 data.table 中传递列名的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!