Assign a matrix to a subset of a data.table

dt1[,c("a1","a2")] <- as.data.table(m1)

gives a simple solution but does make a copy.

@Simon O'Hanlon provides a solution in the data.table way:

dt1[ , `:=`( a1 = m1[,1] , a2 = m1[,2] ) ]

and in my opinion an even better data.table solution is provided by @Frank:

dt1[,c("a1","a2") := as.data.table(m1)]

A data.frame is not a matrix, nor is a data.table a matrix. Both data.frame and data.table objects are lists. These are stored very differently, although the indexing can be similar, this is processed under the hood.

Within [<-.data.frame splits a matrix-valued value into a list with an element for each column.

(The line is value <- split(value, col(value)))).

Note also that [<-.data.frame will copy the entire data.frame in the process of assigning something to a subset of columns.

data.table attempts to avoid this copying, as such [<-.data.table should be avoided, as all <- methods in R make copies.

Within [<-.data.table, [<-.data.frame will be called if i is a matrix, but not if only value is.

data.table usually likes you to be explicit in ensuring that the types of data match when assigning. This helps avoid any coercion and related copying.

You could, perhaps put in a feature request here to ensure compatibility, but given your usage is far outside what is recommended, then perhaps the package authors might request you simply use the data.table conventions and approaches.

Tags:

R

Data.Table