分组汇总
本课属于 Coddy R 学习旅程的“逻辑与流程”单元。第 40 课,共 64 课。
tapply(values, groups, f) 会对值进行分组,并在一次调用中对每个组应用 f。它的结果与 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))输出:
food fun rent
40 40 20
food fun rent
30 40 20 结果按分组名称排序,因此 [[ ]] 会读取一个分组,而 names() 会列出这些分组:
amounts <- c(10, 20, 30, 40)
category <- c("food", "rent", "food", "fun")
avg <- tapply(amounts, category, mean)
print(avg[["food"]])
print(names(avg))输出:
[1] 20
[1] "food" "fun" "rent"汇总函数可以由你自己定义。这里会统计每组中金额超过 25 的订单数量:
amounts <- c(10, 20, 30, 40)
category <- c("food", "rent", "food", "fun")
print(tapply(amounts, category, function(v) sum(v > 25)))输出:
food fun rent
1 1 0 结果是一个带名称的向量,因此 sort() 和 which.max() 可以找出最大的组。which.max() 会返回相同值中的第一个:
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)))输出:
[1] "food"
[1] "food" "fun" "rent"挑战
简单补全 city_report(cities, temps)。按字母顺序为每个城市返回一行,oslo: avg 4.5, max 9,其中包含四舍五入到小数点后一位的平均气温和最高气温。然后添加 Warmest: ,后面接平均气温最高的城市(如果平均气温相同,则选按字母顺序排在最前面的城市)。
提供的代码会读取两行逗号分隔且长度相同的城市和气温数据,并打印返回的每一行。
亲手试试
city_report <- function(cities, temps) {
# 在这里编写你的代码
character(0)
}
# 提供的输入和输出代码:保持原样
input <- suppressWarnings(readLines(file("stdin")))
cat(city_report(strsplit(input[1], ",")[[1]], as.numeric(strsplit(input[2], ",")[[1]])), sep = "\n")
这节课包含一个小测验。开始学习即可作答,并记录你的进度。
逻辑与流程中的所有课
自己练习: R 在线编译器