What is going on with the apply
function below? Why doesn't it produce the desired output? Is there a simple way to produce the desired output using the apply
function?
I feel like I'm missing something really fundamental in how the apply
function is working. I think this basically comes down to the following lines in the apply
function.
Line #67: else length(ans <- unlist(ans, recursive = FALSE))
Line #83: array(ans, c(len.a%/%d2, d.ans))
But I'm still not really getting what's going on. I know there are other, non-apply
, ways to produce the desired output. But at this point I'm just trying to understand what's going on with apply
.
ff <- matrix(1:6,ncol=2)
# [,1] [,2]
# [1,] 1 4
# [2,] 2 5
# [3,] 3 6
bb <- matrix(7:10,ncol=2)
# [,1] [,2]
# [1,] 7 9
# [2,] 8 10
# DESIRE:
# 7 36
# 14 45
# 21 54
# 8 40
# 16 50
# 24 60
# This works (but isn't the general solution I'm looking for)
rr1 <- t(t(ff) * bb[1,])
rr2 <- t(t(ff) * bb[2,])
rbind(rr1,rr2)
# [,1] [,2]
# [1,] 7 36
# [2,] 14 45
# [3,] 21 54
# [4,] 8 40
# [5,] 16 50
# [6,] 24 60
# This produces the right numbers but swaps the off-diagonal blocks. Why?
apply(bb, MARGIN=1, function(x,y) t(t(y) * x), y=ff)
# [,1] [,2]
# [1,] 7 8
# [2,] 14 16
# [3,] 21 24
# [4,] 36 40
# [5,] 45 50
# [6,] 54 60
# Other formulations like these don't make a difference
apply(bb, MARGIN=2, function(x,y) t(t(y) * as.vector(t(x))), y=ff)
apply(bb, MARGIN=2, function(x) t(t(ff) * x))