R Team Roster Optimization w/ lpSolve -
i new r , have particular fantasy sports team optimization problem solve. have seen other posts use lpsolve similar problems can not seem wrap head around code. example data table below. every player on team, plays particular role, has salary, , has avg points produced per game. constraints need need 8 players. no more 3 players may come 1 team. there must @ least 1 player each role (of 5). , cumulative salary must not exceed $10,000.
team player role avgpts salary bears 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, write in 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 works fine in producing optimal fantasy team without limitation of no more 3 players may come 1 team. stuck , suspect relates con
argument. appreciated.
what if added similar way did roles con
?
if add t(model.matrix(~ team + 0, df))
you'll have indicators each team in constraint. example gave:
> 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
we need update dir
, rhs
account this:
dir <- c(">=",">=",">=",">=",">=",rep('<=',n_teams),"<=","<=") rhs <- c(1,1,1,1,1,rep(3,n_teams),8,10000)
with n_teams
set appropriately.
Comments
Post a Comment