logo

Solving Linear Programming Problems with R 📂Optimization

Solving Linear Programming Problems with R

Overview

You can use the lpSolve package1. It is used by inputting A,b,cA, \mathbf{b}, \mathbf{c} of the Linear Programming Problem expressed in matrix form.

Code

Maximizex1+x2subject tox1+x21x13x22 \begin{matrix} \text{Maximize} & & x_{1} & + & x_{2} \\ \text{subject to} &-& x_{1} & + & x_{2} & \le & 1 \\ & & x_{1} & & & \le & 3 \\ & & & & x_{2} & \le & 2 \end{matrix}

Let’s solve a maximization problem as in x1,x20x_{1} , x_{2} \ge 0 with a simple example. In the fresh shrimp sushi restaurant, they solved this problem by hand using the Simplex Method and know the answer (x1,x2)=(3,2)\left( x_{1}^{\ast}, x_{2}^{\ast} \right) = (3,2). This Linear Programming Problem is expressed as:

OptimizecTxsubject toAxb \begin{matrix} \text{Optimize} & \mathbf{c}^{T} \mathbf{x} \\ \text{subject to} & A \mathbf{x} \le \mathbf{b} \end{matrix}

Given the form above, we denote c=(1,1)\mathbf{c} = (1,1), A=[111010]A = \begin{bmatrix} -1 & 1 \\ 1 & 0 \\ 1 & 0 \end{bmatrix}, b=(1,3,2)\mathbf{b} = (1,3,2) and solve it as follows. f.obj corresponds to c\mathbf{c}, f.con corresponds to AA, and f.rhs corresponds to b\mathbf{b}.

library(lpSolve)

f.obj <- c(1, 1)

f.con <- matrix(c(-1, 1,
                   1, 0,
                   0, 1), nrow = 3, byrow = TRUE)

f.dir <- c("<=",
           "<=",
           "<=")

f.rhs <- c(1,
           3,
           2)

lp("max", f.obj, f.con, f.dir, f.rhs)

lp("max", f.obj, f.con, f.dir, f.rhs)$solution

As a result, as we already knew, the answer is (x1,x2)=(3,2)=\left( x_{1}, x_{2} \right) = \left( 3,2 \right) = 3 2.

> lp("max", f.obj, f.con, f.dir, f.rhs)
Success: the objective function is 5 
> 
> lp("max", f.obj, f.con, f.dir, f.rhs)$solution
[1] 3 2

Environment

  • OS: Windows
  • R: v4.1.2
  • lpSolve v5.6.15

See Also