Question

I'm trying to extract rows from all the matrices in a list in R. Is there an easy way to do this other than looping? For e.g.,

set.seed(123)
list1 <- list(replicate(4,rnorm(2)))
rep(list1,3)

This code generates the following list:

[[1]]
           [,1]       [,2]      [,3]       [,4]
[1,] -0.5604756 1.55870831 0.1292877  0.4609162
[2,] -0.2301775 0.07050839 1.7150650 -1.2650612

[[2]]
           [,1]       [,2]      [,3]       [,4]
[1,] -0.5604756 1.55870831 0.1292877  0.4609162
[2,] -0.2301775 0.07050839 1.7150650 -1.2650612

[[3]]
           [,1]       [,2]      [,3]       [,4]
[1,] -0.5604756 1.55870831 0.1292877  0.4609162
[2,] -0.2301775 0.07050839 1.7150650 -1.2650612

Now I want to extract 2nd row of all the matrices in this list and store it in another matrix or list. Is there a way to do this without looping?

Thanks

Was it helpful?

Solution

Or like this?

set.seed(123)
list1 <- list(replicate(4,rnorm(2)))
l<-rep(list1,3)
lapply(l,function(x) x[2,])

OTHER TIPS

matrix(unlist(lapply(x,function (x) { x[2,]})),nrow=length(x), byrow=T)

           [,1]      [,2]       [,3]       [,4]
[1,] -0.2372892 0.8751748 -0.5452381 -0.1484494
[2,] -0.2372892 0.8751748 -0.5452381 -0.1484494
[3,] -0.2372892 0.8751748 -0.5452381 -0.1484494

This extracts the rows with lapply and puts them together with rbind.

x = rep(list1,3)
do.call( rbind, lapply(x,'[',2,) )

The plyr package is another option

library(plyr)
laply(x,function(y) y[2,])

The ?"[" help page is enlightening. After reading it, I realized the very short, simple code below also works.

laply(x,'[',2,TRUE)
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top