【问题标题】:How to do group by count in R [duplicate]如何在R中按计数分组[重复]
【发布时间】:2016-01-29 09:37:28
【问题描述】:

我想统计月份来源级别的预订 ID

Month   Source  Booking_id
Oct        A    100
Nov        B    101
Oct        A    106
Jan        B    109
Nov        A    110
Nov        B    111


data <- structure(list(Month = c("October", "November", "October", "January", 
"November", "November"), Source = c("A", "B", "A", "B", "A", 
"B"), Booking_ID = c(100L, 101L, 106L, 109L, 110L, 111L)), .Names = c("Month", 
"Source", "Booking_ID"), class = c("tbl_df", "tbl", "data.frame"
), row.names = c(NA, -6L))

【问题讨论】:

    标签: r


    【解决方案1】:

    也许这会有所帮助:

    table(data$Month, data$Booking_id)
    
    #     100 101 106 109 110 111
    # Jan   0   0   0   1   0   0
    # Nov   0   1   0   0   1   1
    # Oct   1   0   1   0   0   0
    
    
    table(data$Month, data$Source)
    
    #     A B
    # Jan 0 1
    # Nov 1 2
    # Oct 2 0
    

    【讨论】:

    • 不工作.. 我刚得到一排几个月
    • @Akshit 你能dput你的数据吗?
    • 它工作了谢谢....我之前有一些 Null 值
    【解决方案2】:

    两种选择:

    1.聚合

    aggregate(Booking_ID ~ Month + Source, data, FUN = "length")
    

    输出:

         Month Source Booking_ID
    1 November      A          1
    2  October      A          2
    3  January      B          1
    4 November      B          2
    

    2。 sqldf

    library(sqldf)
    sqldf("SELECT  Month, Source, COUNT(*) AS Count FROM data GROUP BY Month, Source")
    

    输出:

         Month Source Count
    1  January      B     1
    2 November      A     1
    3 November      B     2
    4  October      A     2
    

    【讨论】:

      【解决方案3】:

      我们可以使用dplyr。我们按“月份”、“来源”分组并获取“Booking_id”的n_distinct,即“Booking_id”的unique元素的数量,或者如果我们需要总数,请使用n()

      library(dplyr)
      data %>%
        group_by(Month, Source) %>%
        summarise(n= n_distinct(Booking_ID))
        #if we wanted the total count instead of unique
        #summarise(n=n()) 
      
      #    Month Source     n
      #     (chr)  (chr) (int)
      #1  January      B     1
      #2 November      A     1
      #3 November      B     2
      #4  October      A     2
      

      【讨论】:

      • 缺少Source 级别,不是吗?
      • 不工作.. 错误:列“booking_com$booking_month”的类型不受支持(NILSXP,classes = NULL)
      • @Akshit 请显示示例数据集的 dput 输出。它对我有用。
      • > table(booking_com$booking_month, booking_com$source_meaning)
      • @Akshit 正如我之前提到的,使用dput(df1) 并在您的帖子中显示输出。
      猜你喜欢
      • 2018-08-02
      • 1970-01-01
      • 1970-01-01
      • 2022-09-22
      • 1970-01-01
      • 2017-01-20
      • 2022-07-22
      • 2016-12-09
      • 1970-01-01
      相关资源
      最近更新 更多