我刚刚开始学习R并遇到了一些我不确定如何处理代码的问题。
我正在创建一个data.frame,其中包含可以分配给项目的个人池。该项目需要一个BA,一个PM,两个SA,和另外一个可以是SA或BA 的人。每个人都有一个评级和相关的成本,我需要最高评级,同时保持成本低于一定的门槛。
我不确定如何实现上述方案中的粗体部分..以下代码正在运行,但并未考虑额外的BA / SA。
(这是自学..没有分配作业)
EDIT-Desired output ,其中最后一行可以是SA或BA位置。
name position rating cost BA PM SA
Matt SA 95 9500 0 0 1
Aaron BA 85 4700 1 0 0
Stephanie SA 95 9200 0 0 1
Molly PM 88 5500 0 1 0
Jake SA 74 5300 0 0 1
代码:
#load libraries
library(lpSolve)
# create data.frame
name = c("Steve", "Jeremy", "Matt", "Aaron", "Stephanie", "Molly", "Jake", "Tony", "Jay", "Katy", "Alison")
position = c("BA", "PM", "SA", "BA", "SA", "PM", "SA", "SA", "PM", "BA", "SA")
rating = c(75, 90, 95, 85, 95, 88, 74, 81, 55, 65, 68)
cost = c(5000, 8000, 9500, 4700, 9200, 5500, 5300, 7300, 3300, 4100, 4400)
df = data.frame(name, position, rating, cost)
# create restrictions
num_ba = 1
num_pm = 1
num_sa = 2
max_cost = 35000
# create vectors to constrain by position
df$BA = ifelse(df$position == "BA", 1, 0)
df$PM = ifelse(df$position == "PM", 1, 0)
df$SA = ifelse(df$position == "SA", 1, 0)
# vector to optimize against
objective = df$rating
# constraint directions
const_dir <- c("=", "=", "=", "<=")
# matrix
const_mat = matrix(c(df$BA, df$PM, df$SA, df$cost), 4, byrow=TRUE)
const_rhs = c(num_ba, num_pm, num_sa, max_cost)
#solve
x = lp("max", objective, const_mat, const_dir, const_rhs, all.bin=TRUE, all.int=TRUE)
print(df[which(x$solution==1), ])
答案 0 :(得分:1)
如果我的问题是正确的,那可能会有效:
library(lpSolve)
# create data.frame
name = c("Steve", "Jeremy", "Matt", "Aaron", "Stephanie", "Molly", "Jake", "Tony", "Jay", "Katy", "Alison")
position = c("BA", "PM", "SA", "BA", "SA", "PM", "SA", "SA", "PM", "BA", "SA")
rating = c(75, 90, 95, 85, 95, 88, 74, 81, 55, 65, 68)
cost = c(5000, 8000, 9500, 4700, 9200, 5500, 5300, 7300, 3300, 4100, 4400)
df = data.frame(name, position, rating, cost)
# create restrictions
num_pm = 1
min_num_ba = 1
min_num_sa = 2
tot_saba = 4
max_cost = 35000
# create vectors to constrain by position
df$PM = ifelse(df$position == "PM", 1, 0)
df$minBA = ifelse(df$position == "BA", 1, 0)
df$minSA = ifelse(df$position == "SA", 1, 0)
df$SABA = ifelse(df$position %in% c("SA","BA"), 1, 0)
# vector to optimize against
objective = df$rating
# constraint directions
const_dir <- c("==", ">=", "<=", "==", "<=")
# matrix
const_mat = matrix(c(df$PM, df$minBA, df$minSA, df$SABA, df$cost), 5, byrow=TRUE)
const_rhs = c(num_pm, min_num_ba,min_num_sa, tot_saba, max_cost)
#solve
x = lp("max", objective, const_mat, const_dir, const_rhs, all.bin=TRUE, all.int=TRUE)
print(df[which(x$solution==1), ])
我正在做的是修改一些约束并添加一个新约束:BA的数量必须是> = 1. SA的数量&gt; = 2,和 BA和SA的总和必须为4,因此您总是选择5个人。
然而,这提供了与OP所写的不同的解决方案:
name position rating cost PM minBA minSA SABA
1 Steve BA 75 5000 0 1 0 1
3 Matt SA 95 9500 0 0 1 1
4 Aaron BA 85 4700 0 1 0 1
5 Stephanie SA 95 9200 0 0 1 1
6 Molly PM 88 5500 1 0 0 0
然而,总结此解决方案的等级给出438,而运算结果为437,所以这应该是正确的。
HTH。