从R中的子矩阵创建矩阵

时间:2016-05-05 05:55:54

标签: r matrix submatrix

我需要在R中创建一个矩阵,其元素来自我之前定义的矩阵。 例如,我有4个矩阵,

w <- matrix(c(1,2,3,4),2,2)
x <- matrix(c(5,6,7,8),2,2)
y <- matrix(c(9,10,11,12),2,2)
z <- matrix(c(13,14,15,16),2,2)

然后,新矩阵应为4X4矩阵,w[1:2,1:2]元素,x[1:2,3:4]元素,{{1} }是y元素,[3:4,1:2]z元素。

我怎样才能快速完成?

1 个答案:

答案 0 :(得分:4)

我们可以创建一个array,然后遍历第三维,并rbind

ar1 <- array(c(w, x, y,z), dim=c(2, 4,2))
do.call(rbind,lapply(seq(dim(ar1)[3]), function(i) ar1[,,i]))
#     [,1] [,2] [,3] [,4]
#[1,]    1    3    5    7
#[2,]    2    4    6    8
#[3,]    9   11   13   15
#[4,]   10   12   14   16

或者@thelatemail在评论中提到

apply(array(c(w,x,y,z), dim=c(2,4,2)), 2, I)

其中I代表inhibit interpretation或使用identity代替I

相关问题