Formula Interfaces
Aggregate Formula
Response by Group
Many base R functions accept a formula. In score ~ group, the left side is summarized separately for each right-side group.
Program
Play the script to add a selected bonus, then summarize scores by group with formula syntax.
aggregate_formula.R
scores <- data.frame(group = c("A", "A", "B", "B"), score = c(8, 10, 6, 12))
bonus <-
scores$score <- scores$score + bonus
summary <- aggregate(score ~ group, data = scores, FUN = mean)
label <- paste(summary$group, summary$score, collapse = "; ")
cat(label, "\n", sep = "")
scores <- data.frame(group = c("A", "A", "B", "B"), score = c(8, 10, 6, 12))
bonus <-
scores$score <- scores$score + bonus
summary <- aggregate(score ~ group, data = scores, FUN = mean)
label <- paste(summary$group, summary$score, collapse = "; ")
cat(label, "\n", sep = "")
scores <- data.frame(group = c("A", "A", "B", "B"), score = c(8, 10, 6, 12))
bonus <-
scores$score <- scores$score + bonus
summary <- aggregate(score ~ group, data = scores, FUN = mean)
label <- paste(summary$group, summary$score, collapse = "; ")
cat(label, "\n", sep = "")
formula
`score ~ group` reads as summarize `score` by `group`.
aggregate
`aggregate(formula, data, FUN)` applies a summary to each group.
data argument
`data = scores` tells R where to find the formula names.