The lapply() function is a very powerful tool for applying a function to a list of elements. It is a member of the apply family of functions in R, which also includes apply(), tapply(), and mapply().
The lapply() function takes three arguments:
- A list X
- A function (or the name of a function) FUN
- Other arguments via its ... argument.
If X is not a list, it will be coerced to a list using as.list().
The lapply() function then loops over the elements of X and applies the function FUN to each element. The output of lapply() is a list, with the same length as X, where each element is the output of FUN applied to the corresponding element of X.
The lapply() function is a very versatile tool, and can be used for a wide variety of tasks. For example, you can use lapply() to:
- Calculate the mean of each element in a list of vectors
- Apply a transformation to each element in a list of matrices
- Categorize each element in a list of strings
Note
- If you are using lapply() to apply a function to a list of vectors, you can use the sapply() function to simplify the output. The sapply() function will try to simplify the output of lapply() to a vector, matrix, or array.
- If you are using lapply() to apply a function to a list of matrices, you can use the mapply() function to apply the function to multiple matrices simultaneously. The mapply() function is similar to lapply(), but it allows you to specify multiple arguments to the function that is being applied.