How to add rows with 0 counts to summarised output

后端 未结 2 1986
温柔的废话
温柔的废话 2020-12-11 12:37

I have added sample data below, I have used dplyr to count on Rco and month:

structure(list(Rco = structure(c(1L, 1L, 1L, 1L, 2L, 2         


        
相关标签:
2条回答
  • 2020-12-11 12:43

    We can use expand.grid on the unique values of the first two columns, and merge with the initial dataset. This will fill NA for combinations that are not present in the expand.grid.

    res <- merge(expand.grid(lapply(df1[1:2], unique)), df1, all.x=TRUE)
    

    But, it is easy to change the NA to 0

    res[is.na(res)] <- 0
    
    0 讨论(0)
  • 2020-12-11 12:50

    You can use tidyr::complete and specify the fill to be 0 (instead of the default NA):

    library(tidyr)
    complete(df, Rco, month, fill = list(count = 0))
    
    0 讨论(0)
提交回复
热议问题