How to Fix in R: system is exactly singular


One error you may encounter in R is:

Lapack routine dgesv: system is exactly singular: U[2,2] = 0

This error occurs when you attempt to use the solve() function, but the matrix you’re working with is a singular matrix that does not have a matrix inverse.

This tutorial shares how to resolve this error in practice.

How to Reproduce the Error

Suppose we create the following matrix in R:

#create singular matrix
mat <- matrix(c(1, 1, 1, 1), ncol=2, nrow=2)

#view matrix
mat

     [,1] [,2]
[1,]    1    1
[2,]    1    1

Now suppose we attempt to use the solve() function to calculate the matrix inverse:

#attempt to invert matrix
solve(mat)

Error in solve.default(mat) : 
  Lapack routine dgesv: system is exactly singular: U[2,2] = 0

We receive an error because the matrix that we created does not have an inverse matrix.

Note: Check out this page from Wolfram MathWorld that shows 10 different examples of matrices that have no inverse matrix.

By definition, a matrix is singular if it has a determinant of zero.

You can use the det() function to calculate the determinant of a given matrix before you attempt to invert it:

#calculate determinant of matrix
det(mat)

[1] 0

The determinant of our matrix is zero, which explains why we run into an error.

How to Fix the Error

The only way to fix this error is to simply create a matrix that is not singular.

For example, suppose we use the solve() function to invert the following matrix in R:

#create matrix that is not singular
mat <- matrix(c(1, 7, 4, 2), ncol=2, nrow=2)

#view matrix
mat

     [,1] [,2]
[1,]    1    4
[2,]    7    2

#calculate determinant of matrix
det(mat)

[1] -26

#invert matrix
solve(mat)

            [,1]        [,2]
[1,] -0.07692308  0.15384615
[2,]  0.26923077 -0.03846154

We don’t receive any error when inverting the matrix because the matrix is not singular.

Additional Resources

The following tutorials explain how to fix other common errors in R:

How to Fix: the condition has length > 1 and only the first element will be used
How to Fix: non-numeric argument to binary operator
How to Fix: dim(X) must have a positive length
How to Fix: error in select unused arguments

Leave a Reply

Your email address will not be published. Required fields are marked *