Solving Linear Programming Problems with R
Overview
You can use the lpSolve
package1. It is used by inputting of the Linear Programming Problem expressed in matrix form.
Code
Let’s solve a maximization problem as in with a simple example. In the fresh shrimp sushi restaurant, they solved this problem by hand using the Simplex Method and know the answer . This Linear Programming Problem is expressed as:
Given the form above, we denote , , and solve it as follows. f.obj
corresponds to , f.con
corresponds to , and f.rhs
corresponds to .
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 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