代码之家  ›  专栏  ›  技术社区  ›  tnt

组内r dplyr计数观察

  •  0
  • tnt  · 技术社区  · 6 年前

    我有一个数据框,其中包含不同日期和小时的“是/否”值。对于每一天,我希望得到我有数据的总小时数,以及有值y的总小时数。

    df <- data.frame(day = c(1,1,1,2,2,3,3,3,3,4),
                     hour = c(1,2,3,1,2,1,2,3,4,1),
                     YN = c("Y","Y","Y","Y","Y","Y","N","N","N","N"))
    
    df %>% 
      group_by(day) %>%
      summarise(tot.hour = n(),
                totY = WHAT DO I PUT HERE?)
    
    1 回复  |  直到 6 年前
        1
  •  4
  •   BENY    6 年前

    使用布尔值然后加起来

    df %>% 
        group_by(day) %>%
        dplyr::summarise(tot.hour = n(),
                  totY = sum(YN=='Y'))
    # A tibble: 4 x 3
        day tot.hour  totY
      <dbl>    <int> <int>
    1     1        3     3
    2     2        2     2
    3     3        4     1
    4     4        1     0