我有一个由12个矩阵组成的数组:
ma = array(sample(0:127,3*4*6,replace=TRUE), c(3,4,12))
让它们命名为A,B,C ...... L
我想创建一个矩阵,其上面的矩阵以4rows * 3列模式排列:
ABC
DEF
GHI
JKL
因此最终矩阵将有12列和12列。
我可以按照以下代码执行此操作:
rbind(cbind(m[,,1],m[,,2],m[,,3]),
cbind(m[,,4],m[,,5],m[,,6]),
cbind(m[,,7],m[,,8],m[,,9]),
cbind(m[,,10],m[,,11],m[,,12]))
但我无法为此编写通用函数:
matbinder(ma,n)
其中ma
是输入矩阵数组,n
是要放在一行中的初始矩阵数(在本例中为3)。
答案 0 :(得分:3)
我将它用作样本矩阵,因为它将按照您喜欢的顺序包含所有字母
ma = array(as.vector(t(outer(letters[1:12],1:12, FUN=paste0))), c(3,4,12))
然后你可以像
那样进行转换a<-ma
dim(a) <- c(3,12,4)
apply(a,2,c)
产生
[,1] [,2] [,3] [,4] [,5] [,6] [,7] [,8] [,9] [,10] [,11] [,12]
[1,] "a1" "a4" "a7" "a10" "b1" "b4" "b7" "b10" "c1" "c4" "c7" "c10"
[2,] "a2" "a5" "a8" "a11" "b2" "b5" "b8" "b11" "c2" "c5" "c8" "c11"
[3,] "a3" "a6" "a9" "a12" "b3" "b6" "b9" "b12" "c3" "c6" "c9" "c12"
[4,] "d1" "d4" "d7" "d10" "e1" "e4" "e7" "e10" "f1" "f4" "f7" "f10"
[5,] "d2" "d5" "d8" "d11" "e2" "e5" "e8" "e11" "f2" "f5" "f8" "f11"
[6,] "d3" "d6" "d9" "d12" "e3" "e6" "e9" "e12" "f3" "f6" "f9" "f12"
[7,] "g1" "g4" "g7" "g10" "h1" "h4" "h7" "h10" "i1" "i4" "i7" "i10"
[8,] "g2" "g5" "g8" "g11" "h2" "h5" "h8" "h11" "i2" "i5" "i8" "i11"
[9,] "g3" "g6" "g9" "g12" "h3" "h6" "h9" "h12" "i3" "i6" "i9" "i12"
[10,] "j1" "j4" "j7" "j10" "k1" "k4" "k7" "k10" "l1" "l4" "l7" "l10"
[11,] "j2" "j5" "j8" "j11" "k2" "k5" "k8" "k11" "l2" "l5" "l8" "l11"
[12,] "j3" "j6" "j9" "j12" "k3" "k6" "k9" "k12" "l3" "l6" "l9" "l12"
这是有效的,因为通过翻转尺寸,我们基本上构建了一个3 * 12矩阵的4个元素数组,它对应于我们想要的行。然后我们使用apply来折叠额外的维度。
通用matbinder(ma,n)
函数看起来像
matbinder <- function(ma,n) {
d<-dim(ma)
r<-ceiling(d[3]/n)
a<-c(ma, rep(NA, (n*r-d[3]) * prod(d[1:2])))
dim(a)<-c(d[1], n*d[2],r)
apply(a,2,c)
}
答案 1 :(得分:0)
利用我有限的知识,我管理了以下代码:
matbinder2 = function(submat, mats_per_row){
submat_dims = dim(submat)
submatr = submat_dims[1]
submatc = submat_dims[2]
submatn = submat_dims[3]
matc = submatc*mats_per_row
matr = submatr* ceiling(submatn/mats_per_row)
mat = array(NA, c(matr,matc))
for(m in 1:submatn){
r = 1+(floor(submatc*(m-1)/matc))*submatr
c = 1+((submatc*(m-1))%%matc)
i=1;j=1;k=0;l=0;
while(TRUE){
mat[r+l,c+k] = submat[i,j,m]
j=j+1; k=k+1;
if(j>submatc){j=1;k=0; i=i+1;l=l+1;if(i>submatr){break;}}
}
}
mat
}