Skip to content

Instantly share code, notes, and snippets.

@joaopcnogueira
Last active November 15, 2021 15:44
Show Gist options
  • Save joaopcnogueira/c503e47aa5042115cddb00e8c055a4e8 to your computer and use it in GitHub Desktop.
Save joaopcnogueira/c503e47aa5042115cddb00e8c055a4e8 to your computer and use it in GitHub Desktop.
Gist Example of Optimization and Linear Programming with R
# Import lpSolve package
library(lpSolve)
#
# Set up the problem: maximize
# z = 2*x1 + 11*x2 subject to
# 2*x1 + 2*x2 <= 20
# x1 + 2*x2 <= 12
# 3*x1 + 4*x2 <= 36
# x1 <= 5
# x1 >= 0
# x2 >= 0
# Set coefficients of the objective function
f.obj <- c(2, 11)
# Set matrix corresponding to coefficients of constraints by rows
# Do not consider the non-negative constraint; it is automatically assumed
f.con <- matrix(c(2, 2,
1, 2,
3, 4,
1, 0,
1, 0,
0, 1), nrow = 6, byrow = TRUE)
# Set unequality signs
f.dir <- c("<=",
"<=",
"<=",
"<=",
">=",
">=")
# Set right hand side coefficients
f.rhs <- c(20,
12,
36,
5,
0,
0)
# Solve: final value (z)
lp("max", f.obj, f.con, f.dir, f.rhs)
# Success: the objective function is 66
# Variables final values
lp("max", f.obj, f.con, f.dir, f.rhs)$solution
# x1 = 0 and x2 = 6
# Sensitivities
lp("max", f.obj, f.con, f.dir, f.rhs, compute.sens = TRUE)$sens.coef.from
lp("max", f.obj, f.con, f.dir, f.rhs, compute.sens = TRUE)$sens.coef.to
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment