问题
x<-data.frame(product=c(rep("A",3),rep("B",4)),
xdate=as.Date(c("2020-01-01","2020-01-02","2020-01-04",'2020-01-02','2020-01-04','2020-01-07','2020-01-08')),
number=sample(1:10,7))
In sample data I want to fill missing dates by category. In the sample data it means that for category A I want all missing dates between it's minimum date 2020-01-01 and maximum '2020-01-04 and the same logic for category B. I am aware of function complete but it seems like it's insufficient for what I am looking for. And the number variable should be filled with 0s
回答1:
We can use complete
here as well :
library(dplyr)
library(tidyr)
x %>%
group_by(product) %>%
complete(xdate = seq(min(xdate), max(xdate), by = "1 day"), fill = list(number = 0))
来源:https://stackoverflow.com/questions/60724664/r-fill-missing-dates-by-category