How to Quickly Subset List Elements in R

Master R

By Guangming Lang Comment

Every operation in R is a function call. For example, when you subset a vector using [], you’re really calling the function [.

y = 1:6
y[2]
## [1] 2
`[`(y, 2)
## [1] 2

This allows us to easily subset the elements of a list when the elements are vectors. For example, given a list of 3 elements: a character vector, an integer vector, and a logical vector, we can use lapply and [ to easily extract the 2nd value from each vector.

x = list(letters[1:4], 1:5, c(T, F, T, F, F, T))
lapply(x, `[`, 2)
## [[1]]
## [1] "b"
## 
## [[2]]
## [1] 2
## 
## [[3]]
## [1] FALSE

To learn more, read the chapter on functions from Hadley’s book, Advanced R.

If you enjoyed this post, get updates. It's FREE