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().
Cet exercice fait partie du cours
Case Study: Analyzing City Time Series Data in R
Instructions
- Use
diff()to produce a simple quarterly difference ingdp. Be sure to specify thegdpcolumn and set thelagequal to1period (in this case, 1 quarter). Save this into yourgdpobject asquarterly_diff. - Now that you have a measure of quarterly GDP change, your next step is to split your
quarterly_diffdata into years usingsplit(). In your call tosplit(), be sure to specify thequarterly_diffcolumn ofgdpand set thefargument equal to"years"(with quotes). - Use
lapply()on your newly split data. To calculate a cumulative sum in each year, set theFUNargument equal tocumsum(without quotes). - Use
do.call()to rbind yourgdpchange_ytddata back into an xts object. - Finally, use
plot.xts()to examine year-to-date change in GDP (gdpchange_xts).
Exercice interactif pratique
Essayez cet exercice en complétant cet exemple de 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")