【问题标题】:Get the first and second highest frequencies from multiple column从多列中获取第一和第二高频率
【发布时间】:2018-02-20 00:55:42
【问题描述】:

我有一个包含 52 行和 161 列的数据框。我已经给出了我的数据框的结构。

>str(CEPH)
'data.frame':   52 obs. of  161 variables:
$ id         : chr  "85" "86" "94" "00" ...
$ subgroup   : chr  "AAA" "AAA" "AAA" "AAA" ...
$ A1_A   : chr  "3:01" "3:01" "2:01" "2:01" ...
$ A1_B   : chr  "" "" "" "" ...
$ A2_A   : chr  "2:01" "32:01:01" "32:01:01" "68:01:02" ...
$ A2_B   : chr  "" "32:01:02" "32:01:02" "" ...
$ A2_C   : chr  "" "" "" "" ...
$ B1_A   : chr  "7:02:01" "44:03:01" "40:02:00" "44:02:00" ...
...

我在某些专栏中有更多的 NA。因此,我需要找到第一和第二高频率。我尝试了以下代码。但是有50多列。它不可能一一地通过列。有什么方法可以使用 sapply 进行检索

输入数据:

 id subgroup A1_A A1_B A1_C A1_D A1_E A1_F A1_G  
 1  85     AAA     3:01   ""       ""        ""      ""       ""                                                                                                                 
 2  86     AAA     3:01   05:01    ""        07:08   ""       ""                                                                                                                              
 3  94     AAA     2:01   05:01    ""        ""      ""       ""                                                                                                                                              
 4  000    AAA     2:01   06:07    ""        ""      ""       ""                                                                                                                                              
 5  37     AAA 30:01:00   07:08    ""        ""      ""       ""                                                                                                                                              
 6  48     AAA     2:01   01:01    ""        ""      ""       "" 

fre <- function(CEPH,col) {
q<-sort(table(CEPH[,col]),decreasing = TRUE)[1:2]
          return(q) }
 fre(AAA,4)

我得到了没有列名的输出

  NA      32:01:02 
  49        2 

欲望输出

Types   Frequent_Type    Highest_Frequency       
A1_A     2:01            20
A1_A     NA               5
A1_B     NA              49    
A1_B     3:01:01         5  
A1_C     2:01            20
A1_C     05:02            2

【问题讨论】:

  • @akrun 我添加了输入数据的可重现的小例子
  • 请通过this link了解重现性
  • 我想你可以查看here 的想法
  • 如果你试试apply(CEPH,2,function(x) sort(table(x),decreasing = T)[1:2])会怎么样
  • 最好是编辑现有帖子(即使已关闭)并投票重新打开。您是否尝试过链接帖子中的suggested solution

标签: r sapply


【解决方案1】:

这可能不是确切的解决方案。但不知何故,我设法将两个频率分开并合并在一起。

first_highest<-t(sapply(CEPH, function(x) {t_x <- sort(table(x), decreasing=TRUE); list(value=names(t_x)[1],freq=t_x[1])}))
second_highest<-t(sapply(CEPH, function(x) {t_x <- sort(table(x), decreasing=TRUE); list(value=names(t_x)[2],freq=t_x[2])}))

frequeny<-cbind(first_highest,second_highest)

【讨论】:

    猜你喜欢
    • 2016-12-28
    • 2015-01-18
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2022-01-17
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多