How to Use lapply, sapply and mapply in R

Channel:
Subscribers:
53,300
Published on ● Video Link: https://www.youtube.com/watch?v=34sbvhr_pm8



Category:
Tutorial
Duration: 7:45
31,150 views
799


This video shows how to use the lapply, sapply and mapply functions to execute a function on each element of a list or vector in R. The apply family of functions provide a convenient way to quickly invoke a function on each element of vectors without having to write custom for loops.

Note that since data frames are lists where each column are separate elements of the list, the lapply and sapply will apply a function to each column when run on a data frame. This provides a quick way to create column-based summary statistics.

Code used in this clip:

# Example of lapply
data <- mtcars

# Function to apply
mpg_category <- function(mpg){
if(mpg > 30){
return("High")
} else if (mpg > 20){
return("Medium")
}
return("Low")
}

# Apply to each element
lapply(X = data$mpg, FUN = mpg_category)

# Use sapply to simplify the result to a vector or matrix instead of a list
sapply(X = data$mpg, FUN = mpg_category)

# You can pass additional arguments after FUN

within_range <- function(mpg, low, high){
if (mpg >= low & mpg <= high){
return(TRUE)
}
return(FALSE)
}

index <- sapply(X = data$mpg, FUN = within_range, low = 15, high = 20)
index

data[index,]

# Use mapply to apply a function along multiple vectors at the same time

# Function to apply
mpg_within_standard_range <- function(mpg, cyl){
if (cyl == 4){
return(within_range(mpg, low = 23, high = 31))
} else if (cyl == 6) {
return(within_range(mpg, low = 18, high = 23))
}
return(within_range(mpg, low = 13, high = 18))
}

index <- mapply(FUN = mpg_within_standard_range, mpg = data$mpg, cyl = data$cyl)
index

data[!index,]

# When used on a dataframe, lapply and sapply apply a function to each column

sapply(data, FUN = median)



* Note: YouTube does not allow greater than or less than symbols in the text description, so the code above will not be exactly the same as the code shown in the video! For R that means I may use = for assignment and the special Unicode large < and > symbols in place of the standard sized ones for dplyr pipes and comparisons. These special symbols should work as expected for R code on Windows, but may need to be replaced with standard greater than and less than symbols for other operating systems.







Tags:
lapply
sapply
mapply
apply family in R
lapply function in r
sapply function in r
mapply function in r
apply a function to a list
apply family of functions
lapply()
sapply()
mapply()
sapply in r
lapply in r
mapply in r
r mapply
r sapply
r lapply
how to use sapply
how to use mapply
how to use lapply
how to use sapply()
how to use mapply()
how to use lapply()
r tutorial
r programming
use mapply
use sapply
use lapply
lapply r
sapply r
mapply r