Press "Enter" to skip to content

Hack: The ‘[‘ in R lists

[This article was first published on R – Predictive Hacks, and kindly contributed to R-bloggers]. (You can report issue about the content on this page here)


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

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"

Be First to Comment

Leave a Reply

Your email address will not be published.