Apply Functions

sapply

sapply will function identically to lapply unless the output can be simplified, in which case sapply executes that simplification. The following occurs when we run sapply in place of lapply on our squares vector.

Examples

Use the sapply function to run this function to find the average number of stars for each company.

myavgstars <- function(company) {
    file_path <- paste0("/anvil/projects/tdm/data/icecream/", company, "/reviews.csv")
    reviews <- read.csv(file_path)
    avg_stars <- mean(reviews$stars, na.rm = TRUE)
    return(avg_stars)
}

mycompanies <- c("bj", "breyers", "hd", "talenti")
Click to see solution
myavgstars <- function(company) {
    file_path <- paste0("/anvil/projects/tdm/data/icecream/", company, "/reviews.csv")
    reviews <- read.csv(file_path)
    avg_stars <- mean(reviews$stars, na.rm = TRUE)
    return(avg_stars)
}

mycompanies <- c("bj", "breyers", "hd", "talenti")

avg_stars_per_company <- sapply(mycompanies, myavgstars)
avg_stars_per_company
bj
    4.3058038524487
breyers
    4.02796085480328
hd
    4.21847475832438
talenti
    4.31162447775866