The “sapply” Function in R
Package: Base R (no specific package required)
Purpose: Applies a function to each element of a list or vector and simplifies the result into an array, vector, or matrix.
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:
simplify: Logical; if TRUE, attempts to reduce the result to a simpler form.
USE.NAMES: Logical; if TRUE and X is a named vector or list, the names are used to name the result.
Example:
# Example data for using the sapply function
numbers <- list(a = 1, b = c(2, 3, 4), c = 5:7)
# Apply the sum function to each element of the list
result <- sapply(numbers, FUN = sum)
# Display the result
print(result)In this example, the sapply function is used to apply the sum function to each element of the numbers list. The resulting result vector contains the sums of the elements in each sublist. The sapply function is useful for simplifying the result into a more convenient format, such as a vector or matrix.