Site icon R-bloggers

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<-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"

To leave a comment for the author, please follow the link and comment on their blog: R – Predictive Hacks.

R-bloggers.com offers daily e-mail updates about R news and tutorials about learning R and many other topics. Click here if you're looking to post or find an R/data-science job.
Want to share your content on R-bloggers? click here if you have a blog, or here if you don't.