【问题标题】:Count the frequency of a value in a data table with multiple columns in R? [duplicate]计算R中具有多列的数据表中值的频率? [复制]
【发布时间】:2016-07-29 00:13:35
【问题描述】:

假设我有一个这样的数据表:

id       days       age
"jdkl"   8          23
"aowl"   1          09
"mnoap"  4          82
"jdkl"   3          14
"jdkl"   2          34
"mnoap"  27         56

我想创建一个新的数据表,其中一列带有 id,一列带有它们出现的次数。我知道数据表中有 =.N 的内容,但我不确定如何仅将其用于一列。

最终的数据表如下所示:

id          count
"jdkl"      3
"aowl"      2
"mnoap"     1

【问题讨论】:

    标签: r


    【解决方案1】:

    你可以只使用基础R中的table

    as.data.frame(sort(table(df$id), decreasing = T))
    

    但是,如果您想使用data.table 来执行此操作:

    library(data.table)
    setDT(df)[, .(Count = .N), by = id][order(-Count)]
    

    或者有dplyr解决方案

    library(dplyr)
    df %>% count(id) %>% arrange(desc(n))
    

    【讨论】:

    • @sayaa:我安排它以匹配 OP 发布的输出。懒得整理baseR的输出了:D
    【解决方案2】:

    我们可以使用

    library(dplyr)
    df %>%
        group_by(id) %>%
        summarise(Count = n()) %>%
        arrange(desc(Count))
    

    或者使用来自base Raggregate

    r1 <- aggregate(cbind(Count=days)~id, df1, length)
    r1[order(-r1$Count),]
    #      id Count
    #2  jdkl     3
    #3 mnoap     2
    #1  aowl     1
    

    【讨论】:

      猜你喜欢
      • 2021-02-09
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2019-01-25
      • 1970-01-01
      • 2019-11-24
      相关资源
      最近更新 更多