How to add rows with 0 counts to summarised output

后端 未结 2 1992
温柔的废话
温柔的废话 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
    

提交回复
热议问题