The lapply() function in R is used to apply a function to each element of a list or vector and returns the results in a list.
This function is beneficial because it abstracts away the need for explicit loop constructs and is often more efficient.
Syntax
lapply(X, FUN)
Parameters
- X: It is a list object.
- FUN: Function applied to each element of X.
Example 1: Basic usage
main_list <- list(
A = c(1, 2, 3),
B = c(4, 5, 6),
C = c(7, 8, 9)
)
result <- lapply(main_list, sum)
print(result)
Output
Example 2: Applying a custom function to a list
main_list <- list(
A = c(1, 2, 3),
B = c(4, 5, 6),
C = c(7, 8, 9)
)
main_function <- function(x) {
return(sum(x) / length(x))
}
result <- lapply(main_list, main_function)
print(result)
Output
Example 3: Nested Lists
If your list contains other lists (nested lists), lapply() will still treat each top-level element as a single unit.
nested_list <- list(
numbers = c(1, 2, 3),
letters = c("a", "b", "c"),
inner_list = list(one = 1, two = 2)
)
result <- lapply(nested_list, length)
print(result)
Output
In this example, the lapply() function returns the length of each top-level element in nested_list.
Remember, lapply() always returns a list. If you need a vector, you can use unlist().
If you need a data frame, you can use as.data.frame() function.
Example 4: Use lapply() function with data frame
df <- data.frame(
col1 = c(1, 2, 3),
col2 = c(4, 5, 6),
col3 = c(7, 8, 9)
)
result <- lapply(df, mean)
print(result)
Output
Difference between lapply() and sapply()
While lapply() always returns a list, there’s a similar function called sapply() which tries to simplify the result to a vector or matrix if possible. Use lapply() to ensure the result is always a list.
Related posts
Krunal Lathiya is a seasoned Computer Science expert with over eight years in the tech industry. He boasts deep knowledge in Data Science and Machine Learning. Versed in Python, JavaScript, PHP, R, and Golang. Skilled in frameworks like Angular and React and platforms such as Node.js. His expertise spans both front-end and back-end development. His proficiency in the Python language stands as a testament to his versatility and commitment to the craft.