Using apply function over the row margin with expectation of stacked results

社会主义新天地 提交于 2020-01-25 08:34:29

问题


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))

来源:https://stackoverflow.com/questions/54538730/using-apply-function-over-the-row-margin-with-expectation-of-stacked-results

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!