我想做的事情的要点是叠加锁定开始的日期和结束的日期。我的数据包含每周销售数据,但不包含锁定开始或结束的日期,因此当我使用“lockdown.end.dates <- which(Unit.sales$Date %in%lockdown.end.dates)”代码它将我的“locdown.end.dates”向量变成一个空对象,就像在我附加的图像中看到的那样。**
这就是我的数据的样子
当我尝试创建一个包含未包含在我的 unit.sales 数据框中的日期的向量时,这就是我的对象窗格的外观。请注意,对于lockdown.start.date,我已经调整了日期,使它们与我在unit.sales 数据框中的日期重叠
####Install Packages####
library(fpp2)
library(dplyr)
library(zoo)
library(xts)
library(ggplot2)
######Load data########
Unit.sales <- structure(list(
Date = c(
"30/03/2019",
"06/04/2019",
"13/04/2019",
"20/04/2019",
"27/04/2019",
"04/05/2019",
"11/05/2019",
"18/05/2019",
"25/05/2019",
"01/06/2019"
),
Units = c(
967053.4,
633226.9,
523264,
473914.2,
418087.5,
504342.2,
477819,
415650,
406972.3,
429791.4
)
),
row.names = c(NA, 10L),
class = "data.frame")
######Convert date column to date format########
Unit.sales$Date <- as.Date(Unit.sales$Date, format='%d/%m/%Y')
######Convert data frame to time series object#####
unit.sales.ts <- xts(Unit.sales$Units, Unit.sales$Date)
class(unit.sales.ts)
#######Visualize data######
unit.sales.plot <- Unit.sales %>% ggplot(aes(x=Date, y=Units)) +
geom_line() +
scale_x_date(date_labels="%b %y",date_breaks ="2 month") +
labs(title = "Linechart of unit sales")
#Create objects containing the lockdown dates#
lockdown.start.dates <- as.Date(c("2020-03-28", "2020-11-07", "2021-01-09"))
lockdown.start.dates <- which(Unit.sales$Date %in% lockdown.start.dates)
lockdown.end.dates <- as.Date(c("2020-06-15", "2020-11-05", "2021-04-12"))
lockdown.end.dates <- which(Unit.sales$Date %in% lockdown.end.dates)
#Add lockdown dates to the unit.sales.plot#
unit.sales.plot +
geom_vline(xintercept = as.numeric(Unit.sales$Date[lockdown.start.dates,]),
col = "red", lwd = 3)