New to R and Stack Overflow. Suppose I have the following macroeconomic data loaded into a data frame called testdata in R.
> testdata
date gdp cpi_index rpi_index
21 2013 Q1 409985 125.067 247.4
22 2013 Q2 412620 125.971 249.7
23 2013 Q3 415577 126.352 250.9
24 2013 Q4 417265 127.123 252.5
25 2014 Q1 420091 127.241 253.9
26 2014 Q2 423249 128.139 256.0
27 2014 Q3 426022 128.191 256.9
28 2014 Q4 428347 128.312 257.4
I want to generate a new data called testdata_growth which contains the q-o-q growth rates for the macro variables in testdata. Currently my way of going about this is the following:
# Generating q-o-q growth rates
gdp_growth <- c(NA, diff(testdata$gdp)/ testdata$gdp[-1])
rpi_index_growth <- c(NA, diff(testdata$rpi_index)/ testdata$rpi_index[-1])
cpi_index_growth <- c(NA, diff(testdata$cpi_index)/ testdata$cpi_index[-1])
# Combining growth rates into a new data frame
testdata_growth <- data.frame(testdata$date, gdp_growth, rpi_index_growth, cpi_index_growth)
My question is how I can code the above into a loop, so that I can generate the new data frame with growth rates quicker (as I have dozens of macroeconomic variables that I need to apply this growth rate calculation to).
Any assistance would be greatly appreciated.
Thanks!
(Also, if you have any comments on how to improve my question, I would take these into consideration the next time I post onto Stack Overflow - many thanks!)
Edit: Added dput(testdata) below
> dput(testdata)
structure(list(date = structure(21:28, .Label = c("2008 Q1",
"2008 Q2", "2008 Q3", "2008 Q4", "2009 Q1", "2009 Q2", "2009 Q3",
"2009 Q4", "2010 Q1", "2010 Q2", "2010 Q3", "2010 Q4", "2011 Q1",
"2011 Q2", "2011 Q3", "2011 Q4", "2012 Q1", "2012 Q2", "2012 Q3",
"2012 Q4", "2013 Q1", "2013 Q2", "2013 Q3", "2013 Q4", "2014 Q1",
"2014 Q2", "2014 Q3", "2014 Q4"), class = "factor"), gdp = c(409985L,
412620L, 415577L, 417265L, 420091L, 423249L, 426022L, 428347L
), cpi_index = c(125.067, 125.971, 126.352, 127.123, 127.241,
128.139, 128.191, 128.312), rpi_index = c(247.4, 249.7, 250.9,
252.5, 253.9, 256, 256.9, 257.4)), .Names = c("date", "gdp",
"cpi_index", "rpi_index"), row.names = 21:28, class = "data.frame")