使用变量在data.table中传递列名 [英] Pass column name in data.table using variable

查看:79
本文介绍了使用变量在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))

我可以通过以下方式访问列'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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆