tobinz
tobinz

Reputation: 335

matrix multiplication insider a data.table

I need to do matrix multiplication inside a data.table. Like this

DT1 <- data.table( x = rnorm(100), y = rnorm(100))

DT2 <- data.table(z = rt(100,3))

DT3 <- data.table::data.table( a = list(DT1,DT2))

In a simple DT1, I know by using

DT1[, x %*% t(x)]

can ouput a matrix.

However, when DT1,DT2 are wrapped in DT3, if I want to compute x %*% t(z), how can I do it? Thanks

Upvotes: 2

Views: 153

Answers (2)

ThomasIsCoding
ThomasIsCoding

Reputation: 101335

Perhaps you can try Map + tcrossprod within DT3 like below

DT3[, do.call(tcrossprod, Map(`[[`, a, c("x", "z")))]

Upvotes: 1

akrun
akrun

Reputation: 887108

We can loop over the list column with lapply, extract the dataset first column and apply the %*%

DT3[, lapply(a, function(u) u[[1]] %*% t(u[[1]]))]

If the OP wanted to do this based on extracting the list elements

DT3[, a[[1]]$x %*% t(a[[2]]$z)]

Upvotes: 0

Related Questions