[R] splitting and stacking matrices

Gabor Grothendieck ggrothendieck at gmail.com
Tue Mar 1 23:56:40 CET 2011


On Tue, Mar 1, 2011 at 4:55 PM, Darcy Webber <darcy.webber at gmail.com> wrote:
> 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
>

Try converting to a 3d array, swapping the last two dimensions and
reconstituting it as a matrix:

> matrix(aperm(array(a, c(4, 4, 2)), c(1, 3, 2)), nc = 4)
     [,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



-- 
Statistics & Software Consulting
GKX Group, GKX Associates Inc.
tel: 1-877-GKX-GROUP
email: ggrothendieck at gmail.com



More information about the R-help mailing list