Dinesh
Dinesh

Reputation: 285

R data.table - multiply two columns whose components are matrices

I have a data.table with some numeric columns and another column each entry of which is a matrix. Here is an example:

dt = data.table(a = c(1,2,3), b = c(-1,4,2))
dt$c = vector("list",3)
for (ind in 1:3){dt$c[[ind]] = round(matrix(10*runif(8), nrow = 4))}

For each row, I want to multiply the numeric vector formed by columns a and b with the corresponding 4 x 2 matrix in c and store the resulting 4 numbers into columns V1, V2, V3 and V4. For instance, for the first row, I would take the 4 x 2 matrix dt$c[[1]], multiply it with the 2 x 1 vector rbind(dt$a[1],dt$b[1]) and assign the resulting 4 numbers into the first row of 4 new columns named V1, V2, V3 and V4.

I am looking for a native data.table way to do this. I am currently looping over all rows and that is prohibitively slow for my actual problem size. Tried a variety of data.table syntaxes but I suspect I am missing something fundamental in the way column c is internally treated as a list and therefore I am unable to get the matrix multiplication to work.

Any help on this would be greatly appreciated.

Upvotes: 2

Views: 280

Answers (1)

akrun
akrun

Reputation: 886938

We can use Map to do corresponding column value multiplication

dt[, paste0("V", 1:4) := do.call(rbind.data.frame,
        Map(function(x, y, z) t(z %*% c(x, y)) , a, b, c))]
dt
#   a  b                           c V1 V2 V3 V4
#1: 1 -1  1, 7, 4,10, 9, 7, 4, 1,... -8  0  0  9
#2: 2  4  1, 8, 8, 4, 7, 1, 5,10,... 30 20 36 48
#3: 3  2  6, 6, 9, 5, 0, 0,10, 2,... 18 18 47 19

Upvotes: 3

Related Questions