Group Summaries
Part of the Logic & Flow section of Coddy's R journey. Lesson 40 of 64.
tapply(values, groups, f) groups the values and applies f to every group in one call. It gives the same result as sapply(split(values, groups), f):
amounts <- c(10, 20, 30, 40)
category <- c("food", "rent", "food", "fun")
print(tapply(amounts, category, sum))
print(tapply(amounts, category, max))Output:
food fun rent
40 40 20
food fun rent
30 40 20 The result is named by group in sorted order, so [[ ]] reads one group and names() lists them:
amounts <- c(10, 20, 30, 40)
category <- c("food", "rent", "food", "fun")
avg <- tapply(amounts, category, mean)
print(avg[["food"]])
print(names(avg))Output:
[1] 20
[1] "food" "fun" "rent"The summary function can be your own. Here it counts the orders above 25 in each group:
amounts <- c(10, 20, 30, 40)
category <- c("food", "rent", "food", "fun")
print(tapply(amounts, category, function(v) sum(v > 25)))Output:
food fun rent
1 1 0 The result is a named vector, so sort() and which.max() find the biggest group. which.max() gives the first of equal values:
amounts <- c(10, 20, 30, 40, 5)
category <- c("food", "rent", "food", "fun", "rent")
totals <- tapply(amounts, category, sum)
print(names(totals)[which.max(totals)])
print(names(sort(totals, decreasing = TRUE)))Output:
[1] "food"
[1] "food" "fun" "rent"Challenge
EasyComplete city_report(cities, temps). Return one line per city in alphabetical order, oslo: avg 4.5, max 9, with the mean temperature rounded to one decimal and the highest temperature. Then add Warmest: followed by the city with the highest mean (the alphabetically first one when means tie).
The supplied code reads the cities and the temperatures as two comma-separated lines of equal length and prints each returned line.
Try it yourself
city_report <- function(cities, temps) {
# Write your code here
character(0)
}
# Supplied input/output code: keep it as it is
input <- suppressWarnings(readLines(file("stdin")))
cat(city_report(strsplit(input[1], ",")[[1]], as.numeric(strsplit(input[2], ",")[[1]])), sep = "\n")
This lesson includes a short quiz. Start the lesson to answer it and track your progress.
All lessons in Logic & Flow
1Strings In Depth
Substrings with substr()Formatting with sprintf()Splitting and JoiningSearching StringsReplacing TextRecap - Username Builder4Matrices
Creating MatricesIndexing MatricesRow and Column SummariesMatrix ArithmeticRecap - Seating Chart2Key-Value Lookups
Named Vector LookupsChecking KeysAdding and Removing KeysLooping Over NamesRecap - Stock Desk8Sorting and Grouping
Sorting VectorsSorting by a KeyGrouping with split()Group SummariesRecap - Leaderboard3Sets and Counting
Unique ValuesSet OperationsMembership TestsCounting with table()Recap - Event Guests6Functions as Values
Anonymous FunctionsPassing FunctionsReturning FunctionsClosures with StateRecap - Discount Rules9Data Frames
Creating Data FramesColumns and RowsFiltering RowsAdding and SortingRecap - Sales Report12Project - Expense Tracker
Recording ExpensesTotal SpendingPractice on your own: Online R compiler