Search code examples
rlinear-programminglpsolve

Using lpSolve in R to Minimize Absolute Values in an Objective Function


I would like to set up a linear program (if it is possible, I'm not sure) to solve this problem in R:

I want to minimize the function:
abs(x1) + abs(x2) + abs(x3) + abs(x4)

Constraints:
x1 + x2 + x3 + x4 = 0
0.2x1 + 0.3x2 + 0.5x3 + 0.1x4 = 0.2

Constraints are usually written as inequalities so I assume I can have two equations of each, one with <= 0 and <= 0.2, and the other two with >= 0 and >= 0.2. The decision variables are continuous and can be positive or negative.

I can setup the matrix for the constraints to use lpSolve but I am most confused about how to implement the absolute value functions in the objective function. This site (http://lpsolve.sourceforge.net/5.1/absolute.htm) was a good read but I'm not sure how to translate that into the inputs for lpSolve in R. Any help or guidance would be much appreciated!


Solution

  • I will answer this on how to model the linear program with absolute values correctly for any LP solver to easily solve. The trick is to introduce two auxiliary variables for each variable that has the absolute value. For example:

    Introduce the variables z(1,p) and z(1,n) where the values in the parentheses are indices for the variable z. The 1 notes it corresponds to x1, and the p stands for positive and the n stands for negative. Add these constraints:

    z(1,p) - z(1,n) = x1

    z(1,p) >= 0

    z(1,n) >= 0

    See what this does, when x1 is positive, then z(1,p) = x1 and z(1,n) = 0. When x1 is negative, then -z(1,n) = x1 and z(1,p) = 0. Thus it is clear that abs(x1) = z(1,p) + z(1,n). So you just need to substitute that in your objective function and add those constraints (for each index 1,...,4).