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.
word_lengths(words): the number of characters in each word.mean_by_region(sales): the meanamountfor each region, withtapply.totals: a data frame of the totalamountper region, withaggregate.