将多个列添加到data.table中,其中列名保存在向量中 [英] Adding multiple columns to a data.table, where column names are held in a vector

查看:95
本文介绍了将多个列添加到data.table中,其中列名保存在向量中的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想在R中的data.table中添加大量列。
列名保存在向量 a 中。

I want to add a large number of columns to a data.table in R. The column names are held in a vector a. How to do it?

x <- data.table(a=1,b=1)
f <- function(x) {list(0)}

以下工作:

x <- x[, c("col1","col2","col3") := f()]

但以下内容不是:

a <- c("col1","col2","col3")
x <- x[, a := f()]

如何添加在 a 中定义的列?

How do I add the columns defined within a?

推荐答案

要使其正常工作,您必须将 a 包装在()像这样:

In order to make that work, you have to wrap the a in () like this:

x[, (a) := f()]

这将产生以下数据表:


> x
   a b col1 col2 col3
1: 1 1    0    0    0


说明:当您使用 x [,a:= f()] 时,将结果分配为 f()到列 a data.table 允许这样做)。因此,在这种情况下, a 被视为名称。当您使用(a)时, a 被视为表达式(在这种情况下为列名称的向量)。

Explanation: when you use x[, a:=f()] you assign the outcome of f() to column a (data.table allows this for convenience). Thus a is treated as a name in this occasion. When you use (a), a is treated as an expression (in this case a vector of column names).

此外:您无需再次将 x分配给 x ;-作为数据表通过引用进行更新,因为使用了:= 运算符。

Furthermore: you don't need to assign this to x again with x <- as the datatable is updated by reference because the := operator is used.

这篇关于将多个列添加到data.table中,其中列名保存在向量中的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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