Lesson 7 of 8 · 11 min

sapply and grouped summaries

sapply: a function for every item

sapply calls a function on each element and collects the results into a vector:

squares <- sapply(1:5, function(n) n ^ 2)       # 1 4 9 16 25
sapply(c("a", "bb"), nchar, USE.NAMES = FALSE)  # 1 2

lapply does the same but always returns a list (useful when results have different shapes). Many built-in functions are already vectorised (like nchar(words)), so try that first.

tapply: summarise by group

tapply(values, groups, function) splits the values by group and applies the function to each group:

rainfall <- c(30, 50, 10, 70)
season   <- c("dry", "wet", "dry", "wet")
tapply(rainfall, season, mean)
#  dry wet
#   20  60

aggregate: the same, as a data frame

aggregate with a formula reads naturally: "amount, grouped by region".

aggregate(amount ~ region, data = sales, FUN = sum)

The result is a data frame, ready for sorting, plotting or joining. Grouping and summarising like this is the bread and butter of data analysis (the popular dplyr package does the same with group_by and summarise).

Your task

The starter has a sales data frame.

  1. word_lengths(words): the number of characters in each word.
  2. mean_by_region(sales): the mean amount for each region, with tapply.
  3. totals: a data frame of the total amount per region, with aggregate.
script.R
sales <- data.frame(
  region = c("North", "South", "East", "North", "East", "South"),
  amount = c(250, 100, 120, 150, 180, 80)
)

word_lengths <- function(words) {
}

mean_by_region <- function(sales) {
}

totals <- NULL

R 4.5 runs right here in your browser. The first run downloads about 25 MB; after that it is instant.

Discussion

Stuck? Ask here. Be kind, and share hints rather than full answers.

Loading the discussion…