How to replicate excel solver in R

前端 未结 1 1532
栀梦
栀梦 2020-12-23 12:41

I used excel solver to solve an optimization problem, and I am trying to replicate it in R.

I found many packages like optim, ROI etc., but it seems all of them only

相关标签:
1条回答
  • 2020-12-23 13:16

    You need to construct a vector for the objective function and a constraint matrix, finally solving with one of the R LP solvers:

    library(lpSolve)
    costs <- matrix(c(9, 10, 11, 4, 5, 10, 1, 3, 5, 7, 5, 4), nrow=3)
    nr <- nrow(costs)
    nc <- ncol(costs)
    columns <- t(sapply(1:nc, function(x) rep(c(0, 1, 0), c(nr*(x-1), nr, nr*(nc-x)))))
    rows <- t(sapply(1:nr, function(x) rep(rep(c(0, 1, 0), c(x-1, 1, nr-x)), nc)))
    mod <- lp("max", as.vector(costs), rbind(columns, rows), "<=", rep(1, nr+nc), binary.vec=rep(TRUE, nr*nc))
    

    Now you can grab the solution and the objective function:

    mod$objval
    # [1] 27
    matrix(mod$solution, nrow=nr)
    #      [,1] [,2] [,3] [,4]
    # [1,]    0    0    0    1
    # [2,]    1    0    0    0
    # [3,]    0    1    0    0
    

    Note that functions like optim are not well suited for this problem both because they don't consider matrices of constraints and also because they cannot limit to binary variable values.

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