[R] how to get growth rate of a (time series) data?
ggrothendieck at gmail.com
Wed Jun 19 14:11:47 CEST 2013
On Wed, Jun 19, 2013 at 7:04 AM, Yanyuan Zhu <yyz at tongji.edu.cn> wrote:
> Hello all, now I'm trying to switch from Excel to R to deal with the data,
> and as a newbie i got the problem as follows.
> suppose I have a data named "test"
> test<- data.frame(year=c(1996:2011),
> in which Y means the GDP of a country
> If i want to get Delta Y = Y(t)-Y(t-1) , i could use diff() in R
> but what if i want to get gY=(Y(t)-Y(t-1))/Y(t-1)?
> seems diff(test$Y)/(test$Y)[-1] doesnt work ...
As already mentioned, that R expression gives (Y[t] - Y[t-1]) / Yt[t]
whereas you want
Y <- test$Y
n <- length(Y)
diff(Y) / Y[-n]
or you might want to use a time series class for simpler
manipluations: Using ts class:
Y.ts <- ts(test[, 2], start = test[1,1])
Ydiff.ts <- diff(Y.ts) / lag(Y.ts, - 1)
or, using tis class which is frequently used for equally spaced
Y.tis <- tis(test[, 2], start = test[1,1], freq = 1)
Ydiff.tis <- diff(Y.tis) / lag(Y.tis, - 1)
or using zoo class which, in addition, supports non-equally spaced
series and also allows for two different approaches here:
Y.z <- read.zoo(test, FUN = identity)
Ydiff.z <- diff(Y.z) / lag(Y.z, - 1)
This also works with zoo:
Ydiff.z <- diff(Y.z, arith = FALSE) - 1
Statistics & Software Consulting
GKX Group, GKX Associates Inc.
email: ggrothendieck at gmail.com
More information about the R-help