更新R中data.table中的整行 [英] Update an entire row in data.table in R

查看:85
本文介绍了更新R中data.table中的整行的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在R中有一个data.table对象,该对象具有9,000列。我的代码一次计算所有9,000列的新值,并返回值向量。我只想一次用所有值替换data.table中的行。在dataFrame对象中,这很容易。但是,我不知道如何在data.table中工作。

I have a data.table object in R that has 9,000 columns. My code calculates new values for all 9,000 columns at once and returns a vector of values. I'd like to just replace the row in the data.table with all the values at once. In a dataFrame object this is easy. However, I can't figure out how to get that working in a data.table.

d <- data.table(q=c(1,2,3,4,5,6,7,8,9), x=rep(c("a","b","c"),each=3), y=c(1,3,6), v=1:9)
d[q==1, := c(5,5,5,5)] # FAILS
d[q==1, ] <- c(5,5,5,5) # FAILS

任何想法如何有效一次更新整行?

Any idea how to efficiently update the whole row at once?

推荐答案

您可以使用 names(d)对于LHS,然后使用 as.list 来将向量转换为列表,这样 data.table 将了解需要将 each 值分配给 different 列,而不是将 all 值分配给 each 列。

You could use names(d) for LHS, then use as.list in order to convert your vector to a list so data.table will understand that it need to assign each value to a different column instead all the values to each column.

您还将此处的个字符向量转换为数字 x 列),因此 data.table 将返回警告,以确保您知道。

You are also converting character vector to numeric here (the x column), so data.table will return a warning in order to make sure you are aware of that.

vec <- c(5, 5, 5, 5)
d[q == 1L, names(d) := as.list(vec)][]
#    q x y v
# 1: 5 5 5 5
# 2: 2 a 3 2
# 3: 3 a 6 3
# 4: 4 b 1 4
# 5: 5 b 3 5
# 6: 6 b 6 6
# 7: 7 c 1 7
# 8: 8 c 3 8
# 9: 9 c 6 9

这篇关于更新R中data.table中的整行的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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