【问题标题】:Find the most frequent element in the row with lists in R在R中的列表中查找行中最频繁的元素
【发布时间】:2020-08-20 14:09:54
【问题描述】:

我有如下数据表:

n    col1
1    c('1', '1', '2')
2    1
3    c('3', '3', '1')
4    3

作为输出,我只想让每行中出现频率最高的字符。所以,它会是这样的:

 n    col2
 1    1
 2    1
 3    3
 4    3

我真的不知道如何在 R 中解决这个问题。它应该类似于在列表中找到最常见的值。我用谷歌搜索有 table() 函数,但我不知道我应该如何在这里使用它。看起来并不难,但我就是想不通

【问题讨论】:

    标签: r list vector datatable


    【解决方案1】:

    我们可以从这里使用Mode

    Mode <- function(x) {
      ux <- unique(x)
      ux[which.max(tabulate(match(x, ux)))]
    }
    
    df1$col2 <- sapply(df1$col1, Mode)
    df1$col2
    #[1] "1" "1" "3" "3"
    

    tidyverse

    library(dplyr)
    library(purrr)
    df1 %>%
        transmute(n, col2 = map_chr(col1, Mode))
    

    数据

    df1 <- data.frame(n = 1:4, col1 = I(list(c('1', '1', '2'), '1', 
          c('3', '3', '1'), '3')))
    

    【讨论】:

    • 谢谢!我只试过Mode,效果很好
    猜你喜欢
    • 1970-01-01
    • 2022-08-16
    • 1970-01-01
    • 1970-01-01
    • 2021-12-09
    • 2015-10-08
    • 2018-10-01
    • 2013-06-25
    • 1970-01-01
    相关资源
    最近更新 更多