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:

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

You need to convert the RHS to a list, and an easy way to do that is to use

DT[, 2:ncol(DT) :=[,2:ncol(DT)])]

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