set.seed(4)
data <- array(rexp(12), dim=c(3,2,2))
, , 1
[,1] [,2]
[1,] 0.1716006 0.8026470
[2,] 4.3039449 0.6271484
[3,] 0.8681056 0.7348583
, , 2
[,1] [,2]
[1,] 0.44881179 0.8371497
[2,] 0.05069988 2.6802979
[3,] 0.50935005 0.2880769
我想获得一个像这样的[6,2]维度的数组:
, 1
[,1] [,2] [,3] [,4] [,5] [,6]
[1,] 0.1716006 0.8026470 4.3039449 0.6271484 0.8681056 0.7348583
, 2
[,1] [,2] [,3] [,4] [,5] [,6]
[1,] 0.44881179 0.8371497 0.05069988 2.6802979 0.50935005 0.2880769
我想用for循环来做这个,因为我的数组有[633,333,12]维,但是一切都很受欢迎。
答案 0 :(得分:2)
我们可以使用aperm
置换data
,我们会更改数组的第一维和第二维:
data <- aperm(data, perm = c(2, 1, 3))
data
#, , 1
#
# [,1] [,2] [,3]
#[1,] 0.1716006 4.3039449 0.8681056
#[2,] 0.8026470 0.6271484 0.7348583
#
#, , 2
#
# [,1] [,2] [,3]
#[1,] 0.4488118 0.05069988 0.5093501
#[2,] 0.8371497 2.68029789 0.2880769
现在使用dim<-
dim(data) <- c(1, 6, 2)
data
#, , 1
#
# [,1] [,2] [,3] [,4] [,5] [,6]
#[1,] 0.1716006 0.802647 4.303945 0.6271484 0.8681056 0.7348583
#
#, , 2
#
# [,1] [,2] [,3] [,4] [,5] [,6]
#[1,] 0.4488118 0.8371497 0.05069988 2.680298 0.5093501 0.2880769
答案 1 :(得分:1)
这会有用吗?
apply(data,3,c)
答案 2 :(得分:0)
选项可以使用data
的第三维作为:
sapply(1:dim(data)[3],function(x)t(data[,,x]))
# [,1] [,2]
# [1,] 0.1716006 0.44881179
# [2,] 0.8026470 0.83714966
# [3,] 4.3039449 0.05069988
# [4,] 0.6271484 2.68029789
# [5,] 0.8681056 0.50935005
# [6,] 0.7348583 0.28807690