[R] subsetting a list of matrices

Marc Schwartz (via MN) mschwartz at mn.rr.com
Tue Feb 28 18:41:17 CET 2006


On Tue, 2006-02-28 at 17:14 +0000, Federico Calboli wrote:
> Hi All,
> 
> I have a list of matrices:
> 
> > x
>      [,1] [,2]
> [1,]    1    4
> [2,]    2    5
> [3,]    3    6
> > y
>      [,1] [,2] [,3] [,4] [,5] [,6]
> [1,]   18   21   24   27   30   33
> [2,]   19   22   25   28   31   34
> [3,]   20   23   26   29   32   35
> > z =list(x,y)
> 
> I want to create a second list that is has a subset each matrix in the
> list subsetting so I get the 2nd and 3rd row of each (and all columns).
> 
> How could I do that (apart from looping)?
> 
> Regards,
> 
> Federico Calboli


Here is one approach:

> lapply(z, function(x) x[2:3, ])
[[1]]
     [,1] [,2]
[1,]    2    5
[2,]    3    6

[[2]]
     [,1] [,2] [,3] [,4] [,5] [,6]
[1,]   19   22   25   28   31   34
[2,]   20   23   26   29   32   35


HTH,

Marc Schwartz




More information about the R-help mailing list