R fill missing dates by category

*爱你&永不变心* 提交于 2021-02-04 08:24:31

问题


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

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!