Bianca Gonzalez
Bianca Gonzalez

Reputation: 39

create x with first order autoregressive process in an OLS

I have a simple regression: yt=β1+β2xi+ei, with n=27, and "x" an AR(1):

xi = c + ∅x(i-1) + ηi , where ηi~N(0,1) , x0~N(c/(1-∅),1/(1-∅^2) , c=2 , ∅=0.6

I need to create "x", for this I have set everything including the "x0", however I am stuck:

phi <- 0.6
c <- 2
ni <- rnorm(27)
x0 <- rnorm(1,(c/(1-phi)),(1/(1-(phi)^2)))

With for I couldn't make it work:

xa<- vector(mode="numeric",length=0)
x<- rep(0,27)
for(i in 1:27){
  w<-c+phi*x[i-1]+ni[i]
  xa <- c(xa,w)
}

How should I create "x"?

Upvotes: 2

Views: 253

Answers (2)

Bianca Gonzalez
Bianca Gonzalez

Reputation: 39

well, I managed to come up with a solution:

after set

phi <- 0.6
c <- 2
e <- as.vector(rnorm(27))
ni<- as.vector(rnorm(27))
x0 <- rnorm(1,(c/(1-phi)),(1/(1-(phi)^2)))

we need to do a for like this:

x<- rep(0,27)
x[1]<- c+phi*x0+ni[1]
for(i in 2:27){
  x[i]<-c+phi*x[i-1]+ni[i]
}

and then it works!!!!

Upvotes: 0

WaltS
WaltS

Reputation: 5530

It looks like your computed x[i-1] is not used to compute x[i]. If I understand your AR model, you might try

x <- rep(0,27)
x[1] <- x0
for(i in 2:27){
  x[i] <-c + phi*x[i-1] + ni[i]
}

or using an R function which generates more general AR simulations

mu <- c/(1-phi)
x <- arima.sim(model=list(ar=c(phi,0), sd=1), n=27) + mu

UPDATE

To have x[1] contain the first computed value after x0, try

x <- rep(0,28)
x[1] <- x0
for(i in 2:28){
  x[i] <-c + phi*x[i-1] + ni[i-1]
}
# to change indexing so x[1] is not x0 but is first computed value
for( i in 1:27) { x[i] <- x[i+1] }
x <- x[-28]

Upvotes: 1

Related Questions