R lapply() Function

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

  1. X: It is a list object.
  2. FUN: Function applied to each element of X.

Example 1: Basic usageFigure of using the lapply() function on a list

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

Output of using the lapply() function on a list

Example 2: Applying a custom function to a list

Figure of Applying a custom function to a list using lapply()

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

Output of Applying a custom function to a list using lapply()

Example 3: Nested Lists

If your list contains other lists (nested lists), lapply() will still treat each top-level element as a single unit.

Figure of using lapply() function on Nested Lists

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

Output of Nested Lists

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

Figure of using lapply() function on 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

Output of using lapply() function on data frame

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

R apply()

R rapply()

R tapply()

Leave a Comment