如何在R中求解方程组(3个例子

317 阅读2分钟

要解决R语言中的方程组,我们可以使用内置的**solve()**函数。

下面的例子说明了如何使用这个函数来解决R语言中几个不同的方程组。

例1:求解双变量方程组

假设我们有以下方程组,我们想求出x和y的值。

5x + 4y = 35

2x + 6y = 36

下面的代码显示了如何使用R中的**solve()**函数来解决x和y的值。

#define left-hand side of equations
left_matrix <- matrix(c(5, 2, 4, 6), nrow=2)

left_matrix

     [,1] [,2]
[1,]    5    4
[2,]    2    6

#define right-hand side of equations
right_matrix <- matrix(c(35, 36), nrow=2)

right_matrix

     [,1]
[1,]   35
[2,]   36

#solve for x and y
solve(left_matrix, right_matrix)  

     [,1]
[1,]    3
[2,]    5

这告诉我们,x的值是3,y的值是5

例2:求解三变量的方程组

假设我们有以下方程组,我们想求出x、y和z的值。

4x + 2y + 1z = 34

3x + 5y - 2z = 41

2x + 2y + 4z = 30

下面的代码显示了如何使用R中的**solve()**函数来解决x、y和z的值。

#define left-hand side of equations
left_matrix <- matrix(c(4, 3, 2, 2, 5, 2, 1, -2, 4), nrow=3)

left_matrix

     [,1] [,2] [,3]
[1,]    4    2    1
[2,]    3    5   -2
[3,]    2    2    4

#define right-hand side of equations
right_matrix <- matrix(c(34, 41, 30), nrow=3)

right_matrix

     [,1]
[1,]   34
[2,]   41
[3,]   30

#solve for x and y
solve(left_matrix, right_matrix) 

     [,1]
[1,]    5
[2,]    6
[3,]    2

这告诉我们,x的值是5,y的值是6,z的值是2

例3:求解四变量方程组

假设我们有以下的方程组,我们想求出w、x、y和z的值。

6w + 2x + 2y + 1z = 37

2w + 1x + 1y + 0z = 14

3w + 2x + 2y + 4z = 28

2w + 0x + 5y + 5z = 28

下面的代码显示了如何使用R中的**solve()**函数来解决w、x、y和z的值。

#define left-hand side of equations
left_matrix <- matrix(c(6, 2, 3, 2, 2, 1, 2, 0, 2, 1, 2, 5, 1, 0, 4, 5), nrow=4)

left_matrix

     [,1] [,2] [,3] [,4]
[1,]    6    2    2    1
[2,]    2    1    1    0
[3,]    3    2    2    4
[4,]    2    0    5    5

#define right-hand side of equations
right_matrix <- matrix(c(37, 14, 28, 28), nrow=4)

right_matrix

     [,1]
[1,]   37
[2,]   14
[3,]   28
[4,]   28

#solve for x and y
solve(left_matrix, right_matrix)

     [,1]
[1,]    4
[2,]    3
[3,]    3
[4,]    1

这告诉我们,w的值是4,x是3,y是3,z是1

其他资源

下面的教程解释了如何在R中进行其他常见的操作。

如何在R中计算五个数字的摘要
如何在R中创建摘要表
如何在R中计算Z-scores

The postHow to Solve a System of Equations in R (3 Examples)appeared first onStatology.