Jalinne
Jalinne

Reputation: 1

Is this the right way to store the residuals from an OLS regression in R?

I wanted to simulate 1000 iterations of an OLS regression and save the residuals in a n x 1 vector.

For doing so, this is the code that I came up with:

Data <- read.csv("cons.csv")

ols <- function(y,x){
  ones <- rep(1,length(x))
  X = matrix(c(ones, x), ncol = 2)
  beta = solve(t(X) %*% X) %*% t(X) %*% as.matrix(y)
  return(beta)
}

b0 = 0.42
b1 = 0.95
n = 198
x = log(Data$di[-199])
xT = log(Data$di[199])

beta <- matrix(0, 2, 1000)

for (i in 1:1000) {
  set.seed(i) 
  u <- rnorm(n, mean = 0, sd = 1) 
  y <- b0 + b1 * x + u
  beta[, i] <- ols(y, x) 
  residuals <- y - (beta[1,i] + beta[2,i] * x)
}

Is this the right way to calculate the residuals or am I missing something here?

Upvotes: 0

Views: 81

Answers (0)

Related Questions