[英]Referring to a column through a character variable in data.table R
I am using data.table and I want to filter a data.table within a function where I am passing the name of the column as a character vector. 我正在使用data.table,并且想在函数中过滤data.table,在该函数中我将列名作为字符向量传递。
For a simple reproducible example let's take the mtcars dataset of base R. 对于一个简单的可复制示例,让我们以基本R的mtcars数据集为例。
I can write using data.table syntax: 我可以使用data.table语法编写:
mtcars[am == 1, .N ]
But what if the name of the variable of interest -- ie am -- is stored as a character vector, ie "am"? 但是,如果感兴趣的变量的名称(即am)存储为字符向量(即“ am”)怎么办?
Your advice will be appreciated. 您的建议将不胜感激。
One option is to use get
( ?get search object by name): 一种选择是使用get
(按名称获取搜索对象):
mtcars[get('am') == 1, .N]
# [1] 13
Another option is to specify it in the .SDcols
另一种选择是在.SDcols
指定它
mtcars[, sum(.SD==1) ,.SDcols = 'am']
#[1] 13
We can also include multiple variables 我们还可以包含多个变量
mtcars[, sum(Reduce(`&`, lapply(.SD, `==`, 1))), .SDcols = c('am', 'carb')]
#[1] 4
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.