How to create inverse matrix in R

4

In order to get the inverse of an array, we can use different commands of R solve() , ginv() , etc. However, when trying to use these commands, an error occurs where we think the problem must be because there are negative values in the matrix, since in the description of the commands they specify that we must find the inverse for positive-defined matrices. How did we resolve this issue?

    
asked by anonymous 23.03.2014 / 17:40

2 answers

2

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 
    
23.03.2014 / 20:18
0

If you reverse X'X , the simplest way is to use solve() :

    # crio uma matriz qualquer (3 colunas, 100 linhas)
    X = cbind(1, rnorm(100), runif(100))

    # invertenddo X'X
    a = solve(t(X)%*%X)

    # invertendo a decomposição QR
    b = chol2inv(X)

    # é a mesma coisa?
    a==b
          [,1]  [,2]  [,3]
    [1,] FALSE FALSE FALSE
    [2,] FALSE FALSE FALSE
    [3,] FALSE FALSE FALSE
    
23.03.2014 / 19:33