Set up linear programming optimization in R using LpSolve?

僤鯓⒐⒋嵵緔 提交于 2020-01-15 10:16:09

问题


I have this optimization problem where I am trying to maximize column z based on a unique value from column X, but also within a constraint that each of the unique values picked of X added up column of Y most be less than (in this example) 23.

For example, I have this sample data:

d=data.frame(x=c(1,1,1,2,2,2,3,3,3),y=c(9,7,5,9,7,5,9,7,5),z=c(25,20,5,20,10,5,10,5,3))

Which looks like this:

  X  Y  Z 
1 1  9  25     
2 1  7  20   
3 1  5  5    
4 2  9  20    
5 2  7  10     
6 2  5  5    
7 3  9  10     
8 3  7  5               
9 3  5  5

The result should look like this:

  X  Y  Z 
1 1  9  25  
4 2  9  20     
9 3  5  5 

How do I set this problem up in the lpSolve::lp function?


回答1:


You are trying to maximize the sum of the z values of the selected options subject to two types of constraints:

  • The sum of the y values for the selected options does not exceed 23
  • You select exactly one value for each unique x value

You can create a binary variable for each option and then solve with lpSolve:

d=data.frame(x=c(1,1,1,2,2,2,3,3,3),y=c(9,7,5,9,7,5,9,7,5),z=c(25,20,5,20,10,5,10,5,3))
library(lpSolve)
all.x <- unique(d$x)
d[lp(direction = "max",
     objective.in = d$z,
     const.mat = rbind(outer(all.x, d$x, "=="), d$y),
     const.dir = rep(c("==", "<="), c(length(all.x), 1)),
     const.rhs = rep(c(1, 23), c(length(all.x), 1)),
     all.bin = TRUE)$solution == 1,]
#   x y  z
# 1 1 9 25
# 4 2 9 20
# 9 3 5  3


来源:https://stackoverflow.com/questions/46779740/set-up-linear-programming-optimization-in-r-using-lpsolve

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!