样本数据:
set.seed(1) ; x <- array(rnorm(2*3*5), dim = c(2, 3, 5))
# , , 1
#
# [,1] [,2] [,3]
# [1,] -0.6264538 -0.8356286 0.3295078
# [2,] 0.1836433 1.5952808 -0.8204684
#
# , , 2
#
# [,1] [,2] [,3]
# [1,] 0.4874291 0.5757814 1.5117812
# [2,] 0.7383247 -0.3053884 0.3898432
#
# , , 3
#
# [,1] [,2] [,3]
# [1,] -0.6212406 1.12493092 -0.01619026
# [2,] -2.2146999 -0.04493361 0.94383621
#
# , , 4
#
# [,1] [,2] [,3]
# [1,] 0.8212212 0.9189774 0.07456498
# [2,] 0.5939013 0.7821363 -1.98935170
#
# , , 5
#
# [,1] [,2] [,3]
# [1,] 0.61982575 -0.1557955 -0.4781501
# [2,] -0.05612874 -1.4707524 0.4179416
然后排列维度,apply()
identity
(或者,等价地,as.vector
甚至c
, see ?apply
) 到第三维并转置:
res <- t(apply(aperm(x, c(3, 2, 1)), 1, identity))
# [,1] [,2] [,3] [,4] [,5] [,6]
# [1,] -0.6264538 -0.8356286 0.32950777 0.18364332 1.59528080 -0.8204684
# [2,] 0.4874291 0.5757814 1.51178117 0.73832471 -0.30538839 0.3898432
# [3,] -0.6212406 1.1249309 -0.01619026 -2.21469989 -0.04493361 0.9438362
# [4,] 0.8212212 0.9189774 0.07456498 0.59390132 0.78213630 -1.9893517
# [5,] 0.6198257 -0.1557955 -0.47815006 -0.05612874 -1.47075238 0.4179416
同样,根据 @Frank 的建议:res <- matrix(aperm(x, c(3, 2, 1)), dim(x)[3])
Finally:
desired_output <- cbind(x[1,1,],x[1,2,],x[1,3,],x[2,1,],x[2,2,], x[2,3,])
all.equal(res, desired_output)
# [1] TRUE