[R] Optimization inconsistencies

Petr Savicky savicky at cs.cas.cz
Fri May 18 11:42:43 CEST 2012


On Thu, May 17, 2012 at 06:14:37PM -0400, Nathan Stephens wrote:
> I have a very simple maximization problem where I'm solving for the vector
> x:
> 
> objective function:
> w'x = value to maximize
> 
> box constraints (for all elements of w):
> low < x < high
> 
> equality constraint:
> sum(x) = 1

Hi.

As Peter Dalgaard suggested, lpSolve may be used. If "low" may contain
negative values, then it is important to note that lpSolve assumes
all variables nonnegative. So, a transformation is needed, for example
x = low + y and solve for y. The following is one approach.

  library(lpSolve)
 
  n <- 8
  w <- 1:n
  low <- rep(-1, times=n)
  high <- rep(1, times=n)
 
  crit <- w
  mat <- rbind(diag(n), 1)
  rhs <- c(high - low, 1 - sum(low))
  dir <- c(rep("<=", times=n), "==")
 
  out <- lp("max", objective.in=crit, const.mat=mat, const.dir=dir, const.rhs=rhs)
  x <- low + out$solution

  round(x, digits=15)

  [1] -1 -1 -1  0  1  1  1  1

Hope this helps.

Petr Savicky.



More information about the R-help mailing list