Optimization of budget allocation in R (formerly Excel Solver)

前端 未结 2 1754
Happy的楠姐
Happy的楠姐 2021-01-27 08:10

i translated a Problem I had in Excel into R. I want to allocate a fixed Budget in a form that \"Gesamt\" (which is returned by the function) is maximized.

NrwGe         


        
相关标签:
2条回答
  • 2021-01-27 08:28

    Try optim with the L-BFGS-U method (which allows for bounds) and a lower bound of 0. Then project the input components onto a vector which sums to 5000 passing that to NrwGes. fscale = -1 says to maximize rather than minimize. The final allocation will be proj(res$par) as shown at the bottom. No packages are used.

    proj <- function(x) 5000 * 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", control = list(fnscale = -1))
    

    giving:

    > res
    $`par`
    [1] 2107.8438  482.5702  468.9409  268.0808  142.4305
    
    $value
    [1] 86.64285
    
    $counts
    function gradient 
          14       14 
    
    $convergence
    [1] 0
    
    $message
    [1] "CONVERGENCE: REL_REDUCTION_OF_F <= FACTR*EPSMCH"
    
    > proj(res$par)  # final allocation
    [1] 3037.3561  695.3729  675.7334  386.2984  205.2391
    
    0 讨论(0)
  • 2021-01-27 08:39

    An option is nloptr package :

    library(nloptr)
    
    # we use NLOPT_LN_COBYLA algorithm because it doesn't need gradient functions
    opts <- list(algorithm="NLOPT_LN_COBYLA",
                 xtol_rel=1.0e-8,
                 maxeval=10000)
    # objective function (negative because nloptr always minimize)
    objFun <- function(x){ -NrwGes(x) }
    
    # sum of budget <= 5000 (in the form g(x) <= 0)
    g <- function(x){ sum(x) - 5000 }
    
    
    res <- nloptr(x0=rep.int(0,5), # initial solution (all zeros)
                  eval_f=objFun, 
                  lb=rep.int(0,5), # lowerbounds = 0
                  ub=rep.int(5000,5), # upperbounds = 5000
                  eval_g_ineq=g,
                  opts=opts)
    

    Result :

    > res
    Call:
    nloptr(x0 = rep.int(0, 5), eval_f = objFun, lb = rep.int(0, 5), 
        ub = rep.int(5000, 5), eval_g_ineq = g, opts = opts)
    
    
    Minimization using NLopt version 2.4.2 
    
    NLopt solver status: 4 ( NLOPT_XTOL_REACHED: Optimization stopped because xtol_rel 
    or xtol_abs (above) was reached. )
    
    Number of Iterations....: 261 
    Termination conditions:  xtol_rel: 1e-08    maxeval: 10000 
    Number of inequality constraints:  1 
    Number of equality constraints:    0 
    Optimal value of objective function:  -86.6428477187536 
    Optimal value of controls: 3037.382 695.3725 675.7232 386.2929 205.2291
    

    N.B. you can access to solution, objective of res using res$solution, res$objective etc.

    0 讨论(0)
提交回复
热议问题