Session Ready
Exercise

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().

Instructions
100 XP
  • Use diff() to produce a simple quarterly difference in gdp. Be sure to specify the gdp column and set the lag equal to 1 period (in this case, 1 quarter). Save this into your gdp object as quarterly_diff.
  • Now that you have a measure of quarterly GDP change, your next step is to split your quarterly_diff data into years using split(). In your call to split(), be sure to specify the quarterly_diff column of gdp and set the f argument equal to "years" (with quotes).
  • Use lapply() on your newly split data. To calculate a cumulative sum in each year, set the FUN argument equal to cumsum (without quotes).
  • Use do.call() to rbind your gdpchange_ytd data back into an xts object.
  • Finally, use plot.xts() to examine year-to-date change in GDP (gdpchange_xts).