我有一个dim = c(2,2,64)的数组,我想把它变成一个dim = c(16,16)的矩阵。我需要填充矩阵的顺序是按行和列排列数组的3d维度,而不更改行或列元素的顺序。
data1<-matrix(seq(1:4),2,2,byrow=TRUE)
data1
[,1] [,2]
[1,] 1 2
[2,] 3 4
data2<-matrix(c(5,6,7,8),2,2,byrow=TRUE)
data2
[,1] [,2]
[1,] 5 6
[2,] 7 8
data3<-matrix(c(9,10,11,12),2,2,byrow=TRUE)
data3
[,1] [,2]
[1,] 9 10
[2,] 11 12
我想得到这样的东西,数组的下一个元素(data3)在第一列和新矩阵的3行等。
data.comp
[,1] [,2] [,3] [,4]
[1,] 1 2 5 6
[2,] 3 4 7 8
我尝试过将aperm和abind命令组合在一起,但无法弄明白。 有没有办法不使用循环?
答案 0 :(得分:0)
一种方法,如下:
你几乎有这样的事情:
#I am following your example but I am using 4 2x2 matrices
#in order to make it work
ar <- array(NA, c(2,2,4))
#too lazy to write a loop...
ar[,,1] <- data1
ar[,,2] <- data2
ar[,,3] <- data3
ar[,,4] <- data4
这样做的一种方法是:
#initiate two vectors which will host
#columns 1:2 and 3:4
temp_mat1 <- c()
temp_mat2 <- c()
for(i in 1:dim(ar)[3]){
if(i%%2==0) {
#if i is even create columns 3:4
temp_mat1 <- rbind(temp_mat1, ar[,,i])
}else{
#if i is odd create columns 1:2
temp_mat2 <- rbind(temp_mat2, ar[,,i])
}
}
#then column bind them together
cbind(temp_mat2, temp_mat1)
输出:
> cbind(temp_mat2, temp_mat1)
[,1] [,2] [,3] [,4]
[1,] 1 2 5 6
[2,] 3 4 7 8
[3,] 9 10 13 14
[4,] 11 12 15 16