Reputation: 1515
I am trying to pick the best possible fantasy football team given different constraints. My goal is to pick the players that maximize the sum of their projected points.
The constraints are:
1) The team must include:
-1 QB
-2 RBs
-2 WRs
-1 TE
2) A player's risk must not exceed 6
3) The sum of the players' costs must not exceed 300.
How can I do this? What is the best package/function in R to optimize these constraints? What would the function call look like to maximize the projected points given these constraints? FYI, I'll be searching through 100-300 players.
Thanks in advance! Here is a small example data set:
name <- c("Aaron Rodgers","Tom Brady","Arian Foster","Ray Rice","LeSean McCoy","Calvin Johnson","Larry Fitzgerald","Wes Welker","Rob Gronkowski","Jimmy Graham")
pos <- c("QB","QB","RB","RB","RB","WR","WR","WR","TE","TE")
pts <- c(167, 136, 195, 174, 144, 135, 89, 81, 114, 111)
risk <- c(2.9, 3.4, 0.7, 1.1, 3.5, 5.0, 6.7, 4.7, 3.7, 8.8)
cost <- c(60, 47, 63, 62, 40, 60, 50, 35, 40, 40)
mydata <- data.frame(name, pos, pts, risk, cost)
Upvotes: 3
Views: 2388
Reputation: 89057
Your constraints and objective are linear, but your variables are binaries: whether each player should be picked or not. So your problem is a little more general than a Linear Programming (LP), it is a Mixed-Integer Programming (MIP). On CRAN's Optimization Task View, look for their MIP section.
CPLEX is a commercial solver you probably not have access to, but GLPK is free. If I were you, I would probably go with the high level interface Rglpk.
It will require you put your problem in matrix form, I suggest you look at the documentation and examples.
Edit: Here is an implementation:
# We are going to solve:
# maximize f'x subject to A*x <dir> b
# where:
# x is the variable to solve for: a vector of 0 or 1:
# 1 when the player is selected, 0 otherwise,
# f is your objective vector,
# A is a matrix, b a vector, and <dir> a vector of "<=", "==", or ">=",
# defining your linear constraints.
# number of variables
num.players <- length(name)
# objective:
f <- pts
# the variable are booleans
var.types <- rep("B", num.players)
# the constraints
A <- rbind(as.numeric(pos == "QB"), # num QB
as.numeric(pos == "RB"), # num RB
as.numeric(pos == "WR"), # num WR
as.numeric(pos == "TE"), # num TE
diag(risk), # player's risk
cost) # total cost
dir <- c("==",
"==",
"==",
"==",
rep("<=", num.players),
"<=")
b <- c(1,
2,
2,
1,
rep(6, num.players),
300)
library(Rglpk)
sol <- Rglpk_solve_LP(obj = f, mat = A, dir = dir, rhs = b,
types = var.types, max = TRUE)
sol
# $optimum
# [1] 836 ### <- the optimal total points
# $solution
# [1] 1 0 1 0 1 1 0 1 1 0 ### <- a `1` for the selected players
# $status
# [1] 0 ### <- an optimal solution has been found
# your dream team
name[sol$solution == 1]
# [1] "Aaron Rodgers" "Arian Foster" "LeSean McCoy"
# [4] "Calvin Johnson" "Wes Welker" "Rob Gronkowski
Upvotes: 8