How to subset from a list in R

user1257894 picture user1257894 · Mar 8, 2012 · Viewed 85.2k times · Source

I have a rather simple task but haven't find a good solution.

> mylist  
[[1]]
 [1]  1  2  3  4  5  6  7  8  9 10

[[2]]
 [1] "a" "b" "c" "d" "e" "f" "g" "h" "i" "j" "k" "l" "m" "n" "o" "p" "q" "r" "s" "t" "u" "v" "w" "x" "y" "z"

[[3]]
[1] 25 26 27 28 29 30 31 32

y <- c(3,5,9)    

I would like to extract from mylist the sub-elements 3,5, and 9 of each component in the list. I have tried, sapply[mylist,"[[",y] but not luck!, and others like vapply, lapply, etc.. Thanks in advance for your help

Mauricio Ortiz

Answer

sgibb picture sgibb · Mar 8, 2012

You could use sapply(mylist, "[", y):

mylist <- list(1:5, 6:10, 11:15)
sapply(mylist, "[", c(2,3))