如何将数据表中的多个列和所选行设置为其他数据表中的值 [英] How to set multiple columns and selected rows in data table to value from other data table
问题描述
问题与这个问题有些相关(如何将数据表中的多个列设置为同一数据表中不同列的值?)。
The Question is somewhat related with this question (How to set multiple columns in a data table to values from different columns in the same data table?).
set.seed(1)
df <- data.frame(matrix(sample(1:100,30),ncol=6))
# X1 X2 X3 X4 X5 X6
#1 27 86 19 43 75 29
#2 37 97 16 88 17 1
#3 57 62 61 83 51 28
#4 89 58 34 32 10 81
#5 20 6 67 63 21 25
library(data.table)
dt <- data.table(df)
df1 <- data.frame(matrix(sample(1:100,30),ncol=6))
df1
# X1 X2 X3 X4 X5 X6
#1 49 64 74 68 39 8
#2 60 75 58 2 88 24
#3 100 11 69 40 35 91
#4 19 67 98 61 97 48
#5 80 38 46 57 6 29
dt1 <- data.table(df1)
更改某一行和列。
dt[1:3, c("X1","X2"), with = F] = dt1[1:3, c("X3","X5"), with = F]
但是这一个给出一个错误:
But this one give an error:
Error in `[<-.data.table`(`*tmp*`, 1:3, c("X1", "X2"), with = F, value = list( :
unused argument (with = F)
我会做的数据有很多列。
I will do with the data had many columns. I hope that the name of column should be character at first.
推荐答案
使用 =
运算符,您正在尝试将值分配到 data.table 中的所需位置。相反,您应该使用:=
运算符更新您的 data.table dt
dt [...]
。略微改写@ thelatemail的注释(不需要第二个 with = FALSE
):
By using the =
operator as you do, you are trying assign the values to the desired spots in the data.table. Instead you should update your data.table dt
by reference with the :=
operator inside dt[...]
. A slight adaptation of @thelatemail's comment (the second with = FALSE
is not needed):
dt[1:3, c("X1","X2") := dt1[1:3, c("X3","X5"), with = FALSE]]
这篇关于如何将数据表中的多个列和所选行设置为其他数据表中的值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!