[R] splitting and stacking matrices
Darcy Webber
darcy.webber at gmail.com
Tue Mar 1 22:55:27 CET 2011
Dear R users,
I am having some difficulty arranging some matrices and wondered if
anyone could help out. As an example, consider the following matrix:
a <- matrix(1:32, nrow = 4, ncol = 8)
a
[,1] [,2] [,3] [,4] [,5] [,6] [,7] [,8]
[1,] 1 5 9 13 17 21 25 29
[2,] 2 6 10 14 18 22 26 30
[3,] 3 7 11 15 19 23 27 31
[4,] 4 8 12 16 20 24 28 32
I would like it to look like the following matrix:
[,1] [,2] [,3] [,4]
[1,] 1 5 9 13
[2,] 2 6 10 14
[3,] 3 7 11 15
[4,] 4 8 12 16
[5,] 17 21 25 29
[6,] 18 22 26 30
[7,] 19 23 27 31
[8,] 20 24 28 32
I can achieve this using the following:
a1 <- a[, 1:4]
a2 <- a[, 5:8]
b <- rbind(a1, a2)
However, my initial matrix often has a varibale number of columns (in
multiples of 4, and I still want to split the columns into blocks of 4
and stack these). I have considered working out how many blocks the
matrix must be split into using: no.blocks <- ncol(a)/4. My problem is
then implementing this information to actually split the matrix up and
then stack it. Any guidance on this would be much appreciated.
Regards
Darcy Webber
More information about the R-help
mailing list