Search code examples
rlinear-programminglpsolve

R: In lpSolveAPI, how do I change the objective function from minimization to maximization?


library(lpSolveAPI)
my.lp <- make.lp(nrow = 3, ncol = 2)
set.column(my.lp, 1, c(1, 1, 2))
set.column(my.lp, 2, c(3, 1, 0))
set.objfn(my.lp, c(1, 0))
set.constr.type(my.lp, rep("<=", 3))
set.rhs(my.lp, c(4, 2, 3))
set.bounds(my.lp, lower = c(-Inf, -Inf), upper = c(Inf, Inf))
> my.lp
Model name: 
            C1    C2       
Minimize     1     0       
R1           1     3  <=  4
R2           1     1  <=  2
R3           2     0  <=  3
Kind       Std   Std       
Type      Real  Real       
Upper      Inf   Inf       
Lower     -Inf  -Inf 

In my.lp, the objective function is set to minimization. How can I change this to maximization? It's not clear to me by looking at the help page of set.objfn.


Solution

  • Set the sense (minimize/maximize) with lp.control.

    lp.control(my.lp, sense="max")
    
    my.lp
    #Model name: 
    #            C1    C2       
    #Maximize     1     0       
    #R1           1     3  <=  4
    #R2           1     1  <=  2
    #R3           2     0  <=  3
    #Kind       Std   Std       
    #Type      Real  Real       
    #Upper      Inf   Inf       
    #Lower     -Inf  -Inf       
    
    solve(my.lp)    # returns 0, success
    #[1] 0
    
    get.variables(my.lp)
    #[1] 1.5 0.0
    
    get.objective(my.lp)
    #[1] 1.5