使用LpSolve在R中设置线性编程优化? [英] Set up linear programming optimization in R using LpSolve?

查看:292
本文介绍了使用LpSolve在R中设置线性编程优化?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个优化问题,我试图根据列X的唯一值最大化z列,而且还限制在从X选取的每个唯一值中,Y的总和最多小于(在此示例)23.

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))

看起来像这样:

  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

结果应如下所示:

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

如何在lpSolve :: lp函数中设置此问题?

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

推荐答案

您正尝试使所选选项的z值之和最大化,这取决于两种约束:

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

  • 所选选项的y值之和不超过23
  • 您为每个唯一的x值恰好选择一个值

您可以为每个选项创建一个二进制变量,然后使用lpSolve求解:

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

这篇关于使用LpSolve在R中设置线性编程优化?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆