Using lpsolve from R


R is a language and environment for statistical computing and graphics. It is a GNU project which is similar to the S language and environment which was developed at Bell Laboratories (formerly AT&T, now Lucent Technologies) by John Chambers and colleagues. R can be considered as a different implementation of S. There are some important differences, but much code written for S runs unaltered under R.

R provides a wide variety of statistical (linear and nonlinear modelling, classical statistical tests, time-series analysis, classification, clustering, ...) and graphical techniques, and is highly extensible. The S language is often the vehicle of choice for research in statistical methodology, and R provides an Open Source route to participation in that activity.

One of R's strengths is the ease with which well-designed publication-quality plots can be produced, including mathematical symbols and formulae where needed. Great care has been taken over the defaults for the minor design choices in graphics, but the user retains full control.

R is available as Free Software under the terms of the Free Software Foundation's GNU General Public License in source code form. It compiles and runs on a wide variety of UNIX platforms and similar systems (including FreeBSD and Linux), Windows and MacOS.

The R environment

R is an integrated suite of software facilities for data manipulation, calculation and graphical display. It includes

The term "environment" is intended to characterize it as a fully planned and coherent system, rather than an incremental accretion of very specific and inflexible tools, as is frequently the case with other data analysis software.

R, like S, is designed around a true computer language, and it allows users to add additional functionality by defining new functions. Much of the system is itself written in the R dialect of S, which makes it easy for users to follow the algorithmic choices made. For computationally-intensive tasks, C, C++ and Fortran code can be linked and called at run time. Advanced users can write C code to manipulate R objects directly.

Many users think of R as a statistics system. We prefer to think of it of an environment within which statistical techniques are implemented. R can be extended (easily) via packages. There are about eight packages supplied with the R distribution and many more are available through the CRAN family of Internet sites covering a very wide range of modern statistics.

We will not discuss the specifics of R here but instead refer the reader to the R website. Also see An Introduction to R

R and lpsolve

lpsolve is callable from R via an extension or module. As such, it looks like lpsolve is fully integrated with R. Matrices can directly be transferred between R and lpsolve in both directions. The complete interface is written in C so it has maximum performance.

There are currently two R packages based on lp_solve. Both packages are available from CRAN.

The lpSolve R package is the first implementation of an interface of lpsolve to R. It provides high-level functions for solving general linear/integer problems, assignment problems and transportation problems. The following link contains the version of the driver: lpSolve: Interface to Lp_solve v. 5.5 to solve linear/integer programs. It does not contain the lpsolve API. Only the higher level calls. Documentation for this interface can be found on: Interface to Lp_solve v. 5.5 to solve linear/integer programs
This driver is written and maintained by Sam Buttrey.

The lpSolveAPI R package is a second implementation of an interface of lpsolve to R. It provides an R API mirroring the lp_solve C API and hence provides a great deal more functionality but has a steeper learning curve. The R interface to lpsolve contains its own documentation. See An R interface to the lp_solve library for the driver.
This driver is written and maintained by Kjell Konis.

Installing the lpsolve driver in R

How to install the driver depends on the environment.


In the RGui menu, there is a menu item 'Packages'. From there a package can be installed from a CRAN mirror or from a local zip file.

R command line

Packages can also be installed from the R command line. This is a more general approach that will work under all environments.
Installing the package takes a single command:

The lpSolve R package:

  > install.packages("lpSolve")
and to install the lpSolveAPI package use the command:
  > install.packages("lpSolveAPI")

The > shown before each R command is the R prompt. Only the text after > must be entered.

Loading the lpsolve driver in R

Installing the package is not enough. It must also loaded in the R memory space before it can be used. This can be done with the following command:
  > library(lpSolveAPI)
  > library("lpSolveAPI", character.only=TRUE)

Getting Help

Documentation is provided for each function in the lpSolve package using R's built-in help system. For example, the command

  > ?add.constraint
will display the documentation for the add.constraint function.

Building and Solving Linear Programs Using the lpSolve R Package

This implementation provides the functions lp, lp.assign, lp.object, lp.transport and print.lp. These functions allow a linear program (and transport and assignment problems) to be defined and solved using a single command.

For more information enter:

  > ?lp
  > ?lp.assign
  > ?lp.object
  > ?lp.transport
  > ?print.lp

See also Interface to Lp_solve v. 5.5 to solve linear/integer programs

Building and Solving Linear Programs Using the lpSolveAPI R Package

This implementation provides an API for building and solving linear programs that mimics the lp_solve C API. This approach allows much greater flexibility but also has a few caveats. The most important is that the lpSolve linear program model objects created by make.lp and read.lp are not actually R objects but external pointers to lp_solve 'lprec' structures. R does not know how to deal with these structures. In particular, R cannot duplicate them. Thus one must never assign an existing lpSolve linear program model object in R code.

To load the library, enter:

  > library(lpSolveAPI)

Consider the following example. First we create an empty model x.

  > x <- make.lp(2, 2)
Then we assign x to y.
  > y <- x
Next we set some columns in x.
  > set.column(x, 1, c(1, 2))
  > set.column(x, 2, c(3, 4))

And finally, take a look at y.

  > y
  Model name:
              C1    C2
  Minimize     0     0
  R1           1     3  free  0
  R2           2     4  free  0
  Type      Real  Real
  upbo       Inf   Inf
  lowbo        0     0
The changes we made in x appear in y as well. Although x and y are two distinct objects in R, they both refer to the same lp_solve 'lprec' structure.

The safest way to use the lpSolve API is inside an R function - do not return the lpSolve linear program model object.

Learning by Example
  > lprec <- make.lp(0, 4)
  > set.objfn(lprec, c(1, 3, 6.24, 0.1))
  > add.constraint(lprec, c(0, 78.26, 0, 2.9), ">=", 92.3)
  > add.constraint(lprec, c(0.24, 0, 11.31, 0), "<=", 14.8)
  > add.constraint(lprec, c(12.68, 0, 0.08, 0.9), ">=", 4)
  > set.bounds(lprec, lower = c(28.6, 18), columns = c(1, 4))
  > set.bounds(lprec, upper = 48.98, columns = 4)
  > RowNames <- c("THISROW", "THATROW", "LASTROW")
  > ColNames <- c("COLONE", "COLTWO", "COLTHREE", "COLFOUR")
  > dimnames(lprec) <- list(RowNames, ColNames)
Lets take a look at what we have done so far.
  > lprec  # or equivalently print(lprec)
  Model name:
  Minimize         1         3      6.24       0.1
  THISROW          0     78.26         0       2.9  >=  92.3
  THATROW       0.24         0     11.31         0  <=  14.8
  LASTROW      12.68         0      0.08       0.9  >=     4
  Type          Real      Real      Real      Real
  upbo           Inf       Inf       Inf     48.98
  lowbo         28.6         0         0        18
Now lets solve the model.
  > solve(lprec)
  [1] 0

  > get.objective(lprec)
  [1] 31.78276

  > get.variables(lprec)
  [1] 28.60000  0.00000  0.00000 31.82759

  > get.constraints(lprec)
  [1]  92.3000   6.8640 391.2928

Note that there are some commands that return an answer. For the accessor functions (generally named get.*) the output should be clear. For other functions (e.g., solve), the interpretation of the returned value is described in the documentation. Since solve is generic in R, use the command

  > ?solve.lpExtPtr
to view the appropriate documentation. The assignment functions (generally named set.*) also have a return value - often a logical value indicating whether the command was successful - that is returned invisibly. Invisible values can be assigned but are not echoed to the console. For example,
  > status <- add.constraint(lprec, c(12.68, 0, 0.08, 0.9), ">=", 4)
  > status
  [1] TRUE
indicates that the operation was successful. Invisible values can also be used in flow control.
Cleaning up

To free up resources and memory, the R command rm() must be used.
For example:

  > rm(lprec)

See also Using lpsolve from MATLAB, Using lpsolve from O-Matrix, Using lpsolve from Sysquake, Using lpsolve from Octave, Using lpsolve from FreeMat, Using lpsolve from Euler, Using lpsolve from Python, Using lpsolve from Sage, Using lpsolve from PHP, Using lpsolve from Scilab Using lpsolve from Microsoft Solver Foundation