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, \mathbf{b}, \mathbf{c}$ of the Linear Programming Problem expressed in matrix form.

Code

$$ \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 $x_{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 $\left( x_{1}^{\ast}, x_{2}^{\ast} \right) = (3,2)$. This Linear Programming Problem is expressed as:

$$ \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 $\mathbf{c} = (1,1)$, $A = \begin{bmatrix} -1 & 1 \\ 1 & 0 \\ 1 & 0 \end{bmatrix}$, $\mathbf{b} = (1,3,2)$ and solve it as follows. f.obj corresponds to $\mathbf{c}$, f.con corresponds to $A$, and f.rhs corresponds to $\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 $\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