问题
How can we solve a linear program using R? I want to solve the following example:
min -a -2b +4c
Constraints
a + b + s1 = 5
a + 3c -s2 = 10
2b - 3c = 20
a >= 0, b >= 0, c >= 0, s1 >= 0, s2 >= 0
The equations might not make total sense. I just need to know the syntax of writing these equations in R. I might write something like this for the above equations
require(lpSolve)
R.obj <- c(-1,-2,4)
R.con <- matrix(c(1,1,1,1,3,-1,2,-3),nrow=3,byrow=TRUE)
R.dir <- c("=","=","=")
R.rhs <- c(5,10,20)
lp("min",R.obj,R.con,R.dir,R.rhs)
Would this be correct? In the documentation, the matrix is always M*M
, what if the matrix is M*N
where N != M
?
回答1:
Your constraint matrix has 3 rows and 5 columns, but you've only provided the 8 non-zero values when building your constraint matrix. Further, you have 5 variables, so R.obj
needs 5 values:
require(lpSolve)
R.obj <- c(-1, -2, 4, 0, 0)
R.con <- matrix(c(1, 1, 0, 1, 0, 2, 0, 3, -3, 1, 0, 0, 0, -1, 0), nrow=3)
R.dir <- c("=", "=", "=")
R.rhs <- c(5, 10, 20)
lp("min", R.obj, R.con, R.dir, R.rhs)
# Error: no feasible solution found
A bit of math shows that this LP is indeed infeasible. This LP is equivalent to -a - b >= -5
, a + 3c >= 10
, b = 10 + 1.5c
. You can substitute the last equation into the first to yield -a - 1.5c >= 5
and a + 3c >= 10
, and adding yields c >= 10
. By your third equation, b >= 25
, which means the first equation can never hold due to the non-negativity of a
and s1
.
来源:https://stackoverflow.com/questions/22310767/linear-programs-using-r