R CVXR linear programming

Last modified: 
Monday, 30. March 2020 - 2:01

Here is the example that works:

Original source not working: http://rtutorial.altervista.org/lp_solvers.html
Thanks to Mark Neal for debugging: https://stackoverflow.com/questions/60909930/r-cvxr-matrix-multiplicatio...

library(CVXR)
#create Variable objects that can be manipulated by the solver.
x<-Variable(3)
#coefficients for objective function
C <- matrix(c(2,4,3), nrow = 1)
#the Maximize function does not find a maximum for this function. It is creating an objective function object that the solver will be able to use.

objective<-Maximize(C %*% x)
#make a list of constraints. x[i] is the ith x variable
constraints<-list(3*x[1]+4*x[2]+2*x[3]<=60, 
                  2*x[1]+x[2]+2*x[3]<=40, 
                  x[1]+3*x[2]+2*x[3]<=80, 
                  x>=0)
#now we formulate the problem using the Problem function. this will create a "Problem" object for the solver
problem<-Problem(objective, constraints)
microbenchmark(
#now we can get the solution by calling solve. Now we can print out all the information we want.
ans<-solve(problem),
times=100
)
#show status
print(ans$status)
#show optimum value
print(ans$value)
#show values for variables
print(ans$getValue(x))