In R, lapply() and sapply() are two functions that are used to apply a function to each element of a list or vector. While both functions have similar functionality, there are some key differences between them.
The lapply() function stands for "list apply". It takes a list as input and applies a function to each element of the list, returning a list as output. The output list has the same length as the input list, and each element of the output list corresponds to the result of applying the function to the corresponding element of the input list. Here’s an example:
# Creating a list of numbers
my_list <- list(1, 2, 3, 4, 5)
# Applying the square root function to each element of the list
result <- lapply(my_list, sqrt)
# Displaying the result
result
In this example, the lapply() function applies the sqrt() function to each element of the my_list list, which contains the numbers 1 through 5. The resulting list, result, contains the square roots of each element of my_list.
The sapply() function stands for "simplified apply". It is similar to lapply(), but it tries to simplify the output to a vector or matrix if possible. If the output of the function applied to each element of the input list is a vector of the same length, sapply() will return a matrix with each element of the vector in a separate column. If the output of the function is a scalar value or a vector of different lengths, sapply() will return a vector. Here’s an example:
# Creating a list of numbers
my_list <- list(1, 2, 3, 4, 5)
# Applying the square root function to each element of the list
result <- sapply(my_list, sqrt)
# Displaying the result
result
In this example, the sapply() function applies the sqrt() function to each element of the my_list list, which contains the numbers 1 through 5. Since the output of the sqrt() function is a scalar value for each element of the list, sapply() returns a vector with the square roots of each element of my_list.
The main difference between lapply() and sapply() is that sapply() tries to simplify the output to a vector or matrix if possible, while lapply() always returns a list. This can be useful if you want to apply a function to a list and get a simplified output in some cases, but want to retain the list structure in others.
In summary, lapply() and sapply() are two functions in R that apply a function to each element of a list or vector. The main difference between them is that sapply() tries to simplify the output to a vector or matrix if possible, while lapply() always returns a list.