Open In App

Solve System of Equations in R

Last Updated : 23 Aug, 2021
Improve
Improve
Like Article
Like
Save
Share
Report

In this article, we will discuss how to solve a system of equations in R Programming Language. 

solve() function in R Language is used to solve the equation. Here equation is like a*x = b, where b is a vector or matrix and x is a variable whose value is going to be calculated.

Syntax: solve(a, b)

Parameters:

  • a: coefficients of the equation
  • b: vector or matrix of the equation

Example 1: Solving system equation of three equations

Given Equations:
x + 2y + 3z = 20  
2x + 2y + 3z = 100  
3x + 2y + 8z = 200

Matrix A and B for solution using coefficient of equations:
A->
1   2   3
2   2   3
3   2   8
B->
20
100
200

To solve this using two matrices in R we use the following code:

R




# create matrix A and B using given equations
A <- rbind(c(1, 2, 3), 
           c(2, 2, 3), 
           c(3, 2, 8))
B <- c(20, 100, 200)
  
# Solve them using solve function in R
solve(A, B)


Output:

80 -36 3.99999999999999

which means x=80, y=-36 and z=4 is the solution for linear equations.

Example 2: Solving system equation of three equations

To get solutions in form of fractions, we use library MASS in R Language and wrap solve function in fractions.

Given Equations:
19x + 32y + 31z = 1110  
22x + 28y + 13z = 1406  
31x + 12y + 81z = 3040
Matrix A and B for solution using coefficient of equations:
A->
19   32   31
22   28   13
31   12   81
B->
1110
1406
3040

To solve this using two matrices in R we use the following code:

R




# Load package MASS
library(MASS)
  
# create matrix A and B using given equations
A <- rbind(c(19, 32, 31), 
           c(22, 28, 31), 
           c(31, 12, 81))
B <- c(1110, 1406, 3040)
  
# Solve them using solve
# function wrapped in fractions
fractions(solve(A, B))


Output:

[1] 159950/2243 -92039/4486  29784/2243

which means x=159950/2243 , y=-92039/4486 and z=29784/2243 is the solution for the above given linear equation.

Example 3: Solving Inverse matrix

R




# create matrix A and B using given equations
A <- matrix(c(4, 7, 3, 6), ncol = 2)
print(A)
  
print("Inverse matrix")
  
# Solve them using solve function in R
print(solve(A))


Output:

     [,1] [,2]
[1,]    4    3
[2,]    7    6
[1] "Inverse matrix"
          [,1]      [,2]
[1,]  2.000000 -1.000000
[2,] -2.333333  1.333333


Like Article
Suggest improvement
Share your thoughts in the comments

Similar Reads