R Programming/Time Series

Introduction

edit

In the following examples we will use the data set Mpyr which is included in the R-package Ecdat, which can be loaded into R and viewed in R by the following code.

#Installs the package Ecdat.
install.packages("Ecdat")
#Loads the packages Ecdat.
library(Ecdat)
#Attached the dataset Mpyr.
data(Mpyr)
#Shows the dataset Mpyr.
Mpyr
Time Series:
Start = 1900 
End = 1989 
Frequency = 1 
            m        p         y         r
1900 1.718774 2.092641 0.9030195  4.380000
1901 1.856318 2.086574 1.0131038  4.280000
1902 1.936512 2.120476 1.0114817  4.920000

Creating time-series objects

edit
  • The function ts() is used to create time-series objects.
  • The function as.ts() coerces an object to a time-series.
  • The function is.ts() tests whether an object is a time-series.

Example:

> data.a<-seq(1,24,by=1)
> is.ts(data.a)
[1] FALSE
> ts(data.a, start=c(2005,1), frequency=12) 
     Jan Feb Mar Apr May Jun Jul Aug Sep Oct Nov Dec
2005   1   2   3   4   5   6   7   8   9  10  11  12
2006  13  14  15  16  17  18  19  20  21  22  23  24
> data.b<-seq(1,24,by=1)
> is.ts(data.b)
[1] FALSE
> is.ts(as.ts(data.b))
[1] TRUE

Creating lagged and differenced variables

edit
  • The function lag() creates a lagged variable.
  • The function diff() creates a differenced variable.

Example:

> data.a<-seq(1,12,by=1)
> ts.a<-ts(data.a, start=c(2005,1), frequency=4)
> lag.a<-lag(ts.a,k=1)
> diff.a<-diff(ts.a,lag=1,difference=1)
> ts.a
     Qtr1 Qtr2 Qtr3 Qtr4
2005    1    2    3    4
2006    5    6    7    8
2007    9   10   11   12
> lag.a
     Qtr1 Qtr2 Qtr3 Qtr4
2004                   1
2005    2    3    4    5
2006    6    7    8    9
2007   10   11   12     
> diff.a
     Qtr1 Qtr2 Qtr3 Qtr4
2005         1    1    1
2006    1    1    1    1
2007    1    1    1    1


Plotting time-series objects

edit
  • The function plot.ts() is used for plotting time-series objects.

Fit Autoregressive Models to Time-series by OLS

edit

In order to fit an autoregressive time series model to the data by ordinary least squares it is possible to use the function ar.ols() which is part of the "stats" package.

Autocorrelation function

edit

The function acf() computes (and by default plots) estimates of the autocovariance or autocorrelation function. Function pacf() is the function used for the partial autocorrelations. Function ccf() computes the cross-correlation or cross-covariance of two univariate series.[1]

Useful R-packages

edit
  • fBasics, tis, zoo, tseries, xts, urca, forecast

References

edit

http://cran.r-project.org/web/views/TimeSeries.html

http://cran.r-project.org/doc/contrib/Ricci-refcard-ts.pdf