I need to make a matrix in R
with its elements are from matrices I defined before.
For example, I have 4 matrices,
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)
Then, the new matrix should be a 4X4
matrix with w
is an [1:2,1:2]
element, x
is an [1:2,3:4]
element, y
is an [3:4,1:2]
element, and z
is an [3:4,3:4]
element.
How can I do that quickly?
We can create an array
and then loop through the third dimension, and rbind
it.
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
Or as @thelatemail mentioned in the comments
apply(array(c(w,x,y,z), dim=c(2,4,2)), 2, I)
where I
stands for inhibit interpretation
or use identity
in place of I