R / lpSolve player list optimization
I am new to R and have a special fantasy sports team optimization problem that I would like to solve. I've seen other posts use lpSolve for similar problems, but I don't seem to lean around the code. Sample datasheet below. Each player is on a team, plays a specific role, has a salary and has points per game. I need restrictions, I need exactly 8 players. There can be no more than 3 players from one team. Each role must have at least one player (out of 5). And the total salary should not exceed $ 10,000.
Team Player Role Avgpts Salary
Bears A T 22 930
Bears B M 19 900
Bears C B 30 1300
Bears D J 25 970
Bears E S 20 910
Jets F T 21 920
Jets G M 26 980
[...]
In R I write in the following
> obj = DF$AVGPTS
> con = rbind(t(model.matrix(~ Role + 0, DF)), rep(1,nrow(DF)), DF$Salary)
> dir = c(">=",">=",">=",">=",">=","==","<=")
> rhs = c(1,1,1,1,1,8,10000)
> result = lp("max", obj, con, dir, rhs, all.bin = TRUE)
This code is great for creating an optimal fantasy- free team . The limit of no more than 3 players can come from any team. This is where I am stuck and I suspect it refers to the argument con
. Any help is appreciated.
source to share
What if you added something similar to how you performed roles in con
?
If you add t(model.matrix(~ Team + 0, DF))
, you will have indicators for each command in your constraint. For the example you provided:
> con <- rbind(t(model.matrix(~ Role + 0,DF)), t(model.matrix(~ Team + 0, DF)), rep(1,nrow(DF)), DF$Salary)
> con
1 2 3 4 5 6 7
RoleB 0 0 1 0 0 0 0
RoleJ 0 0 0 1 0 0 0
RoleM 0 1 0 0 0 0 1
RoleS 0 0 0 0 1 0 0
RoleT 1 0 0 0 0 1 0
TeamBears 1 1 1 1 1 0 0
TeamJets 0 0 0 0 0 1 1
1 1 1 1 1 1 1
930 900 1300 970 910 920 980
Now we need to update dir
and rhs
to account for this:
dir <- c(">=",">=",">=",">=",">=",rep('<=',n_teams),"<=","<=")
rhs <- c(1,1,1,1,1,rep(3,n_teams),8,10000)
With n_teams
set accordingly.
source to share