-
-
Save hjgoode3/715b2606daab81d4d794fc7332761382 to your computer and use it in GitHub Desktop.
lpSolver script for fantasy football lineup optimization
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
runOptimizer <- function(excludes = list()) { | |
#Read in dataset | |
dataset<-read.csv("df_full.csv", stringsAsFactors = FALSE) | |
# remove excludes from dataset | |
if (length(excludes) > 1) { | |
dataset <- anti_join(dataset, excludes, by="id") | |
} | |
#Change variables to appropriate types | |
dataset$Pos <- as.factor(dataset$Pos) | |
#### Prepare constraint matrix of zeros ##### | |
A <- matrix(0, nrow = 7, ncol = nrow(dataset)) | |
#Designate the positions that are equivalent to each other when generating the optimal lineup | |
#There are 6 distinct positions and 1 constraint in which salary is < 50,000 | |
#I.e. A player with the position WR/RB/TE can fill the FLEX position | |
#Add a "1" to all position that can fill that position slot | |
#Set QB parameters | |
j<-1 | |
i<-1 | |
for (i in 1:nrow(dataset)){ | |
if (dataset$Pos[i]=="QB") | |
A[j,i]<-1 | |
} | |
#RB | |
j<-2 | |
i<-1 | |
for (i in 1:nrow(dataset)){ | |
if (dataset$Pos[i]=="RB") | |
A[j,i]<-1 | |
} | |
#WR | |
j<-3 | |
i<-1 | |
for (i in 1:nrow(dataset)){ | |
if (dataset$Pos[i]=="WR") | |
A[j,i]<-1 | |
} | |
#TE | |
j<-4 | |
i<-1 | |
for (i in 1:nrow(dataset)){ | |
if (dataset$Pos[i]=="TE") | |
A[j,i]<-1 | |
} | |
#FLEX | |
j<-5 | |
i<-1 | |
for (i in 1:nrow(dataset)){ | |
if (dataset$Pos[i]=="RB" || | |
dataset$Pos[i]=="WR" || | |
dataset$Pos[i]== "TE") | |
A[j,i]<-1 | |
} | |
#DST | |
j<-6 | |
i<-1 | |
for (i in 1:nrow(dataset)){ | |
if (dataset$Pos[i]=="DST") | |
A[j,i]<-1 | |
} | |
A[7, ] <- dataset$Salary # salary <= 50000 | |
# Prepare input for LP solver | |
objective.in <- dataset$Proj_Points | |
const.mat <- A | |
const.dir <- c('==', '>=','>=', '>=','==','==', '<=') | |
const.rhs <- c(1, 2, 3, 1, 7, 1, 50000) | |
# Generate optimal lineup with lp solve | |
require(lpSolve) | |
sol <- lp(direction = "max", objective.in, # maximize objective function | |
const.mat, const.dir, const.rhs, # constraints | |
all.bin = TRUE) # use binary variables only | |
### View the solution | |
inds <- which(sol$solution == 1) | |
sum(dataset$Salary[inds]) | |
solution<-dataset[inds, ] | |
#Print players in optimal lineup | |
solution | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment