【问题标题】:Counting occurrences based on condition in R (using dplyr ?)根据 R 中的条件计算出现次数(使用 dplyr ?)
【发布时间】:2022-01-14 04:43:11
【问题描述】:

我有一个类似的数据集

年份 ID 类型
2000 A 0
2001 A 0
2002 A 1
2000 B 0
2001 乙 0
2002 C 1
2003 C 1

我想总结一下,可能用 dplyr,这样我就可以得到每年类型 0 和类型 1 的计数。

示例:
年份类型计数
2000 0 2
2000 1 0

非常感谢,也很抱歉没有为可视化创建合适的表格。

【问题讨论】:

    标签: r dplyr


    【解决方案1】:

    我想这就是你想要的:

    my_df <- my_df %>% group_by(Year, Type) %>% summarise(Count = n())
    

    【讨论】:

    • 这正是我想要的...非常感谢伙计!
    • 别忘了勾选正确的答案!
    【解决方案2】:

    如果您想查看 count 为 0 的位置,那么您还需要一个最终的 complete

    df <- structure(
      list(Year = c(2000L, 2001L, 2002L, 2000L, 2001L, 2002L,2003L),
           ID = c("A", "A", "A", "B", "B", "C", "C"), 
           Type = c(0L, 0L, 1L, 0L, 0L, 1L, 1L)
           ), 
      class = "data.frame", 
      row.names = c(NA,-7L)
      )
    
    df %>%
      group_by(Year, Type) %>%
      count() %>%
      ungroup() %>%
      complete(Year, Type, fill = list(n = 0))
    

    返回

       Year  Type     n
      <int> <int> <dbl>
    1  2000     0     2
    2  2000     1     0
    3  2001     0     2
    4  2001     1     0
    5  2002     0     0
    6  2002     1     2
    7  2003     0     0
    8  2003     1     1
    

    【讨论】:

      【解决方案3】:
      df <- structure(
        list(Year = c(2000, 2001, 2002, 2000, 2001, 2002,2003),
             Id = c("A", "A", "A", "B", "B", "C", "C"), 
             Type = c(0, 0, 1, 0, 0, 1, 1)
        ), 
        class = "data.frame", 
        row.names = c(NA,-7L)
      )
      

      也许这会有所帮助:

      table(df$Year, df$Type)
      
            0 1
        2000 2 0
        2001 2 0
        2002 0 2
        2003 0 1
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2021-07-14
        • 1970-01-01
        • 2021-12-31
        • 2021-10-24
        • 1970-01-01
        • 2021-03-23
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多