如何将列列表传递给预先确定的 data.table [英] How to pass a list of columns to data.table where some are predetermined
问题描述
我希望能够在 R 中使用 data.table 生成列的子集,这样我可以更早地确定其中的一些列并将预定列表作为字符向量传递,然后与列.
I want to be able to produce a subset of columns in R using data.table in a way that I can determine some of them earlier on and pass the predetermined list on as a character vector, then combine with a static list of columns.
也就是说,鉴于此:
a <- 1:4
b <- 5:8
c <- c('aa','bb','cc','dd')
e <- 1:4
z <- data.table(a,b,c,e)
我想这样做:
z[, list(a,b)]
产生这个输出:
a b
1: 1 5
2: 2 6
3: 3 7
4: 4 8
但我想以与此类似的方式来做这件事(几乎可以):
But I want to do it in some way similar to this (which works, almost):
cols <- "b"
z[, list(get(cols), a)]
结果:请注意,它不会返回存储在 cols
Results:
Note that it doesn't return the name of the column stored in cols
V1 a
1: 5 1
2: 6 2
3: 7 3
4: 8 4
但我需要使用多个 cols
元素(这不起作用):
but I need to do it with more than one element of cols
(which does not work):
cols <- c('a', 'b')
z[, list(mget(cols), c)]
以上产生以下错误:
Error: value for ‘a’ not found
我认为我的问题在于范围界定以及 mget
正在查看哪些环境,但我无法弄清楚我到底做错了什么.另外,如何保留列标题?
I think my problem lies with scoping and which environments mget
is looking in, but I can't figure out what exactly I am doing wrong. Also, how do I preserve the column titles?
推荐答案
在data.table中将变量与列名与硬编码的列名结合起来
给定上面示例中的 z
和 cols
:
要将变量 col
中的列名列表与其他硬编码的列名 c
组合,我们将它们组合成一个新的字符向量 c(col, 'c')
在对 data.table
的调用中.我们可以通过使用up-one-level"从j
([]
中的第二个参数)中引用cols
.符号 ..
:
To combine a list of column names in a variable col
with other hard coded column name c
, we combine them in a new character vector c(col, 'c')
in the call to data.table
. We can refer to cols
from within j
(the second argument within []
) by using the "up-one-level" notation ..
:
z[, c(..cols, 'c')]
感谢@thelatemail 为上述解决方案提供基础.
Thank you to @thelatemail for providing the base to the solution above.
这篇关于如何将列列表传递给预先确定的 data.table的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!