Get startedGet started for free

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

View Course

Exercise instructions

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

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")
Edit and Run Code