简体   繁体   English

按项目填充时间序列中缺失的日期月份

[英]Filling missing date months in a time series by Item

I am fairly new to R and I am trying to do the following task:我对 R 相当陌生,我正在尝试执行以下任务:

I have the following dataset:我有以下数据集:

df1 <- data.frame(ITEM = c("A","A","A","A","A","B","B","B","B","B"),
              Date = c("Jan-2020","Feb-2020","May-2020","Jun-2020","Jul-2020","Jan-2020","Apr-2020","Jun-2020","Jul-2020","Aug-2020"))

Here is an image:这是一张图片:

在此处输入图像描述

I have used the library "zoo" to change the date column into yearmon and I am trying to create rows for the missing "yearmon" dates.我已经使用库“zoo”将日期列更改为 yearmon,并且我正在尝试为缺少的“yearmon”日期创建行。 So something like this:所以是这样的:

在此处输入图像描述

Anyone has any idea how I can do this?有人知道我该怎么做吗?

Thank you谢谢

You can create a sequence of yearmon objects for each ITEM and use it in complete .您可以为每个ITEM创建一系列yearmon对象并在complete中使用它。

library(dplyr)
library(zoo)
library(tidyr)

df1 %>%
  mutate(Date = as.yearmon(Date, '%b-%Y')) %>%
  group_by(ITEM) %>%
  complete(Date = seq(min(Date), max(Date), 1/12)) %>%
  ungroup

#   ITEM  Date     
#   <chr> <yearmon>
# 1 A     Jan 2020 
# 2 A     Feb 2020 
# 3 A     Mar 2020 
# 4 A     Apr 2020 
# 5 A     May 2020 
# 6 A     Jun 2020 
# 7 A     Jul 2020 
# 8 B     Jan 2020 
# 9 B     Feb 2020 
#10 B     Mar 2020 
#11 B     Apr 2020 
#12 B     May 2020 
#13 B     Jun 2020 
#14 B     Jul 2020 
#15 B     Aug 2020 

If you want a sequence of date objects you can use:如果您想要一系列日期对象,您可以使用:

df1 %>%
  mutate(Date = as.Date(as.yearmon(Date, '%b-%Y'))) %>%
  group_by(ITEM) %>%
  complete(Date = seq(min(Date), max(Date), 'month')) %>%
  ungroup()

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM