Proper idiom for adding zero count rows in tidyr/dplyr

后端 未结 5 1014
旧巷少年郎
旧巷少年郎 2020-11-27 16:02

Suppose I have some count data that looks like this:

library(tidyr)
library(dplyr)

X.raw <- data.frame(
    x = as.factor(c(\"A\", \"A\", \"A\", \"B\", \         


        
5条回答
  •  南笙
    南笙 (楼主)
    2020-11-27 16:54

    You could explicitly make all possible combinations and then joining it with the tidy summary:

    x.fill <- expand.grid(x=unique(x.tidy$x), x=unique(x.tidy$y)) %>%
        left_join(x.tidy, by=("x", "y")) %>%
        mutate(count = ifelse(is.na(count), 0, count)) # replace null values with 0's
    

提交回复
热议问题