[R] What is a better way to deal with lag/difference and loops in time series using R?
Gabor Grothendieck
ggrothendieck at gmail.com
Wed Apr 11 13:32:39 CEST 2012
On Tue, Apr 10, 2012 at 11:21 PM, jpm miao <miaojpm at gmail.com> wrote:
> Hello,
>
> I am writing codes for time series computation but encountering some
> problems
>
> Given the quarterly data from 1983Q1 to 1984Q2
>
> PI1<-ts(c(2.747365190,2.791594762, -0.009953715, -0.015059485,
> -1.190061246, -0.553031799, 0.686874720, 0.953911035),
> start=c(1983,1), frequency=4)
>
> If I would like to create a time series vector containing the data in 4
> quarters ahead
>
> Similar problems happen with the usage of the function "diff", which
> calculate the difference. I wonder if it is better to work with the dates
> (1983Q1, 1983Q2,.....) directly?
>
> If I want to write a loop, say, to conduct some computation from 1983Q1
> to 2011Q4, the only way I know is to convert the dates to the ordinal
> indices, 1, 2, 3...... Can we work with the dates? Is there any built-in
> equality that provides the computation like
> 1983Q1 +1 equals 1983Q2?
> In EViews, it is easy to do that. We can let %s run from 1983Q1 to
> 2011Q4, and he knows that 1983Q1+1 is exactly 1983Q2.
>
This takes the difference between each point and the point 4 quarters
back and then lags the result forward.
lag(diff(PI1, 4), 4)
In zoo you can do this:
library(zoo)
z <- as.zoo(PI1)
time(z) <- as.yearqtr(time(z))
# quarter after '83 Q2
z[as.yearqtr("1983 Q2")+1/4]
You might also want to look at rollapply in the zoo package.
xts which is related to zoo has flexible subscripting.
If your data is regular as in your example then you could also use the
tis package which is related to the fame package but can be used
without it.
zoo has several vignettes which give many examples of processing time series.
The timeSeries package is another alternative.
--
Statistics & Software Consulting
GKX Group, GKX Associates Inc.
tel: 1-877-GKX-GROUP
email: ggrothendieck at gmail.com
More information about the R-help
mailing list