向数据表中添加列 [英] Adding columns to a data table

查看:115
本文介绍了向数据表中添加列的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个data.frame(或矩阵或任何其他表格数据结构对象):

  df = data.frame(field1 = c(1,1,1),field2 = c(2,2,2),field3 = c(3,3,3))
/ pre>

并且我想复制其列的一部分 - 在下面的向量中给出:

  fields = c(field1,field2)

已经有一个或多个列的新数据表:

  dt = data.table(fieldX = c x,x))



我正在寻找更高效比:

  for(f in 1:length(fields))
{
dt [,fields [f]] = df [,fields [f]]
}


解决方案

您可以使用 cbind

  cbind (dt,df [fields])

然而,最有效的方法仍然可能是使用 data.table 的引用分配:

  dt [ (fields):= df [fields]] 


I have a data.frame (or a matrix or any other tabular data structure object for that matter):

df = data.frame(field1 = c(1,1,1),field2 = c(2,2,2),field3 = c(3,3,3))

And I want to copy part of its columns - given in the vector below:

fields = c("field1","field2")

to a new data.table that already has 1 or more columns:

dt = data.table(fieldX = c("x","x","x"))

I'm looking for something more efficient (and elegant) than:

for(f in 1:length(fields))
{
dt[,fields[f]] = df[,fields[f]]
}

解决方案

You can use cbind:

cbind(dt, df[fields])

However, the most efficient way is still probably going to be to use data.table's assign by reference:

dt[, (fields) := df[fields]]

这篇关于向数据表中添加列的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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