Re: [R] splitting and stacking matrices

From: Gabor Grothendieck <ggrothendieck_at_gmail.com>
Date: Tue, 01 Mar 2011 17:56:40 -0500

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

______________________________________________
R-help_at_r-project.org mailing list
https://stat.ethz.ch/mailman/listinfo/r-help
PLEASE do read the posting guide http://www.R-project.org/posting-guide.html
and provide commented, minimal, self-contained, reproducible code.
Received on Tue 01 Mar 2011 - 23:04:59 GMT

Archive maintained by Robert King, hosted by the discipline of statistics at the University of Newcastle, Australia.
Archive generated by hypermail 2.2.0, at Tue 01 Mar 2011 - 23:10:17 GMT.

Mailing list information is available at https://stat.ethz.ch/mailman/listinfo/r-help. Please read the posting guide before posting to the list.

list of date sections of archive