Created
September 7, 2015 20:45
-
-
Save atbradley/3ddbef7852cc3c9fa2f6 to your computer and use it in GitHub Desktop.
Simple linear programming function in R, with an example.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
lp <- function(givenName, givenQuantity, resources, needsChart) { | |
if ( !all.equal(names(resources), colnames(needsChart)[2:length(colnames(needsChart))]) ) { | |
warning("constraints and needsChart don't match.") | |
return(NA) | |
} else if ( dim(needsChart)[1] != 2 ) { | |
warning("Can only handle two products.") | |
return(NA) | |
} | |
sapply(givenQuantity, function(x) { | |
resources.left <- resources - (x * c(needsChart[needsChart$name==givenName,2:dim(needsChart)[2]], recursive=T)) | |
poss <- min(as.integer(resources.left / c(t(needsChart[needsChart$name!=givenName,2:dim(needsChart)[2]])))) | |
if ( poss < 0 ) return(NA) | |
poss | |
}) | |
} |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# Example for using the lp() function. | |
# Taken from _Spreadsheet modeling & decision analysis: | |
# A practical introduction to business analytics_, | |
# by Cliff Ragsdale | |
source('./linear-programming.R') | |
resources <- c(leather=6000, nylon=5400, core=3500, labor=2800, stitching=1500) | |
products = data.frame( | |
name=c('softball', 'baseball'), | |
leather=c(5, 4), | |
nylon=c(6, 3), | |
core=c(4,2), | |
labor=c(2.5, 2), | |
stitching=c(1,1) | |
) | |
softball.profit = 17-11 | |
baseball.profit = 15-10.5 | |
baseballs <- 1:1500 | |
softballs <- lp('baseball', baseballs, resources, products) | |
ppf <- data.frame(baseballs, softballs, profit=(baseballs*baseball.profit+softballs*softball.profit)) | |
optimum <- ppf[ppf$profit==max(ppf$profit, na.rm=T),][1,] | |
with(ppf, plot(baseballs, softballs, xlab="# Baseballs", ylab="# Softballs", type='l')) | |
with(optimum, { | |
abline(h=softballs, col=gray(.8)) | |
abline(v=baseballs, col=gray(.8)) | |
points(baseballs, softballs, pch=20) | |
text(baseballs, softballs, | |
sprintf('$%3$0.2f (%1$d, %2$d)', baseballs, softballs, profit), | |
adj=c(-.03,-.5), ps=10) | |
}) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment