Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Optimization packages for R

Does anyone know of any optimization packages out there for R (similar to NUOPT for S+)?

like image 418
wcm Avatar asked Dec 11 '08 14:12

wcm


4 Answers

Another package is ompr. An advantage of this package is there are many solvers that can be used and binary, continuous, integer all variables can easily be added. A simple example:

library(tidyverse)
library(ompr)
library(ompr.roi)


model <-  MIPModel() %>%
  add_variable(x1, type = "integer") %>%
  add_variable(x2, type = "integer") %>%
  set_bounds(x1, lb = 0) %>%
  set_bounds(x2, lb = 0) %>%
  set_objective(x1 - x2, "max") %>%
  add_constraint(x1 + 2*x2 <= 150) %>%
  add_constraint(x1 >= 30) %>%
  add_constraint(x2 >= 40)

Solving with glpk:

library(ROI.plugin.glpk)
result <- solve_model(model, with_ROI(solver = "glpk", verbose = TRUE))

get_solution(result, x1)
get_solution(result, x2)

It can also be solved with other solvers like symphony where the gap_limit can be set in case the problem is complex and will take many iterations to converge:

library(ROI.plugin.symphony)
result <- solve_model(model, with_ROI(solver = "symphony",
                                      verbosity=-1, gap_limit=1.5))
like image 193
Shibaprasadb Avatar answered Nov 16 '22 01:11

Shibaprasadb


R has many, many packages for optimization; check the CRAN Task view on Optimization: http://cran.r-project.org/web/views/Optimization.html. Of course, for nonlinear programs, there is optim(), which is standard and includes Broyden-Fletcher-Goldfarb-Shanno's algorithm, and Nelder-Mead. It's a good first start.

like image 36
gappy Avatar answered Nov 16 '22 01:11

gappy


Try lpSolve with R.

A simple example:

# Maximize 
#   x1 + 9 x2 +   x3 
# Subject to: 
#   x1 + 2 x2 + 3 x3 <= 9
# 3 x1 + 2 x2 + 2 x3 <= 15
f.obj <- c(1, 9, 3)
f.con <- matrix(c(1, 2, 3, 3, 2, 2), nrow = 2, byrow = TRUE)
f.dir <- c("<=", "<=")
f.rhs <- c(9, 15)

lp("max", f.obj, f.con, f.dir, f.rhs)
lp("max", f.obj, f.con, f.dir, f.rhs)$solution
like image 27
dwstu Avatar answered Nov 16 '22 01:11

dwstu


Linprog, mentioned by Galwegian, focuses on linear programming via the simplex algorithm. In addition you may be interested in fPortfolio if you are doing portfolio optimization.

like image 31
JD Long Avatar answered Nov 16 '22 01:11

JD Long