Z117
Z117

Reputation: 211

Matrix multiplication with integers or doubles in data table

Can someone explain to me why this works:

a <- data.table(t(c(1, 2, 3, 4, 5)))
b <- matrix(data=1, nrow=10, ncol=5)
a[,lapply(.SD,function(x)(x*b[,x]))]

But this doesn't:

a <- data.table(t(c(0.1, 0.2, 0.3, 0.4, 0.5)))
b <- matrix(data=1, nrow=10, ncol=5)
a[,lapply(.SD,function(x)(x*b[,x]))]

Upvotes: 1

Views: 1223

Answers (1)

akrun
akrun

Reputation: 887213

In the first case, the column values of 'a' act as column index to subset the 'b', while in the second case it wont because the values are 0.1 to 0.5. So, instead of looping through the columns, loop through the sequence of the columns, and then subset the 'b' and the column values, which would work in both cases

a[, lapply(seq_along(.SD),function(x)(.SD[[x]]*b[,x]))]

Or just replicate the rows of 'a' and then multiply with 'b'

a[rep(seq_len(.N), nrow(b))] * b

Upvotes: 3

Related Questions