R按类别填充缺失的日期 [英] R fill missing dates by category

查看:24
本文介绍了R按类别填充缺失的日期的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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))

在示例数据中,我想按类别填充缺失的日期.在样本数据中,这意味着对于 A 类,我想要它的最小日期 2020-01-01 和最大日期 '2020-01-04 之间的所有缺失日期和类别 B 的相同逻辑.我知道功能完整,但似乎不足以满足我的要求.并且 number 变量应该用 0s 填充

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

推荐答案

我们也可以在这里使用 complete :

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))

这篇关于R按类别填充缺失的日期的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆