如何在R中取数组中所有元素的矩阵积?我搜索了stack exchange,没有找到任何结果。
n <- 3
ARRAY <- array(NA, dim = c(4, 4, n))
for (i in 1:4) {
for (j in 1:4) {
ARRAY[i, j, ] <- rnorm(n)
}
}
# this gives me a 1x1 matrix, which is wrong
Reduce("%*%", ARRAY)
mapply("%*%", ARRAY[,,1], ARRAY[,,2])
# this works, but I'd like a generalizable option
ARRAY[,,1]%*%ARRAY[,,2]%*%ARRAY[,,3]
我们可以使用asplit将第三维拆分为list
,然后使用Reduce
out2 <- Reduce(`%*%`, asplit(ARRAY, 3))
测试
> out1 <- ARRAY[,,1]%*%ARRAY[,,2]%*%ARRAY[,,3]
> identical(out1, out2)
[1] TRUE
Or也可以循环最后一个dim
序列,提取list
中的元素
out2 <- Reduce("%*%", lapply(seq(dim(ARRAY)[3]), function(i) ARRAY[,, i]))
或者也可以从purrr
使用array_branch
library(purrr)
library(magrittr)
out3 <- array_branch(ARRAY, 3) %>%
reduce(`%*%`)
> identical(out1, out3)
[1] TRUE