# Install the lpSolve package if you haven't
#install.packages("lpSolve")
# Load the package
library(lpSolve)Warning: package 'lpSolve' was built under R version 4.3.3
These two examples are ones we covered in class. One minimization of cost of production of to products and one more complex maximization on a split for a mutual fund.
Load these libraries into your environment. Remember you will like need to remove the hashtag in front of install.packages(“lpSolve”) to run the code in r
Let
[
\[\begin{aligned} A &= \text{number of gallons of product A to produce} \\ B &= \text{number of gallons of product B to produce} \end{aligned}\]]
Minimize the total production cost:
\[ Z = 2A + 3B \]
Customer demand for product A:
\[A \ge 125 \]
Minimum combined production requirement:
\[ A + B \ge 350 \]
Processing time limitation (600 hours):
\[ 2A + B \le 600 \]
Non-negativity constraints:
\[A,B \ge 0 \]
This code will walk you through the set up of the minimization progment and then the constraints
Let
[
\[\begin{aligned} x_1 &= \text{dollars invested in Atlantic Oil} \\ x_2 &= \text{dollars invested in Pacific Oil} \\ x_3 &= \text{dollars invested in Midwest Steel} \\ x_4 &= \text{dollars invested in Huber Steel} \\ x_5 &= \text{dollars invested in Government Bonds} \end{aligned}\]]
Maximize the total projected return:
\[ \text{Maximize } Z = 0.073x_1 + 0.103x_2 + 0.064x_3 + 0.075x_4 + 0.045x_5 \]
Total investment (available funds):
\[ x_1 + x_2 + x_3 + x_4 + x_5 = 100{,}000\]
Oil industry limit:
\[ x_1 + x_2 \le 50{,}000 \]
Steel industry limit:
\[ x_3 + x_4 \le 50{,}000 \]
Government bonds requirement (≥ 25 % of steel investment):
\[ x_5 \ge 0.25(x_3 + x_4) \] or equivalently \[ -x_5 + 0.25x_3 + 0.25x_4 \le 0 \]
Pacific Oil limit (≤ 60 % of total oil investment):
\[ x_2 \le 0.60(x_1 + x_2) \]
or equivalently \[ -0.6x_1 + 0.4x_2 \le 0 \]
Non-negativity:
\[ x_1,,x_2,,x_3,,x_4,,x_5 \ge 0 \]
Constraints
# Constraint matrix
constraints <- matrix(c(
# x1 x2 x3 x4 x5
1, 1, 1, 1, 1, # total investment = 100000
1, 1, 0, 0, 0, # oil ≤ 50000
0, 0, 1, 1, 0, # steel ≤ 50000
0, 0, 0.25, 0.25, -1, # bond ≥ 0.25*(steel)
-0.6, 0.4, 0, 0, 0 # Pacific Oil ≤ 0.6*(oil)
), nrow = 5, byrow = TRUE)
# Direction of constraints
directions <- c("=", "<=", "<=", "<=", "<=")
# Right-hand side of constraints
rhs <- c(100000, 50000, 50000, 0, 0)