Solve Linear Program Using R

R is an open source tool which is very popular among the data scientists for essential data science tasks. Performing linear programming is very easy and we can attain an optimum solution in very few steps. Come let’s learn.

Example: A toy manufacturing organization manufactures two types of toys A and B. Both the toys are sold at Rs.25 and Rs.20 respectively. There are 2000 resource units available every day from which the toy A requires 20 units while toy B requires 12 units. Both of these toys require a production time of 5 minutes. Total working hours are 9 hours a day. What should be the manufacturing quantity for each of the pipes to maximize the profits?

Here:

The objective function is:
Max.Z=25x+20y

where x are the units of pipe A

y are the units of pipe B

Constraints:
20x+12y<=2000

5x+5y<=540

Let’s see the code part now:

 

install.packages("lpSolve")

 

library(lpSolve)

 

 

 

 

 

 

 

#Setting the coefficients of decision variables

 

objective.in=c(25,20)

 

 

 

#Constraint Matrix

 

const.mat=matrix(c(20,12,5,5),nrow = 2,byrow = T)

 

 

 

#defining constraints

 

const_time=540  #in minutes

 

const_res=2000

 

 

 

#RHS for constraints

 

const.rhs=c(const_res,const_time)

 

 

 

#Direction for constraints

 

const.dir=c("<=","<=")

 

 

 

 

 

#Finding the optimum solution

 

opt=lp(direction = "max",objective.in,const.mat,const.dir,const.rhs)

 

summary(opt)

 

 

 

 

 

#Objective values of x and y

 

opt$solution

 

 

 

#Value of objective function at optimal point

 

opt$objval

view rawlpp.R hosted with by GitHub

 

Output

summary(opt)

 

Length Class Mode

direction 1 -none- numeric

x.count 1 -none- numeric

objective 2 -none- numeric

const.count 1 -none- numeric

constraints 8 -none- numeric

int.count 1 -none- numeric

int.vec 1 -none- numeric

bin.count 1 -none- numeric

binary.vec 1 -none- numeric

num.bin.solns 1 -none- numeric

objval 1 -none- numeric

solution 2 -none- numeric

presolve 1 -none- numeric

compute.sens 1 -none- numeric

sens.coef.from 1 -none- numeric

sens.coef.to 1 -none- numeric

duals 1 -none- numeric

duals.from 1 -none- numeric

duals.to 1 -none- numeric

scale 1 -none- numeric

use.dense 1 -none- numeric

dense.col 1 -none- numeric

dense.val 1 -none- numeric

dense.const.nrow 1 -none- numeric

dense.ctr 1 -none- numeric

use.rw 1 -none- numeric

tmp 1 -none- character

status 1 -none- numeric

 

> opt$solution

[1] 88 20

 

> opt$objval

[1] 2600

 

Therefore from the output, we see that the organization should produce 88 units of toy A and 20 units of toy B and the maximum profit for the organization will be Rs.2600.