使用列名称的字符向量访问data.table中的列 [英] Accessing columns in data.table using a character vector of column names

查看:112
本文介绍了使用列名称的字符向量访问data.table中的列的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

假设我有一个R data.table:

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 vector? 您可以使用可选的 with = FALSE

Is there a way to specify the list(x,y) using the cols vector?

推荐答案

> all.equal(DT[,list(x,y)], DT[, cols, with = FALSE])
[1] TRUE
> all.equal(DT[,.SD[,list(x,y)][min(v)]], DT[,.SD[,cols, with = FALSE][min(v)]])
[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屋!

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