【发布时间】:2021-06-02 10:10:51
【问题描述】:
我在 R 中有一个示例数据。
df <- data.frame(year = c("2020", "2020", "2020", "2020", "2021", "2021", "2021", "2021"), type = c("circle", "circle", "triangle", "star", "circle", "triangle", "star"))
我需要找到每年的类型。如果类型列在一年中具有相同数量的值,则模式偏好将如下所示:星形 > 圆形 > 三角形。
所以我想要的输出是:
2020 年:“圆”,
2021 年:“明星”
我正在尝试类似的事情:
mode <- function(codes){
which.max(tabulate(codes))
}
mds <- df %>%
group_by(year) %>%
summarise(mode = mode(type))
这不起作用,因为类型列不是数字。
【问题讨论】: