r 如何使用 lpSolve 和限制选择的行

r how to use lpSolve and limit rows selected

我正在尝试在 R 中复制一个 Excel 求解器模型。开始寻找最大化点数是一个简单的问题,唯一的限制是限制可以播放的事件数。所以我有一个两列的数据框,其中包含锦标赛编号和项目积分。在 Excel 中,我们有一个 Play Yes/no 二进制列并将其乘以点并设置为最大化,允许模型将 Play Yes/No 列更改为 0 或 1。约束限制了play yes/no 变量与约束值的总和,例如 25.

library(lpSolve)
tournament<-rep(1:48,1)
mean<-c(12.2,30.4,30.9,44.1,31.3,27.6,31.5,25.0,31.2,24.0,28.0,23.9,14.1,9.5,17.2,37.8,30.5,43.0,32.1,30.7,30.2,37.0,32.1,28.9,23.7,4.6,29.0,29.1,30.7,31.6,49.5,25.1,30.2,10.3,30.3,21.8,88.5,31.0,30.9,2.9,31.1,30.3,29.7,63.7,31.6,91.6,30.6,31.0)

aggdata<-data.frame(tournament,mean)

maxevents <-25

obj<-aggdata$mean
con <- rep(1,nrow(aggdata))
dir <- c("==")
rhs <- maxevents
result <- lp("max", obj, con, dir, rhs, all.bin = TRUE)

结果只查看数据框的 3 行,它应该查看前 25 行。最后,我将添加额外的约束,因为我知道这个简单示例不需要 lp,但需要通过首先是这个障碍。

library(lpSolve)

#objective function
obj <- rep(1, nrow(aggdata))

#constraints
con <- matrix(c(obj <- rep(1, nrow(aggdata)),
                as.vector(aggdata$point)), nrow = 2, byrow = T)  #you can add another constraints here and make 'nrow' equals to number of total constraints
dir <- c("==", "<=")
rhs <- c(25,     #total number of tournament
         1000)   #let's assume that total points can't exceeds 1000

#optimization solution
result <- lp ("max", obj, con, dir, rhs, all.bin=TRUE)
result$solution

示例数据:

aggdata <- data.frame(tournament = rep(1:48,1),
                      point = c(12.2,30.4,30.9,44.1,31.3,27.6,31.5,25.0,31.2,24.0,28.0,23.9,14.1,
                               9.5,17.2,37.8,30.5,43.0,32.1,30.7,30.2,37.0,32.1,28.9,23.7,4.6,
                               29.0,29.1,30.7,31.6,49.5,25.1,30.2,10.3,30.3,21.8,88.5,31.0,30.9,
                               2.9,31.1,30.3,29.7,63.7,31.6,91.6,30.6,31.0))
#  tournament point
#1          1  12.2
#2          2  30.4
#3          3  30.9
#4          4  44.1
#5          5  31.3
#6          6  27.6