How to Use the lapply() Function in R

The lapply() function in R is “used to apply a function to a list, data frame or a vector, returning a list of the same length“.

Syntax

lapply(X, FUN)

Parameters

  1. X: A vector or an object.
  2. FUN: Function applied to each element of X.

Example 1: Iterate over a vector using the lapply() function

movies <- c("Titanic", "BATMAN", "Venom", "Conjuring")
movies_lower <- lapply(movies, tolower)

print(str(movies_lower)) 

Output

List of 4
$ : chr "titanic"
$ : chr "batman"
$ : chr "venom"
$ : chr "conjuring"
NULL

First, we defined a vector and used the lapply() function to convert all the elements to the small case.

Example 2: Iterate over a list using the lapply() function

list_new <- list(
  A = c(11, 19, 21, 46),
  B = data.frame(x = 1:5, y = c(1, 2, 3, 7, 8))
)

lapply(list_new, sum)

Output

$A
[1] 97

$B
[1] 36

Example 3: Use lapply() function with multiple arguments

list_new <- list(
  A = c(11, 19, 21, 46),
  B = c(1, 2, 3, 4)
)

lapply(list_new,
  quantile,
  probs = c(0.25, 0.50)
)

Output

$A
25% 50%
17 20

$B
25% 50%
1.75 2.50

Example 4: Use lapply() with a custom function

You can also apply a custom function with the “lapply()” function.

vec <- 1:3

# Function to calculate the third power
fun <- function(x) {
   x ^ 3
}

# Applying our own function
lapply(vec, fun)

Output

[[1]]
[1] 1

[[2]]
[1] 8

[[3]]
[1] 27

Further reading

sapply in r

apply in r

Leave a Comment