The “lapply” Function in R
Package: Base R (no specific package required)
Purpose: Applies a function to each element of a list and returns a list.
General Class: Data Manipulation
Required Argument(s):
X: A list or vector.
FUN: The function to apply to each element of X.
Notable Optional Arguments:
None
Example:
# Example data for using the lapply function
numbers <- list(a = 1, b = c(2, 3, 4), c = 5:7)
# Apply the sum function to each element of the list
result <- lapply(numbers, FUN = sum)
# Display the result
print(result)In this example, the lapply function is used to apply the sum function to each element of the numbers list. The resulting result list contains the sums of the elements in each sublist. Unlike sapply, lapply always returns a list, making it suitable when you want to maintain the structure of the input list. The lapply function is a powerful tool for applying a function to each element of a list and collecting the results in a new list.