Constraints in R Multiple Integer Linear Programming

≯℡__Kan透↙ 提交于 2019-12-08 06:22:06

问题


I am working on some code in R to optimize my fantasy football lineup but I am having some difficulty with one constraint. I basically have a list of players, their position, expected points, and cost.

Roster must include:

1 QB 2 RB 2 WR 1 TE 1 FLEX (either a RB, WR, or TE) Total cost under $200

My issue is that my code wants to pick the FLEX position as player it already selected as a WR, RB or TE. Here is the code I am using, I have a table that I imported with columns for player, position, points, and cost. In the table, any RB, WR, or TE is duplicated with the position as FLEX. I tried to change the line that sets pos=="FLEX" to pos=="WR"||pos=="RB"||pos=="TE" and that did not work, my only other idea is to run the code and if it duplicates the FLEX player I delete it from the source table. That is a bit of a pain though.

Any ideas are greatly appreciated.

name <- mydata$name
pos <- mydata$pos
pts <- mydata$pts
cost <- mydata$cost

num.players <- length(name)

f <- pts

var.types <- rep("B", num.players)

A <- rbind(as.numeric(pos=="QB")
         , as.numeric(pos=="RB")
         , as.numeric(pos=="WR")
         , as.numeric(pos=="TE")
         , as.numeric(pos=="FLEX")
         ,cost)

dir <- c("=="
        ,"=="
        ,"=="
        ,"=="
        ,"=="
        ,"<=")

b <- c(1
     , 2
     , 2
     , 1
     , 1
     , 200)

library(Rglpk)

sol <- Rglpk_solve_LP(obj = f
                , mat = A
                , dir = dir
                , rhs = b
                , types = var.types
                , max=TRUE)
sol

name[sol$solution == 1]

回答1:


You can rewrite:

1 QB 2 RB 2 WR 1 TE 1 FLEX (either a RB, WR, or TE) 

As

num(QB) == 1
2 <= num(RB) <= 3
2 <= num(WR) <= 3
1 <= num(TE) <= 2
num(RB) + num(WR) + num(TE) == 6


来源:https://stackoverflow.com/questions/26150240/constraints-in-r-multiple-integer-linear-programming

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