Want to share your content on R-bloggers? click here if you have a blog, or here if you don't.

Assume that you have a list and you want to get the n-th element of each component or generally to subset the list. You can use the command sapply(list, "[", c(1,2,3,..))

Let’s see this in practice.

mylist<-list(id<-1:10,
gender<-c("m","m","m","f","f","f","m","f","f","f"),
amt<-c(5,20,30,10,20,50,5,20,10,30)
)

mylist



Output:

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

[[2]]
[1] "m" "m" "m" "f" "f" "f" "m" "f" "f" "f"

[[3]]
[1]  5 20 30 10 20 50  5 20 10 30

Let’s say that we want to get the 3rd and 6th element of the list:

sapply(mylist, "[", c(3,6))



Output:

     [,1] [,2] [,3]
[1,] "3"  "m"  "30"
[2,] "6"  "f"  "50"