smars - 3 months ago 13

R Question

How do I fit this model in R, step by step? My scope is to make a forecast for t+1.

*Y(t) <- years from 1900 to 2000.**X <- a score measure from 0 to 100.**Y(t-1) <- lagged value of order 1 for Y.*

Thanks in advance.

Answer

Your model is an AR(1) time series for `y`

with covariate `x`

. We can just use `arima0`

(no missing value) or `arima`

(missing value allowed) from R base:

```
fit <- arima0(y, order = c(1, 0, 0), xreg = x)
```

Let's consider a small example:

```
set.seed(0)
x <- runif(100)
## intercept: 0.1
## slope of `x`: 1.2
## AR(1) with coefficient 0.5
y <- 0.1 + 1.2 * x + arima.sim(list(ar = 0.5), n = 100, sd = 0.2)
fit <- arima0(y, order = c(1, 0, 0), xreg = x)
#Call:
#arima0(x = y, order = c(1, 0, 0), xreg = x)
#
#Coefficients:
# ar1 intercept xreg
# 0.4639 0.0645 1.2139
#s.e. 0.0879 0.0448 0.0590
#
#sigma^2 estimated as 0.03046: log likelihood = 32.55, aic = -57.11
```

Note the estimate is consistent with our true model.

Thanks. How do I insert more covariates (x1,x2,etc.), just in case?

Have a look at `?arima0`

(or `?arima`

):

```
xreg: Optionally, a vector or matrix of external regressors, which
must have the same number of rows as ‘x’.
```

You can specify a model matrix via `xreg`

. Suppose you have regressors `x1`

, `x2`

, `x3`

, in a data frame `dat`

, you can generate this model matrix via:

```
X <- model.matrix(~ x1 + x2 + x3, dat)
```

Then

```
fit <- arima0(y, order = c(1, 0, 0), xreg = X)
```