lapply() Function in R: How to Use lapply() Method

The apply() function is bundled with the R package. The apply() function can be feed with many functions to perform repetitive operations on a collection of objects (data frame, list, vector, etc.).

The apply() functions form the basis of more complex combinations and helps to perform operations with very few lines of code. More specifically, the family is made up of the apply(), lapply(), sapply(), vapply(), mapply(), rapply(), and tapply() functions. In this post, we will see the R lapply() function.

lapply() Function in R

To apply a given function to every element of a list and obtain a list, use the lapply() function. The lapply() function returns the list of the same length as input, each element of which is the result of applying a function to the corresponding item of X.

Syntax

lapply(X, FUN)

Parameters

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

Example

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

Output

RScript Pro.R
List of 4
$ : chr "titanic"
$ : chr "batman"
$ : chr "venom"
$ : chr "conjuring"
NULL

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

The l in lapply() function holds for the list. The difference between lapply() and apply()  function lies between the output return. The output of lapply() is a list. lapply() can be used for other objects like data frames and lists. The lapply() function does not need MARGIN.

Leave a Comment