[R] Extracting elements from a list

Gabor Grothendieck ggrothendieck at gmail.com
Sat Jul 14 15:04:08 CEST 2007


Use lapply or sapply:

> L <- list(a = 1:4, b = 11:15)
> lapply(L, "[[", 1)
$a
[1] 1

$b
[1] 11

> sapply(L, "[[", 1)
 a  b
 1 11

Also please see last line on every r-help message regarding providing
reproducible code.  Lst was not defined in your post.


On 7/14/07, Forest Floor <rhago at comcast.net> wrote:
> Hi,
>
> I would love an easy way to extract elements from a list.
>
> For example, if I want the first element from each of 10 arrays stored
> in a list,
>
> Lst[[1:10]][1,1]  seems like a logical approach, but gives this error:
> "Error: recursive indexing failed at level 3"
>
> The following workaround is functional but can get annoying/confusing.
>
> first.element=vector()
> for (i in 1:10){ first.element=c(first.element, Lst[[i]][1,1])  }
>
> Is there a better way to do this?   Thanks for any help!
>
> Jeff
>
> ______________________________________________
> R-help at stat.math.ethz.ch 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.
>



More information about the R-help mailing list