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.
- X: A vector or an object.
- FUN: Function applied to each element of X.
movies <- c("Titanic", "BATMAN", "Venom", "Conjuring") movies_lower <- lapply(movies, tolower) print(str(movies_lower))
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.