[R] subsetting a list of matrices

Sundar Dorai-Raj sundar.dorai-raj at pdf.com
Tue Feb 28 18:37:09 CET 2006



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
> 

Try:

x <- matrix(1:6, 3, 2)
y <- matrix(18:35, 3, 6)
z <- list(x = x, y = y)
lapply(z, "[", 2:3, TRUE)

or

lapply(z, "[", 2:3, TRUE, drop = FALSE)

to prevent "[" from dropping the dim attribute. The latter is only 
required if

x <- matrix(1:2, 2, 1)

for example.


HTH,

--sundar




More information about the R-help mailing list