Felipe, it is not very clear what the problem is, ideally you would put the code with (possible) error. But here are some ways to invert an array in R
:
Generating a sample database:
### constante
c <- rep(1, 1000)
### x ~ N(1,2)
set.seed(1)
x <-rnorm(1000, 1,2)
### w ~ N(1,2)
set.seed(2)
w <- rnorm(1000, 1, 2)
X = cbind(c,x,w)
Inverting (X'X):
### com solve:
a <- solve(t(X)%*%X)
### com ginv:
b <-ginv(t(X)%*%X)
### com choleski:
c <- chol2inv(chol(t(X)%*%X))
### com qr:
d <-qr.solve(qr(t(X)%*%X))
Comparing all to see that they are equal:
### primeiro vamos tirar os dimnames para comparar somente os numeros
dimnames(a) <- NULL
dimnames(d) <- NULL
### comparando
all.equal(a,b,c,d)
[1] TRUE
You must use the command all.equal
because of floating-point errors .
If you estimate the coefficients of a regression (if you do not want to use the lm
function), you can use qr.coef
:
### y = 10 + 5x + 2w + u, u~N(0,1)
set.seed(3)
y <- 10 + 5*x +2*w + rnorm(1000)
### estimando os betas
B <- qr.coef(qr(X), y)
B
c x w
9.994012 5.019442 1.994124