Using ‘[‘ square bracket as a function for lapply in R

The square brackets are in fact a function whose first argument is the object being subsetted. Subsequent arguments are the index to that subset.

# For example, if M is a matrix
M[1, 2]  # extracts the element at row 1, col 2
# is the same as 
`[`(M, 1, 2)
# Try them! 

Now, Have a look at the arguments to lapply:

args(lapply)
# function (X, FUN, ...) 

Everything represented in those dots gets passed on to the function FUN as arguments.

Thus, when FUN="[", the first argument to "[" is the current element of the list (being iterated over), ie, the object being subsetted. While the subsequent arguments are the indexes to "["

Leave a Comment