1
library(tidyr)
library(dplyr)
library(lpSolve)

rm(list = ls())
gc()

set.seed(1)

# inital list of players
player_df <- tibble(
  player = 1:100,
  position = sample(x = LETTERS[1:10], size = 100, replace = TRUE),
  stat = rnorm(n = 100, mean = 10, sd = 2),
  is_utility = rbinom(n = 100, size = 1, prob = 0.25)
)


# add on players that can play in the utility role
player_df <- bind_rows(
  player_df,
  player_df |>
    filter(is_utility == 1) |>

    # this replaces the current position with a new position different than initial list
    mutate(
      position = lapply(
        position,
        function(x){
          replaced_x <- sample(LETTERS[1:10], size = 1)
          while(x == replaced_x){
            replaced_x <- sample(LETTERS[1:10], size = 1)
          }
          return(replaced_x)
        }
      ) |> unlist()
    )
  )

# create binary encoding for each player
for(x in unique(player_df$player)){
  player_df[,paste0("is_",x)] <- (player_df$player == x)*1
}

# create binary encoding for each position
for(y in unique(player_df$position)){
  player_df[,paste0("is_",y)] <- (player_df$position == y)*1
}

# remove the original columns and convert to a matrix
model_matrix <- player_df |>
  select(-player, -position, -stat, -is_utility) |>
  t()

# assign how the matrix will be compared to the constraint_rhs
constraint_direction  <- c(
  rep("<=", length(unique(player_df$player))),
  rep("<=", length(unique(player_df$position)))
)

# assign the bounds for the model solution
constraint_rhs <- c(
  rep(1, length(unique(player_df$player))),
  rep(1, length(unique(player_df$position)))
)

# assign the value being optimized
obj_in <- player_df$stat

lp_solution <- lp(
  direction = "max",
  objective.in = obj_in,
  const.mat = model_matrix,
  const.dir = constraint_direction,
  const.rhs = constraint_rhs
)

# bring the optimized solution into the original df
player_df$is_optimized <- lp_solution$solution

player_df <- player_df |>
  arrange(desc(is_optimized)) |>
  select(player, position, stat, is_utility, is_optimized)

For immediate assistance, please email our customer support: [email protected]

Download RAW File