Lagging unemployment
Given that economic trends may take some time to influence tourism, it may be helpful to lag your unemployment data before proceeding with analysis.
Generating a lag in xts is straightforward with the lag()
command, which requires that you specify the data being lagged (the x
argument) and a k
value to determine the direction and scale of the lag.
Be careful to keep your formatting consistent. Base R and the zoo package require that you specify a lag with a negative value, so that a lag of 1 is expressed using "-1"
(and a lead of 1 is counterintuitively expressed using "1"
). By contrast, the xts package specifies lags using a positive value, so that a lag of 1 is expressed using "1"
(and a lead of 1 is expressed using "-1"
).
This exercise is part of the course
Case Study: Analyzing City Time Series Data in R
Exercise instructions
- Use
lag()
to generate a one-month lag of US unemployment. For a one month lag using monthly data, simply set thek
argument equal to1
. Remember that yourunemployment
object contains time series data on both US unemployment (us
) and MA unemployment (ma
). You'll need to specify which column you want to lag. Save this new xts object asus_monthlag
. - Use another call to
lag()
to generate a one-year lag of US unemployment. Once again, make sure you specify the correct column inunemployment
and the appropriatek
value to generate a lag over an entire year. Save this new xts object asus_yearlag
. - Use
merge()
to combine your original unemployment data (unemployment
) with your new lags (us_monthlag
andus_yearlag
). Save this combined data asunemployment_lags
. - Use
head()
to view the first15
rows ofunemployment_lags
.
Hands-on interactive exercise
Have a go at this exercise by completing this sample code.
# Create a one month lag of US unemployment
us_monthlag <- lag(___$___, k = ___)
# Create a one year lag of US unemployment
us_yearlag <-
# Merge your original data with your new lags
unemployment_lags <- merge(unemployment, ___, ___)
# View the first 15 rows of unemployment_lags