The gist of what I am trying to do is to overlay dates in which lockdowns came into place and the dates on which they ended. My data contains weekly sales figures but does not contain the dates in which the lockodwns started or ended, thus when I use the "lockdown.end.dates <- which(Unit.sales$Date %in% lockdown.end.dates)" code it turns my "locdown.end.dates" vector into an empty object as it can be seen in the images that I attached.**

This is how my data looks

enter image description here

This is how my object pane looks when I try to create a vector with dates that are not included in my unit.sales dataframe. Note that for the lockdown.start.date I have tweaked the dates so that they overlap with the ones I have in the unit.sales dataframe

enter image description here

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

There are 0 best solutions below