在给定约束条件下,使用optimx选择最大化变量的数据集子集?

时间:2016-05-09 21:44:03

标签: r

我试图了解如何在optimx中正确设置约束,以在给定约束(总薪水,玩家数量等)的情况下最大化该数据框架内变量(总体性能)的总和。任何指导表示赞赏。理想情况下,最终结果将根据优化更改每个玩家的on.team变量(TRUE / FALSE)。这是我到目前为止的尝试:

# Optimize team roster

require(optimx)

# player data

players <- data.frame(player.name = c("player1", "player2", "player3", "player4", "player5"), 
                      position = c("goalkeeper", "defender", "midfielder", "forward", "midfielder"), 
                      performance = c(10, 20, 30, 40, 50), 
                      salary = c(50000, 80000, 100000, 60000, 70000), 
                      on.team = c(TRUE, TRUE, TRUE, TRUE, TRUE)
                      )

# constraints

max.players <- 3
max.team.salary <- 300000

# parameters to optimize (on.team) with constraints: team.count.players <= max.players and team.salary <= max.team.salary

# function to maximize combined performance of selected players

fn.optimize <- function(players) {
  team.performance <- aggregate(performance ~ performance, data = subset(players, on.team == TRUE), FUN = sum)
  team.salary <- aggregate(salary ~ salary, data = subset(players, on.team == TRUE), FUN = sum)
  team.count.players <- aggregate(on.team ~ on.team, data = subset(players, on.team == TRUE), FUN = sum)
  return(as.numeric(team.performance))
}

# Select the optimium group of players

optimx(players$on.team, function(x) fn.optimize(players))

0 个答案:

没有答案