What is lapply() function?

lapply() function is useful for performing operations on list objects and returns a list object of same length of original set. lappy() returns a list of the similar length as input list object, each element of which is the result of applying FUN to the corresponding element of list. Lapply in R takes list, vector or data frame as input and gives output in list.

**lapply(X, FUN) **
Arguments:
** -X: A vector or an object **
-FUN: Function applied to each element of x

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

lapply() function does not need MARGIN.

A very easy example can be to change the string value of a matrix to lower case with tolower function. We construct a matrix with the name of the famous movies. The name is in upper case format.

movies ← c(“SPYDERMAN”,“BATMAN”,“VERTIGO”,“CHINATOWN”)
movies_lower <-lapply(movies, tolower)
str(movies_lower)

Output:

List of 4 ## $:chr"spyderman" ## $:chr"batman" ## $:chr"vertigo" ## $:chr"chinatown"

We can use unlist() to convert the list into a vector.

movies_lower <-unlist(lapply(movies,tolower)) str(movies_lower)

Output:

## chr [1:4] “spyderman” “batman” “vertigo” "chinatown"

l in lapply() stands for list. The difference between lapply() and apply() lies between the output return. The output of lapply() is a list. lapply function takes list, vector or Data frame as input and returns only list as output.

The lapply() stands for the list and applies functions to a the elements of the input and the output is mostly a list which is used for objects like dataframes and lists.

Screenshot 2021-07-26 at 9.16.04 PM