【问题标题】:How to find mode of a column values for another column in R? [duplicate]如何查找 R 中另一列的列值的模式? [复制]
【发布时间】: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))

这不起作用,因为类型列不是数字。

【问题讨论】:

    标签: r mode


    【解决方案1】:

    考虑通过用matching 索引替换数值索引上的tabulateing 来更改mode 函数

    mode <- function(x) {
        ux <- unique(x)
        ux[which.max(tabulate(match(x, ux)))]
        }
    

    或者另一种选择是转换为factor,因为tabulate 需要numericfactor 输入

    mode <- function(x, lvls) {
        ux <- lvls
        ux[which.max(tabulate(factor(x, levels = ux)))]
        }
    

    现在,将它应用到组上

    df %>%
      group_by(year) %>%
      summarise(mode = mode(type, lvls = c('star', 'circle', 'triangle')))
     
    # A tibble: 2 x 2
    #  year  mode  
    #* <chr> <chr> 
    #1 2020  circle
    #2 2021  star
    

    数据

    df <- structure(list(year = c("2020", "2020", "2020", "2020", "2021", 
    "2021", "2021", "2021"), type = c("circle", "circle", "triangle", 
    "star", "circle", "triangle", "star", "star")), class = "data.frame",
    row.names = c(NA, 
    -8L))
    

    【讨论】:

    • 感谢您的回答!它主要适用于我的情况,但是对于一年中相同数量的类型,它没有给出正确的输出,正如我在问题星 > 圆 > 三角形中提到的那样。你能帮忙吗?
    • @solo 试试更新功能
    • 成功了!干得好!
    猜你喜欢
    • 1970-01-01
    • 2021-09-30
    • 2019-08-22
    • 1970-01-01
    • 1970-01-01
    • 2021-09-13
    • 1970-01-01
    • 2017-01-16
    • 1970-01-01
    相关资源
    最近更新 更多