Inverse of matrix in R

Tim picture Tim · Nov 20, 2010 · Viewed 240.8k times · Source

I was wondering what is your recommended way to compute the inverse of a matrix?

The ways I found seem not satisfactory. For example,

> c=rbind(c(1, -1/4), c(-1/4, 1))  
> c  
      [,1]  [,2]  
[1,]  1.00 -0.25  
[2,] -0.25  1.00  
> inv(c)  
Error: could not find function "inv"  
> solve(c)    
          [,1]      [,2]  
[1,] 1.0666667 0.2666667  
[2,] 0.2666667 1.0666667  
> solve(c)*c  
            [,1]        [,2]  
[1,]  1.06666667 -0.06666667  
[2,] -0.06666667  1.06666667  
> qr.solve(c)*c  
            [,1]        [,2]  
[1,]  1.06666667 -0.06666667  
[2,] -0.06666667  1.06666667  

Thanks!

Answer

user28 picture user28 · Nov 20, 2010

solve(c) does give the correct inverse. The issue with your code is that you are using the wrong operator for matrix multiplication. You should use solve(c) %*% c to invoke matrix multiplication in R.

R performs element by element multiplication when you invoke solve(c) * c.