使用列名的字符向量访问 data.table 中的列 [英] Accessing columns in data.table using a character vector of column names
本文介绍了使用列名的字符向量访问 data.table 中的列的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
假设我有一个 R 数据表:
Suppose I have an R data.table:
DT = data.table(x=rep(c("a","b","c"),each=3), y=c(1,3,6), v=1:9)
我有一个列名的字符向量,我想提取或者更一般地对其进行操作:
and I have a character vector of column names that I would like to extract, or more generally operate on:
cols = c("x","y")
例如,如何使用cols来生成等价的
For example, how can I use cols to generate the equivalent of
DT[,lapply(.SD[,list(x,y)], min) ]
有没有办法使用 cols 向量指定 list(x,y)?
Is there a way to specify the list(x,y) using the cols vector?
推荐答案
您可以使用 data.table
语法 ..
来查找一级"(如在 Unix 终端中)为变量:
You can use the data.table
syntax ..
which "looks up one level" (as in the Unix terminal) for the variable:
> all.equal(DT[,list(x,y)], DT[, ..cols])
[1] TRUE
> all.equal(DT[,.SD[,list(x,y)][min(v)]], DT[,.SD[ ,min(v)], .SDcols = cols])
[1] TRUE
FAQ 1.6 下的更多详细信息我相信:http://datatable.r-forge.r-project.org/datatable-faq.pdf
More details under FAQ 1.6 I believe: http://datatable.r-forge.r-project.org/datatable-faq.pdf
这篇关于使用列名的字符向量访问 data.table 中的列的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文