To solve a system of equations in R, we can use the built-in solve() function.
The following examples show how to use this functions to solve several different systems of equations in R.
Example 1: Solve System of Equations with Two Variables
Suppose we have the following system of equations and we’d like to solve for the values of x and y:
5x + 4y = 35
2x + 6y = 36
The following code shows how to use the solve() function in R to solve for the values of x and y:
#define left-hand side of equations left_matrix 2) left_matrix [,1] [,2] [1,] 5 4 [2,] 2 6 #define right-hand side of equations right_matrix 2) right_matrix [,1] [1,] 35 [2,] 36 #solve for x and y solve(left_matrix, right_matrix) [,1] [1,] 3 [2,] 5
This tells us that the value for x is 3 and the value for y is 5.
Example 2: Solve System of Equations with Three Variables
Suppose we have the following system of equations and we’d like to solve for the values of x, y, and z:
4x + 2y + 1z = 34
3x + 5y – 2z = 41
2x + 2y + 4z = 30
The following code shows how to use the solve() function in R to solve for the values of x, y, and z:
#define left-hand side of equations left_matrix 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 3) right_matrix [,1] [1,] 34 [2,] 41 [3,] 30 #solve for x, y, and z solve(left_matrix, right_matrix) [,1] [1,] 5 [2,] 6 [3,] 2
This tells us that the value for x is 5, the value for y is 6, and the value for z is 2.
Example 3: Solve System of Equations with Four Variables
Suppose we have the following system of equations and we’d like to solve for the values of w, x, y, and z:
6w + 2x + 2y + 1z = 37
2w + 1x + 1y + 0z = 14
3w + 2x + 2y + 4z = 28
2w + 0x + 5y + 5z = 28
The following code shows how to use the solve() function in R to solve for the values of w, x, y, and z:
#define left-hand side of equations left_matrix 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 4) right_matrix [,1] [1,] 37 [2,] 14 [3,] 28 [4,] 28 #solve for w, x, y and z solve(left_matrix, right_matrix) [,1] [1,] 4 [2,] 3 [3,] 3 [4,] 1
This tells us that the value for w is 4, x is 3, y is 3, and z is 1.
Additional Resources
The following tutorials explain how to perform other common operations in R:
How to Calculate Five Number Summary in R
How to Create Summary Tables in R
How to Calculate Z-Scores in R