我想在矩阵的一个边距(在我的示例中为列)上应用函数。问题在于该函数返回矩阵apply
并将其转换为向量,以便它返回矩阵。我的目标是获取三维数组。这是示例(请注意,这matrix()
不是感兴趣的功能,只是一个示例):
x <- matrix(1:12, 4, 3)
apply(x, 2, matrix, nrow = 2, ncol = 2)
输出与输入完全相同。我对此有很呆板的解决方案:
library(abind)
abind2 <- function (x, ...)
abind(x, ..., along = dim(x) + 1)
apply(x, 2, list) %>%
lapply(unlist) %>%
lapply(matrix, nrow = 2, ncol = 2) %>%
do.call(what = 'abind2')
我相信必须存在比这更好的东西。不包含list()
ing和unlist()
ing列的内容。
编辑:此外,该解决方案应该准备好可以轻松地应用于MARGIN
我的解决方案没有的任何选择的任何维数组。
例如,这要返回4维数组。
x <- array(1:24, c(4,3,2))
apply(x, 2:3, list) %>%
lapply(unlist) %>%
lapply(matrix, nrow = 2, ncol = 2) %>%
do.call(what = 'abind2')
一点也不复杂。只需使用
array(x, dim = c(2, 2, ncol(x)))
矩阵和常规数组按列存储到物理地址中的一维长数组中。您可以重新分配维度。
好的,一般来说,这可能是您想要做的事情:
tapply(x, col(x), FUN = matrix, nrow = 2, ncol = 2)
#$`1`
# [,1] [,2]
#[1,] 1 3
#[2,] 2 4
#
#$`2`
# [,1] [,2]
#[1,] 5 7
#[2,] 6 8
#
#$`3`
# [,1] [,2]
#[1,] 9 11
#[2,] 10 12
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句