Add rows to grouped data with dplyr?

后端 未结 4 962
失恋的感觉
失恋的感觉 2020-12-15 07:32

My data is in a data.frame format like this sample data:

data <- 
structure(list(Article = structure(c(1L, 1L, 3L, 1L, 1L, 1L, 
1L, 1L, 1L, 1L, 1L, 1L, 1L         


        
4条回答
  •  一整个雨季
    2020-12-15 08:24

    Since dplyr is under active development, I thought I would post an update that also incorporates tidyr:

    library(dplyr)
    library(tidyr)
    
    data %>%
      expand(Article, Week) %>%
      left_join(data) %>%
      group_by(Article, Week) %>%
      summarise(WeekDemand = sum(Demand, na.rm=TRUE))
    

    Which produces:

       Article     Week WeekDemand
    1    10004 2013-W01       1215
    2    10004 2013-W02        900
    3    10004 2013-W03        774
    4    10004 2013-W04       1170
    5    10006 2013-W01          0
    6    10006 2013-W02          0
    7    10006 2013-W03          0
    8    10006 2013-W04          5
    9    10007 2013-W01          2
    10   10007 2013-W02          0
    11   10007 2013-W03          0
    12   10007 2013-W04          0
    

    Using tidyr >= 0.3.1 this can now be written as:

    data %>% 
      complete(Article, Week) %>%  
      group_by(Article, Week) %>% 
      summarise(Demand = sum(Demand, na.rm = TRUE))
    

提交回复
热议问题