Add a discrete rolling sum to GDP data
While it helps to know the amount of change from one period to the next, you may want to know the total change since the beginning of the year. To generate this type of indicator, you can use the split-lapply-rbind pattern. This process is similar to the process used to generate monthly temperature averages in the previous chapter.
In this exercise, you'll return to the gdp
data used earlier in the chapter. In addition to static GDP values in each quarter, you'd like to generate a measure of GDP change from one quarter to the next (using diff()
) as well as a rolling sum of year-to-date GDP change (using split()
, lapply()
and rbind()
.
This exercise is part of the course
Case Study: Analyzing City Time Series Data in R
Exercise instructions
- Use
diff()
to produce a simple quarterly difference ingdp
. Be sure to specify thegdp
column and set thelag
equal to1
period (in this case, 1 quarter). Save this into yourgdp
object asquarterly_diff
. - Now that you have a measure of quarterly GDP change, your next step is to split your
quarterly_diff
data into years usingsplit()
. In your call tosplit()
, be sure to specify thequarterly_diff
column ofgdp
and set thef
argument equal to"years"
(with quotes). - Use
lapply()
on your newly split data. To calculate a cumulative sum in each year, set theFUN
argument equal tocumsum
(without quotes). - Use
do.call()
to rbind yourgdpchange_ytd
data back into an xts object. - Finally, use
plot.xts()
to examine year-to-date change in GDP (gdpchange_xts
).
Hands-on interactive exercise
Have a go at this exercise by completing this sample code.
# Add a quarterly difference in gdp
gdp$quarterly_diff <- diff(___$___, lag = ___, differences = ___)
# Split gdp$quarterly_diff into years
gdpchange_years <- split(___$___, f = "___")
# Use lapply to calculate the cumsum each year
gdpchange_ytd <- lapply(___, FUN = ___)
# Use do.call to rbind the results
gdpchange_xts <- do.call(rbind, ___)
# Plot cumulative year-to-date change in GDP
plot.xts(___, type = "h")