我有一个函数,可以通过最大化一些参数来分配预算。我有5种不同的输入,它们存储在st
中。但是我想给这些值施加约束。
我有5个频道,例如电视,YouTube,Facebook,显示和流媒体,但我只希望电视中的最高预算为1000欧元,预算为5000欧元。
BruteforcesmallNRW <- function(budget) {
proj <- function(x) budget * x / sum(x)
st <- proj(rep(1, 5))
f <- function(x) NrwGes(proj(x))
res <- optim(st, f, lower = 0 * st, method = "L-BFGS-B", upper = c(1000, Inf, Inf, Inf, Inf), control = list(fnscale = -1))
x <- res$value
y <- proj(res$par)
z <- c(x, y)
return(z)
}
该函数运行良好,但是忽略了我的约束。你能帮我吗?
这是我的自定义功能:
NrwGes <- function(Budget) {
BudgetA <- Budget[1]
BudgetB <- Budget[2]
BudgetC <- Budget[3]
BudgetD <- Budget[4]
BudgetE <- Budget[5]
MaxNRW <- c(data$MaxNRWTV[i], data$MaxNRWCatchup[i], data$MaxNRWYT[i], data$MaxNRWFB[i], data$MaxNRWDisplay[i])
Speed <- c(data$SpeedTV[i], data$SpeedCatchup[i], data$SpeedYT[i], data$SpeedFB[i], data$SpeedDisplay[i])
cpcrp <- c(data$CpGRPTV[i], data$cpGRPCatchup[i], data$cpGRPYT[i], data$cpGRPFB[i], data$cpGRPDisplay[i])
# MaxNRW <- c(data$MaxNRWTV[i], data$MaxNRWYT[i], data$MaxNRWFB[i], data$MaxNRWDisplay[i], data$MaxNRWCatchup[i])
# Speed <- c(data$SpeedTV[i], data$SpeedYT[i], data$SpeedFB[i], data$SpeedDisplay[i], data$SpeedCatchup[i])
# cpcrp <- c(data$CpGRPTV[i], data$cpGRPYT[i], data$cpGRPFB[i], data$cpGRPDisplay[i], data$cpGRPCatchup[i])
TV <- BudgetA*1000/cpcrp[1]
Catchup <- BudgetB*1000/cpcrp[2]
YT <- BudgetC*1000/cpcrp[3]
FB <- BudgetD*1000/cpcrp[4]
Display <- BudgetE*1000/cpcrp[5]
a <- TV^Speed[1]/(1+abs((TV)^Speed[1]-1)/(MaxNRW[1]*0.98))
b <- Catchup^Speed[2]/(1+abs((Catchup)^Speed[2]-1)/(MaxNRW[2]*0.98))
c <- YT^Speed[3]/(1+abs((YT)^Speed[3] -1)/(MaxNRW[3]*0.98))
d <- FB^Speed[4]/(1+abs((FB)^Speed[4]-1)/(MaxNRW[4]*0.98))
e <- Display^Speed[5]/(1+abs((Display)^Speed[5]-1)/(MaxNRW[5]*0.93))
obj <- a+(100-a)/100*b+((100-a)/100*(100-b)/100*c)+((100-a)/100*(100-b)/100*(100-c)/100*d)+((100-a)/100*(100-b)/100*(100-c)/100*(100-d)/100*e)
return(obj)
}