by Guangming Lang
~1 min read

Categories

  • r

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