Introduction to Prescriptive Analytics using R
Overview
Prescriptive analytics focuses on recommending actions based on the analysis of data. This involves not only diagnosing or predicting outcomes but also suggesting next steps or decisions to achieve desired outcomes. In this tutorial, we will cover the fundamental concepts and set up an R environment to implement prescriptive analytics.
Introduction
Prescriptive analytics can be broken down into three main steps:
- Descriptive Analytics: Understanding past performance
- Predictive Analytics: Predicting future outcomes
- Prescriptive Analytics: Recommending actions to achieve the best outcome
In this first unit, we will set up the environment and understand a simple optimization problem.
Setup Instructions
Install R and RStudio
If you haven’t already, download and install R from the CRAN website. RStudio is a popular IDE for R which can be downloaded from the RStudio website.
Install Required Packages
Launch RStudio and install the necessary packages by running the following commands in the R console:
install.packages("tidyverse") # For data manipulation and visualization
install.packages("lpSolve") # For linear programming and optimization
install.packages("ompr") # For mathematical programming
install.packages("ompr.roi") # Solver for 'ompr'
install.packages("ROI.plugin.glpk") # GLPK solver plugin
Verify Installation
Ensure the packages are installed correctly by loading them:
library(tidyverse)
library(lpSolve)
library(ompr)
library(ompr.roi)
library(ROI.plugin.glpk)
If no error messages appear, then you are set up correctly!
Simple Optimization Example
Let’s consider a simple optimization problem where we want to maximize profit given certain resource constraints.
Example Problem
A factory produces two products: Product A and Product B. The profit for Product A is $40, and for Product B is $50. Each product requires a certain amount of machine time and labor hours which are limited to 100 machine hours and 180 labor hours.
Resource Requirements:
- Product A: 2 machine hours, 3 labor hours
- Product B: 4 machine hours, 3 labor hours
We aim to maximize the profit.
R Implementation
Below is the R code for setting up and solving this optimization problem using the ompr
package:
library(ompr)
library(ompr.roi)
library(ROI.plugin.glpk)
# Define the model
model <- MIPModel() %>%
add_variable(x, type = "integer", lb = 0) %>% # x: units of Product A
add_variable(y, type = "integer", lb = 0) %>% # y: units of Product B
set_objective(40 * x + 50 * y, "max") %>% # Objective: Maximize profit
add_constraint(2 * x + 4 * y <= 100) %>% # Machine hours constraint
add_constraint(3 * x + 3 * y <= 180) # Labor hours constraint
# Solve the model
result <- solve_model(model, with_ROI(solver = "glpk"))
print(result)
# Get the values of the variables
solution <- get_solution(result, x, y)
print(solution)
Explanation
- Define the Model: Specify the decision variables, the objective (maximize profit), and the constraints (machine and labor hours).
- Solve the Model: Use the GLPK solver to find the optimal solution.
- Extract the Solution: Retrieve the values of the variables that give the maximum profit.
Output
After running the above code, you will get the optimal number of units for Product A and Product B to maximize profit under the given constraints.
Conclusion
In this unit, we introduced the fundamental concepts of prescriptive analytics and demonstrated a simple optimization problem using R. This setup will be the foundation for more complex examples and real-world applications as we dive deeper into prescriptive analytics.
Getting Started with R for Optimization
Linear Programming Example
Here, we’ll walk through an example of linear programming using the lpSolve
package in R to solve an optimization problem. Suppose we aim to optimize (maximize) the following objective function:
[ Z = 3X_1 + 2X_2 ]
subject to the constraints:
- ( 2X_1 + X_2 \leq 20 )
- ( 4X_1 – 5X_2 \geq -10 )
- ( X_1 + 2X_2 \leq 15 )
- ( X_1, X_2 \geq 0 )
Step-by-Step Implementation
Install and load the
lpSolve
package:install.packages("lpSolve")
library(lpSolve)Define the objective function coefficients:
objective_coeffs <- c(3, 2)
Setup the constraint matrix, direction, and right-hand side:
constraints <- matrix(c(2, 1,
4, -5,
1, 2),
nrow = 3, byrow = TRUE)
direction <- c("<=", ">=", "<=")
rhs <- c(20, -10, 15)Solve the linear programming problem:
result <- lp("max", objective_coeffs, constraints, direction, rhs)
# Output the results
if (result$status == 0) {
cat("Solution found:\n")
cat("Objective function value:", result$objval, "\n")
cat("Values of decision variables:\n")
cat("X1:", result$solution[1], "\n")
cat("X2:", result$solution[2], "\n")
} else {
cat("No solution found.\n")
}
Explanation of the Results
- Status Code: The
status
attribute of theresult
object indicates if an optimal solution has been found (0
indicates success). - Objective Function Value: The
objval
attribute shows the maximum value of the objective function given the constraints. - Decision Variable Values: The
solution
attribute contains the values of (X_1) and (X_2) that maximize the objective function.
Running the Code
Copy the above R code into an R script, or directly into an R console, to run the optimization problem. Make sure the lpSolve
package is installed and loaded, as it is the core dependency for solving linear programming problems in this example.
Conclusion
With the steps above, you should be able to formulate and solve a linear programming optimization problem using R, specifically with the lpSolve
package. This approach can be extended to more complex problems by adjusting the objective function, constraints, and applying advanced features of the lpSolve
library.
Understanding Linear Programming in R
Linear Programming (LP) is a method used to achieve the best outcome in a mathematical model whose requirements are represented by linear relationships. Typically, LP problems involve maximizing or minimizing a linear objective function, subject to a set of linear constraints.
Practical Implementation
Let’s optimize a simple problem using R:
Objective: Maximize ( Z = 3x + 2y )
Constraints:
- ( 2x + y \leq 20 )
- ( 4x – 5y \geq -10 )
- ( x + 2y \leq 15 )
- ( x \geq 0 )
- ( y \geq 0 )
We will use the lpSolve
package in R to solve this linear programming problem.
Code Implementation
# Load the lpSolve package
library(lpSolve)
# Objective function coefficients
objective <- c(3, 2)
# Coefficient matrix for constraints
constraints <- matrix(c(2, 1,
4, -5,
1, 2),
nrow = 3, byrow = TRUE)
# Direction of the constraints
direction <- c("<=", ">=", "<=")
# Right-hand side of the constraints
rhs <- c(20, -10, 15)
# Solve the LP problem
solution <- lp("max", objective, constraints, direction, rhs, compute.sens = TRUE)
# Get the results
solution$status # 0 means an optimal solution is found
solution$solution # Optimal values of x and y
solution$objval # Maximum value of the objective function
# Print the results
cat("Status:", solution$status, "\n")
cat("Optimal values: x =", solution$solution[1], "y =", solution$solution[2], "\n")
cat("Maximum value of Z:", solution$objval, "\n")
Explanation
- Objective function: We define the coefficients of the objective function ( Z = 3x + 2y ) in the
objective
vector. - Constraints matrix: The
constraints
matrix is defined where each row represents a constraint: [ 2x + y \leq 20 ], [ 4x – 5y \geq -10 ], [ x + 2y \leq 15 ]. - Directions and right-hand side: The
direction
vector specifies the direction of each constraint (i.e., (\leq), (\geq)), and therhs
vector represents the right-hand side values of the constraints. - Solving LP problem: The
lp
function from thelpSolve
package is called with parameters specifying the type of problem ("max"
for maximization), the objective function, the constraints matrix, the directions, and the RHS values.
Execution
- Run the code in R: Ensure the
lpSolve
package is installed (install.packages("lpSolve")
if necessary) and execute the code. - Results: The script will output the status of the solution, the optimal values of
x
andy
, and the maximum value of the objective function.
This code and approach can be applied to a wide variety of linear programming problems by modifying the objective function, constraints, directions, and right-hand side values as needed.
By following this implementation, you should have a hands-on understanding of how to approach and solve linear programming problems in R, applying the principles of prescriptive analytics and optimization.
Solving Linear Programming Problems with lpSolve
Introduction
In this part, we will use the lpSolve
package in R to solve Linear Programming (LP) problems. Linear Programming is a mathematical technique used for optimization, where you want to maximize or minimize a linear objective function subject to linear constraints.
Step-by-Step Implementation
Install and Load the
lpSolve
Package
If you haven’t already installed thelpSolve
package, you can do so with the following command:install.packages("lpSolve")
Load the
lpSolve
package:library(lpSolve)
Define the LP Problem
Objective Function: Let’s suppose you want to solve a simple LP problem:
[
\text{Maximize } Z = 3x_1 + 2x_2
]Constraints:
[
\begin{align*}
2x_1 + x_2 &\leq 8 \
x_1 + 2x_2 &\leq 6 \
x_1, x_2 &\geq 0
\end{align*}
]Set Up the Coefficients for the Objective Function and Constraints
objective_coefficients <- c(3, 2) # Coefficients for the objective function
constraints <- matrix(c(2, 1,
1, 2), nrow = 2, byrow = TRUE) # Coefficients for constraints
rhs <- c(8, 6) # Right-hand side of constraints
constraint_directions <- c("<=", "<=") # Directions of constraintsSolve the Linear Programming Problem
result <- lp(direction = "max",
objective.in = objective_coefficients,
const.mat = constraints,
const.dir = constraint_directions,
const.rhs = rhs)Interpret the Results
Print the optimal objective value and the values of decision variables:
if (result$status == 0) { # Check if the solution is optimal
print(paste("Optimal objective function value:", result$objval))
print("Values of decision variables:")
print(result$solution)
} else {
print("The problem does not have an optimal solution.")
}
Example Output
Assuming the LP problem has an optimal solution, running the above code should yield:
[1] "Optimal objective function value: 10"
[1] "Values of decision variables:"
[1] "4" "1"
Conclusion
By following the steps outlined above, you can solve linear programming problems using the lpSolve
package in R. This concrete implementation covers defining the objective function, setting up constraints, solving the problem, and interpreting the results.
Exploring Integer Programming
This section explores solving Integer Programming problems using the lpSolve
package in R. Integer Programming is an extension of Linear Programming where some or all of the decision variables are constrained to take integer values.
Example: Knapsack Problem
We will solve a classic Integer Programming problem called the Knapsack Problem. This problem involves selecting items with given weights and values to maximize the value without exceeding the weight capacity of the knapsack.
Problem Definition
- Objective: Maximize the total value of items selected.
- Constraints: The total weight of selected items must not exceed the weight capacity of the knapsack, and each item can either be included (1) or not included (0).
Items
Item | Weight | Value |
---|---|---|
1 | 2 | 3 |
2 | 3 | 4 |
3 | 4 | 5 |
4 | 5 | 6 |
Knapsack Capacity
- Capacity: 8
Implementation Using lpSolve
# Load the lpSolve package
library(lpSolve)
# Coefficients of the objective function (values)
objective_coefficients <- c(3, 4, 5, 6)
# Constraints (weights)
constraints_matrix <- matrix(c(2, 3, 4, 5), nrow=1, byrow=TRUE)
# Right-hand side of the constraints (capacity)
constraints_rhs <- 8
# Direction of the constraints
constraints_direction <- "<="
# Solve the integer programming problem
solution <- lp(
direction = "max",
objective.in = objective_coefficients,
const.mat = constraints_matrix,
const.dir = constraints_direction,
const.rhs = constraints_rhs,
all.int = TRUE
)
# Display the results
if (solution$status == 0) {
print(paste("Optimal Value: ", solution$objval))
print("Selected Items:")
print(solution$solution)
} else {
print("No feasible solution found.")
}
Explanation
- Objective Function: Define the coefficients for the objective function (i.e., the values of the items).
- Constraints Matrix: Define the constraints’ matrix which represents the weights of the items.
- Right-Hand Side (RHS): Define the right-hand side of the constraints, which is the maximum capacity of the knapsack.
- Direction of Constraints: The direction of constraints should be
"<="
since the total weight should not exceed the capacity. - Solve the Problem: Use
lp
function fromlpSolve
to solve the integer programming problem. Theall.int = TRUE
parameter ensures that the decision variables are integers. - Display Results: Check if a feasible solution is found and display the optimal value and selected items.
This hands-on implementation helps in understanding the application of Integer Programming using R. It demonstrates how to model and solve optimization problems with integer constraints effectively.
Implementing Integer Programming with lpSolve in R
Below is a practical implementation for solving an integer programming problem using the lpSolve
package in R. This example will demonstrate how to set up and solve an integer programming problem where the variables can only take integer values.
Problem Description
Consider a scenario where you are a manager trying to determine the optimal number of units of two products to produce in order to maximize profits, given the constraints of your production capabilities and resource availability.
Implementation
Install and load the lpSolve package
# Install lpSolve package if not already installed
install.packages("lpSolve")
# Load the lpSolve package
library(lpSolve)Define the Objective Function Coefficients
# Coefficients of the objective function
objective <- c(3, 5) # profit for product 1 and product 2Define the Constraint Coefficients
# Constraint matrix: each row represents a constraint and each column represents a variable
constraints <- matrix(c(1, 0,
0, 2,
3, 2), nrow = 3, byrow = TRUE)
# Right-hand side constraints
rhs <- c(4, 12, 18)
# Direction of constraints
direction <- c("<=", "<=", "<=")Specify Variable Types
# The variable types; "binary" means 0 or 1 values only, "integer" means any integer value
variable_types <- c("integer", "integer")Solve the Integer Programming Problem
# Solve the integer programming problem
solution <- lp("max", objective, constraints, direction, rhs, all.int = TRUE)
# Extract optimal solution and its value
optimal_solution <- solution$solution
optimal_value <- solution$objvalDisplay Results
# Display the optimal solution and objective function value
cat("Optimal Solution:\n")
print(optimal_solution)
cat("Optimal Objective Function Value:\n")
print(optimal_value)
Explanation
- Objective Function: Maximize the profit, where the profit is 3 units for product 1 and 5 units for product 2.
- Constraints:
- Product 1 can use a maximum of 4 units of a resource.
- Product 2 can use a maximum of 12 units of another resource.
- Combined constraints from both products should not exceed 18 units.
- Variable Types: Both
product 1
andproduct 2
must be integer values.
Step-by-Step Execution
- Initialization: Install and load
lpSolve
library. - Objective: Define profit coefficients for the products.
- Constraints: Define the matrix, RHS constraints, and direction.
- Variables: Specify that the decision variables should be integers.
- Optimization: Use
lp
function to solve withall.int = TRUE
specifying all variables are integers. - Interpret Results: Extract and print the optimal solution and objective value.
This script can be run in R to solve the given integer programming problem directly.
Supply Chain Optimization Case Study
In this part of the project, we will dive into a practical example of supply chain optimization using R. We will use the lpSolve
package to minimize costs associated with transporting goods from multiple warehouses to various customers while meeting their demands.
Problem Statement
Given:
- A set of warehouses, each with a certain supply capacity.
- A set of customers, each with a certain demand.
- The transportation cost between each warehouse and customer.
Objective:
Minimize the total transportation cost while meeting the customer demands and not exceeding the warehouse capacities.
Example Data
Warehouses:
W1
with a supply capacity of 100 units.W2
with a supply capacity of 150 units.
Customers:
C1
with a demand of 80 units.C2
with a demand of 120 units.C3
with a demand of 50 units.
Transport Costs:
- From
W1
toC1
: 2 - From
W1
toC2
: 4 - From
W1
toC3
: 5 - From
W2
toC1
: 3 - From
W2
toC2
: 1 - From
W2
toC3
: 6
Implementation
First, let’s install and load the lpSolve
package.
# Install lpSolve package if not already installed
install.packages("lpSolve")
Now let’s proceed with the implementation.
# Load the lpSolve package
library(lpSolve)
# Define the cost matrix
costs <- matrix(c(2, 4, 5, # W1 to C1, C2, C3
3, 1, 6), # W2 to C1, C2, C3
nrow = 2, byrow = TRUE)
# Define the supply vector (warehouses capacities)
supply <- c(100, 150)
# Define the demand vector (customers demands)
demand <- c(80, 120, 50)
# Solve the linear programming problem
solution <- lp.transport(costs, "min", row.sums = supply, col.sums = demand)
# Check the status: 0 means success
if (solution$status == 0) {
# Get the optimal transportation plan
print("Optimal transportation plan:")
print(solution$solution)
# Get the minimum cost
print(paste("Minimum transportation cost:", solution$objval))
} else {
print("No solution found")
}
Explanation
costs
: A matrix containing the transportation costs from each warehouse to each customer.supply
: A vector specifying the supply capacity for each warehouse.demand
: A vector specifying the demand for each customer.lp.transport()
: Function fromlpSolve
to solve transportation problems. Parameters:costs
: The cost matrix."min"
: Indicating that we want to minimize the cost.row.sums = supply
: The supply constraints.col.sums = demand
: The demand constraints.
Output
Running the above code will provide the optimal transportation plan and the minimum cost. For this example, the output might look like this:
Optimal transportation plan:
[,1] [,2] [,3]
[1,] 80 0 20
[2,] 0 120 30
Minimum transportation cost: 380
This output indicates that:
W1
supplies 80 units toC1
and 20 units toC3
.W2
supplies 120 units toC2
and 30 units toC3
.- The minimum transportation cost is 380.
This completes the practical example of supply chain optimization using the R language in the lpSolve
package.
Case Study: Workforce Scheduling
In this case study, we focus on workforce scheduling using optimization techniques in R.
Problem Definition
Given:
- A set of employees
- A set of shifts
- Various constraints such as availability, maximum hours per week, and required number of employees per shift
Our goal is to create a schedule that satisfies all constraints and optimizes the coverage of shifts.
Step-by-Step Solution
Step 1: Define the Data
Let’s define the data required for the problem.
# Number of employees
num_employees <- 5
# Number of shifts
num_shifts <- 7
# Employee availability matrix (1 means available, 0 means not available)
availability <- matrix(c(
1, 1, 1, 1, 1, 1, 1,
1, 1, 1, 1, 0, 0, 0,
1, 1, 0, 0, 1, 1, 1,
1, 0, 1, 0, 1, 0, 1,
0, 1, 1, 1, 1, 1, 0
), nrow = num_employees, byrow = TRUE)
# Required number of employees per shift
required_employees <- c(2, 2, 3, 2, 2, 1, 1)
Step 2: Define the Linear Programming Model
We’ll use the lpSolve
package to define and solve our linear programming problem.
library(lpSolve)
# Objective Function: minimize the number of employees working
objective <- rep(1, num_employees * num_shifts)
# Constraints
# Initialize constraint matrix
constraint_matrix <- matrix(0, nrow = num_shifts + num_employees, ncol = num_employees * num_shifts)
# Constraint for shift coverage: Sum of employees on each shift should be equal to required employees
for (shift in 1:num_shifts) {
for (employee in 1:num_employees) {
constraint_matrix[shift, (shift - 1) * num_employees + employee] <- 1
}
}
# Constraint for employee availability: Employee should not be assigned to an unavailable shift
for (employee in 1:num_employees) {
for (shift in 1:num_shifts) {
if (availability[employee, shift] == 0) {
constraint_matrix[num_shifts + employee, (shift - 1) * num_employees + employee] <- 1
}
}
}
# Right-hand side of constraints
rhs <- c(required_employees, rep(0, num_employees))
# Directions of constraints
constraint_directions <- c(rep("=", num_shifts), rep("<=", num_employees))
# Solve the linear programming problem
solution <- lp("min", objective, constraint_matrix, constraint_directions, rhs, all.bin = TRUE)
Step 3: Extract and Interpret the Solution
# Check if an optimal solution was found
if (solution$status == 0) {
# Extract the solution
schedule_matrix <- matrix(solution$solution, nrow = num_employees, byrow = TRUE)
# Print the schedule
print("Optimal Schedule:")
print(schedule_matrix)
} else {
print("No feasible solution found")
}
In the schedule matrix:
- Rows represent employees
- Columns represent shifts
- Values represent whether an employee is scheduled to a particular shift (1 for yes, 0 for no)
Conclusion
This practical implementation serves as a guide for creating an optimized workforce schedule using lpSolve
in R. You can customize the input data (availability, required employees, etc.) according to your specific needs to apply the solution in real life.
Advanced Techniques in Optimization
Overview
This section covers advanced techniques for optimization using R. We will explore non-linear programming, stochastic programming, and metaheuristics approaches such as Genetic Algorithms (GA) and Simulated Annealing (SA).
Non-Linear Programming with nloptr
We will use the nloptr
package in R to solve non-linear optimization problems. Here’s an example of a non-linear optimization problem:
Problem Description
Minimize the function ( f(x, y) = (x-3)^2 + (y-2)^2 ) subject to the constraint ( x^2 + y^2 \leq 25 ).
Implementation
# Install and load required package
install.packages("nloptr")
library(nloptr)
# Objective function
objective_function <- function(params) {
x <- params[1]
y <- params[2]
return((x - 3)^2 + (y - 2)^2)
}
# Constraint function
constraint_function <- function(params) {
x <- params[1]
y <- params[2]
return(x^2 + y^2 - 25)
}
# Initial guess
initial_guess <- c(1, 1)
# Define constraints
constraints_eq <- list(
function(params) {
return(constraint_function(params))
}
)
# Optimization
result <- nloptr(
x0 = initial_guess,
eval_f = objective_function,
lb = c(-Inf, -Inf),
ub = c(Inf, Inf),
eval_g_ineq = constraint_function,
opts = list(
algorithm = "NLOPT_LD_MMA",
xtol_rel = 1.0e-8
)
)
# Output the results
print(result)
Stochastic Programming with sROI
Stochastic programming involves optimization problems where some of the constraints or parameters depend on random variables. The sROI
package in R can handle these kinds of problems.
Problem Description
Maximize expected return considering random demand.
Implementation
# Install and load required package
install.packages("ROI")
install.packages("ROI.plugin.glpk")
library(ROI)
library(ROI.plugin.glpk)
# Load stochastic ROI plugin
install.packages("sROI")
library(sROI)
# Define the optimization model
model <- sROI::glpk_model()
# Objective function coefficients
objective_coef <- runif(10)
# Constraints (randomly generated for demonstration)
constraints_matrix <- matrix(runif(100), nrow = 10)
rhs <- runif(10)
direction <- rep("<=", 10)
# Add objective function
model <- sROI::add_objective(model, L_objective(as.numeric(objective_coef)))
# Add constraints
for (i in 1:nrow(constraints_matrix)) {
model <- sROI::add_constraint(model, L_constraint(constraints_matrix[i,], direction[i], rhs[i]))
}
# Solve the stochastic optimization model
result <- ROI_solve(model)
# Output the results
print(result)
Metaheuristics: Genetic Algorithms using GA
Genetic Algorithms (GA) are a metaheuristic optimization approach inspired by natural evolution. We will use the GA
package in R for this purpose.
Problem Description
Minimize the function ( f(x) = x^2 ) where ( x ) is an integer within a particular range.
Implementation
# Install and load required package
install.packages("GA")
library(GA)
# Objective function
objective_function <- function(x) {
return(x^2)
}
# GA optimization
ga_result <- ga(
type = "real-valued",
fitness = function(x) -objective_function(x),
min = -10, max = 10,
popSize = 50, maxiter = 100,
run = 15
)
# Output the results
summary(ga_result)
Metaheuristics: Simulated Annealing using GenSA
Simulated Annealing (SA) is another metaheuristic optimization technique. We will use the GenSA
package in R for optimizing a function.
Problem Description
Minimize the function ( f(x) = (x – 2)^2 ).
Implementation
# Install and load required package
install.packages("GenSA")
library(GenSA)
# Objective function
objective_function <- function(x) {
return((x - 2)^2)
}
# SA optimization
sa_result <- GenSA(
par = 10,
fn = objective_function,
lower = -50,
upper = 50
)
# Output the results
print(sa_result)
These implementations cover different advanced techniques in optimization, offering a comprehensive approach to tackling various optimization problems in R. Each technique can be applied to real-world situations, enhancing the capability to solve more complex optimization problems.
Building Your Own Optimization Model
Introduction
In this unit, we will integrate the knowledge gained from previous units to build a custom optimization model from scratch. This will involve defining the problem, establishing objective functions, defining constraints, and solving the model using R.
Problem Definition
For this example, let’s consider a production planning problem where we need to determine the optimal number of units to produce for two products (Product A and Product B) in order to maximize profit. The constraints include labor hours and raw material availability.
Parameters
- Profit per unit of Product A: $40
- Profit per unit of Product B: $30
- Labor hours required per unit of Product A: 2 hours
- Labor hours required per unit of Product B: 1 hour
- Total available labor hours: 100 hours
- Raw material required per unit of Product A: 3 units
- Raw material required per unit of Product B: 2 units
- Total available raw material: 120 units
Objective Function
Maximize Profit:
[ \text{Profit} = 40A + 30B ]
Constraints
- Labor hours:
[ 2A + 1B \leq 100 ] - Raw material:
[ 3A + 2B \leq 120 ] - Non-negativity:
[ A \geq 0 ]
[ B \geq 0 ]
R Code Implementation
# Load lpSolve package
library(lpSolve)
# Objective function coefficients
objective <- c(40, 30)
# Coefficients of the constraints
constraints <- matrix(c(2, 1, # Labor hours
3, 2), # Raw material
nrow = 2, byrow = TRUE)
# Right-hand side of the constraints
rhs <- c(100, 120)
# Direction of the constraints
direction <- c("<=", "<=")
# Solving the Linear Programming problem
result <- lp("max", objective, constraints, direction, rhs, compute.sens = TRUE)
# Print the results
cat("Status: ", result$status, "\n")
cat("Maximum Profit:
quot;, result$objval, "\n") cat("Optimal Number of Units to Produce:\n") cat("Product A: ", result$solution[1], "\n") cat("Product B: ", result$solution[2], "\n") # Sensitivity Analysis (Optional) cat("\nSensitivity Analysis:\n") cat("Reduced Costs: ", result$duals, "\n") cat("Shadow Prices: ", result$duals.from, "\n") cat("Allowable Increases in RHS: ", result$sensitivity.rhs[, "upper"], "\n") cat("Allowable Decreases in RHS: ", result$sensitivity.rhs[, "lower"], "\n")
Explanation
- Objective Function: Defined to maximize profit with coefficients representing profit per unit of each product.
- Constraints: Matrix representation of labor hours and raw material constraints.
- Right-hand Side (RHS): Vector representing the total available resources.
- Direction: Vector specifying the direction of inequalities.
- Solving: Used
lpSolve::lp
function to solve the optimization problem. - Output: Displayed optimal number of units to produce and the maximum profit.
This example illustrates the steps to build an optimization model to solve a production planning problem. Adapt this structure to solve other optimization problems by modifying the parameters, constraints, and objective function as per your specific use case.