简体   繁体   English

用R求解联立方程

[英]Solving simultaneous equations with R

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 x , y and z ? 如何解决xyz这些方程? I would like to solve these equations, if possible, using R or any other computer tools. 如果可能,我想使用R或任何其他计算机工具来解决这些方程式。

This should work 这应该工作

A <- matrix(data=c(1, 2, 3, 2, 5, 9, 5, 7, 8), nrow=3, ncol=3, byrow=TRUE)    
b <- matrix(data=c(20, 100, 200), nrow=3, ncol=1, byrow=FALSE)
round(solve(A, b), 3)

     [,1]
[1,]  320
[2,] -360
[3,]  140

For clarity, I modified the way the matrices were constructed in the previous answer. 为清楚起见,我在前一个答案中修改了矩阵的构造方式。

a <- rbind(c(1, 2, 3), 
           c(2, 5, 9), 
           c(5, 7, 8))
b <- c(20, 100, 200)
solve(a, b)

In case we need to display fractions: 如果我们需要显示分数:

library(MASS)
fractions(solve(a, b))

Another approach is to model the equations using lm as follows: 另一种方法是使用lm对方程建模如下:

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: 如果您使用tibble包,您甚至可以像原始方程一样读取它:

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. 它产生相同的输出。

A <- matrix(data=c(1, 2, 3, 2, 5, 9, 5, 7, 8),nrow=3,ncol=3,byrow=TRUE)    
b <- matrix(data=c(20, 100, 200),nrow=3,ncol=1,byrow=FALSE)
solve(A)%*% b

Note that this is a square matrix! 请注意,这是一个方阵!

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM