Menu
CoddyTech

使用 table() 计数

本课属于 Coddy R 学习旅程的“逻辑与流程”单元。第 15 课,共 64 课。

table(x)会统计每个值出现的次数。结果以各个值命名,并按字母顺序排序,因此某个值的计数是 t[["value"]]:

votes <- c("tea", "coffee", "tea", "juice", "tea")
t <- table(votes)
print(t[["tea"]])
print(names(t))
print(as.vector(t))

输出:

[1] 3
[1] "coffee" "juice"  "tea"   
[1] 1 1 3

sort(t, decreasing = TRUE)会按计数从高到低排序。which.max(t)会给出最大计数的位置;如果计数相同,它会选择第一个,也就是按字母顺序排在最前的值:

votes <- c("tea", "coffee", "tea", "juice", "coffee")
t <- table(votes)
print(names(t)[which.max(t)])
print(max(t))

输出:

[1] "coffee"
[1] 2

从未出现过的值不会在表格中出现,因此在读取前使用 %in% names(t) 检查:

t <- table(c("A", "B", "A"))
for (grade in c("A", "B", "C")) {
  n <- if (grade %in% names(t)) t[[grade]] else 0
  cat(grade, n, "\n")
}

输出:

A 2 
B 1 
C 0 

table() 也会统计数字和逻辑值。要统计单个值,sum(x == value) 比创建表更简短:

rolls <- c(6, 2, 6, 6, 1)
print(sum(rolls == 6))
print(table(rolls > 3)[["TRUE"]])

输出:

[1] 3
[1] 3
challenge icon

挑战

简单

完成 vote_winner(votes)。返回得票最多的选项及其票数,如 tea (3 votes) 所示。如果多个选项得票数相同,则返回按字母顺序排在最前面的选项。

提供的代码会读取一行以逗号分隔的选票,并打印返回值。

亲手试试

vote_winner <- function(votes) {
  # 在这里编写你的代码
  ""
}

# 提供的输入和输出代码:保持原样
input <- suppressWarnings(readLines(file("stdin")))
cat(vote_winner(strsplit(input[1], ",")[[1]]), sep = "\n")
quiz icon自我测试

这节课包含一个小测验。开始学习即可作答,并记录你的进度。

逻辑与流程中的所有课

自己练习: R 在线编译器