Peng Guo
Peng Guo

Reputation: 9

Solve a linear system of equations in R

I write matrix equation in R like this

m1 <- rbind(c(1,-2,-1,3),
            c(-2,4,5,-5),
            c(3,-6,-6,8))
             
m2 <- c(0,3,2)

sol <-solve(m1, m2)

but the result show:

Error in solve.default(m1, m2) : 'a' (3 x 4) must be square

How I can write the code solve the equation, Thank you very much

Upvotes: 0

Views: 148

Answers (1)

G. Grothendieck
G. Grothendieck

Reputation: 269634

There is no solution. We can determine this by regressing m2 on m1 and noting that the deviance (= sum of squares of residuals) is non-zero -- if there were a solution then the residuals would be zero hence their sum of squares would be too but even in that situation the solution would not be unique given that there are 4 columns but only 3 rows.

We see from the non-NA coefficients that linear combinations of the columns span a 2 dimensional space, i.e. a plane, and another way to state that is that m2 does not lie in that plane.

fm <- lm(m2 ~ m1 + 0)
fm
##
## Call:
## lm(formula = m2 ~ m1 + 0)
##
## Coefficients:
##   m11    m12    m13    m14  
## 3.222     NA  1.556     NA  

deviance(fm)
## [1] 8.333333

Also note that the second and fourth columns are linearly dependent on the other columns as indicated by the NA's. In fact the second column is -2 times the first

fm2 <- lm(m1[, 2] ~ m1[, -2] + 0)
## ...
## Coefficients:
## m1[, -2]1  m1[, -2]2  m1[, -2]3  
##        -2          0         NA  

deviance(fm2)
## [1] 0

and the fourth column is 3.3333 times the first column plus 0.3333 times the third column.

fm4 <- lm(m1[, 4] ~ m1[, -4] + 0)
fm4
## ...
## Coefficients:
## m1[, -4]1  m1[, -4]2  m1[, -4]3  
##    3.3333         NA     0.3333  

deviance(fm4)
## [1] 9.321501e-32

If we project m2 onto the range of m1 giving m2a and use that in place of m2 then there would be a unique solution in terms of columns 1 and 3 and an infinite number of solutions in terms of all 4 columns. Look at the diagram in the first answer to https://stats.stackexchange.com/questions/241025/why-is-mathbfy-mathbf-haty-perpendicular-to-the-subspace-spanned-by . The x1 and x2 vectors there correspond to columns 1 and 3 of m1 here and the yellow portion there is the plane that they span. y there corresponds to m2 here and y hat is m2a, the projection of m2 onto the plane. Columns 2 and 4 of m1 lie in the yellow area spanned by columns 1 and 4 and m2 does not lie in it which is why there is no solution when solving using m2 whereas m2a, the projection, does lie in the yellow plane which is why there is a solution for it.

Below we see that 3.222 times column 1 plus 1.556 times column 3 equals m2a, the projection of m2 onto the range of m1.

m2a <- fitted(fm) # projection of m2 onto range of m1
fma <- lm(m2a ~ m1[, c(1, 3)] + 0)
fma
## ...
## Coefficients:
## m1[, c(1, 3)]1  m1[, c(1, 3)]2  
##          3.222           1.556  

deviance(fma)
## [1] 4.930381e-32

Upvotes: 1

Related Questions