I have a dataframe that contains GDP values by country with an accompanying date column. The following code reproduces a sample dataset for two countries (FR and DE) and six years(2005-2010):
df <- structure(list(geo = structure(c(1L, 1L, 1L, 1L, 1L, 1L, 2L,
2L, 2L, 2L, 2L, 2L), .Label = c("DE", "FR"), class = "factor"),
date = structure(c(12784, 13149, 13514, 13879, 14245, 14610,
12784, 13149, 13514, 13879, 14245, 14610), class = "Date"),
GDP = c(2147975, 2249584.4, 2373993.1, 2382892.6, 2224501.8,
2371033.2, 1557584.8, 1621633.2, 1715655.4, 1713157.1, 1636336.3,
1707966.5)), .Names = c("geo", "date", "GDP"), row.names = c(NA,
-12L), class = "data.frame")
Now I would like to calculate an additional column that shows the percent differences year over year. I try the following:
library(quantmod)
# provides the Delt() function to calculate percent differences
df$dtGDP <- as.numeric(Delt(df$GDP))
This is erroneous, because it calculates a value for FR in 2005 by using the DE-value from 2010. Is there a way to apply the function "per factor level"?
tapplyand 'ave` you will probably find lots of examples that are very similar to mine. (On the other hand you will find lots of worked examples with plyr-package functions that are essentially isomorphic to each other and to this one.) - IRTFM