如何将列的列表传递给data.table,其中一些是预先确定的 [英] How to pass a list of columns to data.table where some are predetermined

查看:156
本文介绍了如何将列的列表传递给data.table,其中一些是预先确定的的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

能够使用data.table在R中产生列的子集,以这种方式我可以确定它们中的一些,并将预定列表作为字符向量,然后与静态列列表组合。

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

   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


b $ b

我认为我的问题在于范围和环境 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?

推荐答案

将数据中的变量与列名称与硬编码的列名称组合。表



从上述示例中给出 z cols

将变量 col 中的列名称列表与其他硬编码列名称<$ c $在调用时,我们将它们组合到一个新的字符向量 c(col,'c') data.table 。然后,我们将参数传递给= FALSE data.table

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 then pass the argument with=FALSE to data.table.

z[, c(cols, 'c'), with=FALSE]

with = FALSE 参数告诉 data.table 使用新向量作为名称的向量,以从 data.table 中选择。默认情况下, with = TRUE ,而是将它们视为变量。因此,调用 z [,c(cols,'c')] 返回一个具有 c(cols,'c' ),即:a,b,c

The with=FALSE argument tells data.table to use the new vector as a vector of names to select from data.table. The default, with=TRUE, instead treats them as variables. Thus, the call z[, c(cols, 'c')] returns a character vector with the elements in c(cols, 'c'), that is: "a", "b", "c".

感谢@thelatemail为上述解决方案提供基础。

Thank you to @thelatemail for providing the base to the solution above.

这篇关于如何将列的列表传递给data.table,其中一些是预先确定的的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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