如何在 R 中的 lpSolveAPI 处替换变量

How to substitute variable at lpSolveAPI in R

我正在通过 lpSolveAPI 求解线性程序,我想用对象函数的变量替换对象的变量。

例如,我像这样模仿我的原始lp

x5 <- x1 + x2
x6 <- x2 + x3 + x4

object funtion 
min x5 + x6 

subject to
x1 + x2                <=  2
         x3 +  x4      <=  5
      x2    +  x4      <=  3
x1, x2, x3, x4 = binary
x5, x6 = integer

to do this by lpSolveAPI, I try it like below


lprec <- make.lp(3, 4) # make.lp
var_lp <- matrix(c( rep(1, 12)), nrow = 3) # variable as var_lp

set.column(lprec, 1, var_lp[1,1], indices = 1) # s.t.
set.column(lprec, 2, c(var_lp[1,2], var_lp[3,2], indices = c(1,3))
set.column(lprec, 3, var_lp[2,3], indices = 2)
set.column(lprec, 4, c(var_lp[2,4], var_lp[3,4], indices = c(2,3))

我不知道如何在 lpSolveAPI 中表达 x5、x6

感谢您的带领。我希望有人给我一个答案

*另外,我的原始数据有大约 5,000 个约束。 是否可以通过 lpSolveAPI 进行分析??

set.type函数允许您指定整数域

set.type(lprec, 5, type="integer")

不过,您需要增加对问题的定义:

lprec <- make.lp(5,6)

编辑:此问题的代码片段

library(lpSolveAPI)
lprec <- make.lp(5,6)
set.objfn(lprec, obj=c(1,1), indices=c(5,6)) # sense defaults to "min"
set.row(lprec, 1, xt=c(1,1), indices=c(1,2))
set.row(lprec, 2, xt=c(1,1), indices=c(3,4))
set.row(lprec, 3, xt=c(1,1), indices=c(2,4))
set.row(lprec, 4, xt=c(1,1,-1), indices=c(1,2,5))
set.row(lprec, 5, xt=c(1,1,1,-1), indices=c(2,3,4,6))
set.type(lprec, 1, type="binary")
set.type(lprec, 2, type="binary")
set.type(lprec, 3, type="binary")
set.type(lprec, 4, type="binary")
set.type(lprec, 5, type="integer")
set.type(lprec, 6, type="integer")
set.constr.type(lprec, types=c(rep("<=",3), rep("=",2)))
set.rhs(lprec, b=c(2,5,3,0,0))

您可以使用printwrite.lp来检查指定的程序是否是您要求解的程序。使用 solve 你可以计算出全零的解:

solve(lprec)
get.variables(lprec)

(我相信 lpSolve 隐含地假设所有变量都是非负的。)