【问题标题】:r creating a summary table of how often a type is usedr 创建一个类型使用频率的汇总表
【发布时间】:2012-05-04 20:39:10
【问题描述】:

我有一个数据框 Anametype

name    aa  tt  gg  cc  aa  at  ag  ac

 type    3   2   4   3   2   2   3   3

如何创建一个新的排名 data.frame Btype 和次数 类型出现在data.frame A?

count   4   3   1   

type    3   2   4   

感谢您的帮助。

【问题讨论】:

    标签: r


    【解决方案1】:

    一个选项是table() 函数。对于您的数据:

    dat <- data.frame(name = c("aa","tt","gg","cc","aa","at","ag","ac"),
                      type = c(3,2,4,3,2,2,3,3))
    

    它给出:

    > (tab <- with(dat, table(type)))
    type
    2 3 4 
    3 4 1
    

    现在我们只需要对其进行排序:

    > sort(tab, decreasing = TRUE)
    type
    3 2 4 
    4 3 1
    

    当然,这些步骤可以组合起来:

    > with(dat, sort(table(type), decreasing = TRUE))
    type
    3 2 4 
    4 3 1
    

    【讨论】:

      【解决方案2】:

      另外两种可能更快的方法:

      rev(sort(tapply(dat$type, dat$type, length)))
      
      x <- do.call('data.frame', (rle(sort(dat$type)))); x[order(-x$lengths), ]
      

      编辑: 在 Gavin 的数据集上没有,他提出的表格方法是最快的(在 win7 机器上使用微基准测试):

      Unit: microseconds
          expr     min      lq  median       uq      max
      1    RLE 614.452 650.376 669.971 713.3605 104852.7
      2  TABLE 562.664 586.691 607.453 645.9440 128596.5
      3 TAPPLY 585.525 626.115 643.144 689.0995 118123.8
      

      【讨论】:

      • +1 不错的选择。不过,我怀疑 data.table 是解决大问题的最佳选择。
      猜你喜欢
      • 2013-03-08
      • 1970-01-01
      • 2016-05-12
      • 1970-01-01
      • 2021-03-09
      • 1970-01-01
      • 2023-04-03
      • 2022-01-28
      • 1970-01-01
      相关资源
      最近更新 更多