Solving simultaneous equations with R

后端 未结 4 1203
迷失自我
迷失自我 2020-12-04 21:56

Suppose I have the following equations:

 x + 2y + 3z = 20  
2x + 5y + 9z = 100  
5x + 7y + 8z = 200

How do I solve these equations for

4条回答
  •  执笔经年
    2020-12-04 22:34

    Another approach is to model the equations using lm as follows:

    lm(b ~ . + 0, 
       data = data.frame(x = c(1, 2, 5), 
                         y = c(2, 5, 7), 
                         z = c(3, 9, 8), 
                         b = c(20, 100, 200)))
    

    which produces

    Coefficients:
       x     y     z  
     320  -360   140
    

    If you use the tibble package you can even make it read just like the original equations:

    lm(b ~ . + 0, 
       tibble::tribble(
         ~x, ~y, ~z,  ~b,
          1,  2,  3,  20,
          2,  5,  9, 100,
          5,  7,  8, 200))
    

    which produces the same output.

提交回复
热议问题