0

I want to test if a matrix is singular or not in R. I tried a function, which is

is.non.singular.matrix() in matrixcalc package.

However, sometimes, in my case there is a 60*60 matrix generated, the function returns FALSE, which means the matrix is singular. But I can still use solve() to get the invert of the matrix. Which one should I trust? Is there any other better way to do?

Or, for a singular matrix, solve() will return a error message. Is there a way to write a statement, that if solve() returns an error, then do something else (for example, add some variations to the diagonal elements). But I don't know how to get the return value of the error message.

Rich Scriven
  • 97,041
  • 11
  • 181
  • 245
Jiang Du
  • 189
  • 2
  • 14

1 Answers1

1

Test whether try() returns an object of class "try-error":

 mtx <- matrix(c(1,1,2,2), 2)
 if ( inherits( try( solve(mtx), silent=TRUE),  "try-error")){"oops"} else {solve(mtx)}
[1] "oops"

> if ( inherits( try( solve(mtx), silent=TRUE),  "try-error")){
                                     print("oops"); solve(mtx+ rnorm(4) )
                                    } else {solve(mtx)}
[1] "oops"
           [,1]      [,2]
[1,]  0.8310745 -1.618425
[2,] -1.0580812  3.050279

You could conceivably build this as a recursive function. See:

?Recall
IRTFM
  • 258,963
  • 21
  • 364
  • 487
  • Never now the try() function. It's great. Thank you a lot. I will check more about those functions. – Jiang Du Apr 17 '14 at 01:16
  • Could you please tell me more about inherits? The R menu is not that easy to follow... – Jiang Du Apr 17 '14 at 01:23
  • 1
    Yes. It's easy to see by using `class(try(solve(mtx)))`. `inherits(x, "class_name")` is safer to use than `class(x)=="class_name"` – IRTFM Apr 17 '14 at 05:42