Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

data.table: Update multiple columns in a data.table with a matrix

How do I update multiple columns in a data.table with values from a matrix. Here is an MWE illustrating the issue I am facing:

library(data.table)
DT = data.table(expand.grid(1:3,1:3,1:3))
DF = expand.grid(1:3,1:3,1:3)
mat = matrix(seq(0, 80), 27, 3)

In a data.frame world I would go with this syntax:

DF[,2:ncol(DF)] = mat[,2:ncol(DF)] #Data frame approach

A similar take on data.table syntax yields multiple warnings with a very weird output.

DT[,2:ncol(DF) := mat[,2:ncol(DF)], with=FALSE] #Data table approach

This is obviously faulty - as the warnings indicates that the matrix was actually flattened. Warning messages:

1: In `[.data.table`(DT, , `:=`(2:ncol(DF), mat[, 2:ncol(DF)]), with = FALSE) :
  2 column matrix RHS of := will be treated as one vector
like image 516
sriramn Avatar asked Dec 14 '22 12:12

sriramn


1 Answers

You need to convert the RHS to a list, and an easy way to do that is to use as.data.table:

DT[, 2:ncol(DT) := as.data.table(mat[,2:ncol(DT)])]

with is not necessary here, as LHS is deduced to mean column numbers automatically.

like image 140
Señor O Avatar answered Mar 09 '23 01:03

Señor O