# Using R for Time Series in SAS

Here is a great paper on using Time Series in R, and it specifically allows you to use just R output in Base SAS.

SAS Code

/* three methods: */

/* 1. Call R directly – Some errors are not reported to log */

x “’C:\Program Files\R\R-2.12.0\bin\r.exe’–no-save –no-restore <“”&rsourcepath\tsdiag.r””>””&rsourcepath\tsdiag.out”””;

infile “&rsourcepath\tsdiag.out”;

file log;

input;

put ’R LOG: ’ _infile_;

run;

/* include the image in the sas output.Specify a file if you are not using autogenerated html output */

ods html;

data _null_;

file print;

put “<IMG SRC=’” “&rsourcepath\plot.png” “’ border=’0’>”;

put “<IMG SRC=’” “&rsourcepath\acf.png” “’ border=’0’>”;

put “<IMG SRC=’” “&rsourcepath\pacf.png” “’ border=’0’>”;

put “<IMG SRC=’” “&rsourcepath\spect.png” “’ border=’0’>”;

put “<IMG SRC=’” “&rsourcepath\fcst.png” “’ border=’0’>”;

run;

ods html close;

The R code to create a time series plot is quite elegant though-

```
library(tseries)

air <- AirPassengers #Datasetname

ts.plot(air)

acf(air)

pacf(air)

plot(decompose(air))

air.fit <- arima(air,order=c(0,1,1), seasonal=list(order=c(0,1,1), period=12) #The ARIMA Model Based on PACF and ACF Graphs

tsdiag(air.fit)

library(forecast)

air.forecast <- forecast(air.fit)

plot.forecast(air.forecast)

```

You can download the fascinating paper from the Analytics NCSU Website http://analytics.ncsu.edu/sesug/2008/ST-146.pdf

Sam Croker has a MS in Statistics from the University of South Carolina and has over ten years of experience in analytics.   His research interests are in time series analysis and forecasting with focus on stream-flow analysis.  He is currently using SAS, R and other analytical tools for fraud and abuse detection in Medicare and Medicaid data. He also has experience in analyzing, modeling and forecasting in the finance, marketing, hospitality, retail and pharmaceutical industries.

## 2 thoughts on “Using R for Time Series in SAS”

1. The html tags in the R code will cause errors. Here is a corrected and simpler version:

```library(tseries)
air <- AirPassengers #Data set name
plot(air)
acf(air)
pacf(air)
plot(decompose(air))
air.fit <- arima(air,order=c(0,1,1), seasonal=list(order=c(0,1,1), period=12))
#ARIMA Model Based on PACF and ACF Graphs
tsdiag(air.fit)
library(forecast)
air.forecast <- forecast(air.fit)
plot(air.forecast)
```
1. Hi Rob,

Thanks for the info- If you hover your mouse on the code you can see some icons appear on top right corner of code including one which is like “” and which says View Source. If you click View Source- that takes you straight to the actual code. That’s the way to copy the R Code. However this code helps as well- as not all people would be aware of that feature in WordPress.com . I will try and remove the HTML tags as well.

Cheers

Ajay