How to set multiple columns and selected rows in a data table for a value from another data table

The question is somewhat related to this question ( How to set multiple columns in a data table for 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) 

This time I want to change certain rows and columns.

 dt[1:3, c("X1","X2"), with = F] = dt1[1:3, c("X3","X5"), with = F] 

But this gives an error:

 Error in `[<-.data.table`(`*tmp*`, 1:3, c("X1", "X2"), with = F, value = list( : unused argument (with = F) 

I will do with data having many columns. I hope the column name should be a character first.

0
source share
1 answer

Using the = operator, like you, you are trying to assign values ​​to the desired places in the data table. Instead, you should update your data.table dt by reference using the := operator inside dt[...] . A small adaptation of the @thelatemail comment (the second with = FALSE not needed):

 dt[1:3, c("X1","X2") := dt1[1:3, c("X3","X5"), with = FALSE]] 
+2
source

Source: https://habr.com/ru/post/1236540/


All Articles