How to create inverse matrix in R

Asked

Viewed 6,494 times

4

To get the inverse of an array, we can use different R commands solve(), ginv(), etc, however, when trying to use these commands, an error occurs where we think the problem should 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 we managed to resolve this issue?

  • You could exemplify with code, or with the error you are encountering.

  • X_i<-chol2inv(X), where X is a 1000x3 dimension matrix We used the chol2inv() command of our original matrix in an attempt to find the value of (X'X) -1 and found a 3x3 dimension matrix, which is expected. Right? Since this problem has been solved, we need to create a vector y with dimension 1000x1, y being a function (data generator process). Can we define y as a pgd (y<-a+bx+cz) and then define its dimensions with (dim(y)=c(1000,1,1)? We did it and we’re not sure if it’s right.

  • Edit your question, and add there.

  • Felipe, it is not very clear what the problem is, if you manage to put an example of the code becomes easier to help. Here’s how to improve the question: http://meta.pt.stackoverflow.com/questions/824/como-crea-um-exemplo-minimo-reproducvel-em-r/825#825

2 answers

2

Felipe, it is not very clear what the problem is, ideally you would put the code with the (possible) error. But here are some ways to reverse a matrix in the R:

Generating an example 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)

Reversing (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 them all to see they’re the same:

### 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 need to use the command all.equal because of floating point errors.

In case of estimating the coefficients of a regression (if you do not want to use the function lm), 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 

0

if you reverse X'X, the simplest way is by using 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

Browser other questions tagged

You are not signed in. Login or sign up in order to post.