# What is optimx in R

The optimx() is a general-purpose optimization function in R that can call several other R tools for optimization, such as optim, spg, ucminf, nlm, and nlminb. It also tries to unify the calling sequence to allow several tools to use the same front end.

To install optimx, you can use the install.packages function in R with the ‘optimx’ package as an argument.

``install.packages('optimx')``

To load the package before using it, you can use the library() function.

``library(optimx)``

### Example

``````library(optimx)

fun <- function(x) {
x1 <- x
x2 <- x

return((x1 - 2)^2 + (x2 + 3)^2)
}

# Set the optimization parameters
start_vals <- c(0, 0)

# Run the optimization
result <- optimx(start_vals, fun, method = method)

# View the optimization results
print(result)``````

Output

``````               p1         p2      value     fevals  gevals   niter   convcode    kkt1
Nelder-Mead 1.999823 -3.000005 3.144259e-08 65       NA       NA        0        TRUE

kkt2      xtime

In this example, we defined a simple quadratic function fun and used optimx() to find the minimum value of this function.

Then, we set the starting values for the optimization to (0,0) and chose the Nelder-Mead optimization method.

The optimization result is stored in the result object and can be viewed using the print() function.

The optimx also allows for many other options and methods, such as different stopping criteria, constraints, parallelization, etc.

## Using the optimx with different methods and comparing the results

Let’s optimize the Rosenbrock function.

``````library(optimx)

rosenbrock <- function(x) {
(1 - x)^2 + 100 * (x - x^2)^2
}

result <- optimx(c(-1.2, 1), rosenbrock,
)

print(result)``````

Output

``````               p1          p2      value       fevals     gevals   niter   convcode    kkt1
Nelder-Mead  1.0002601 1.0005060 8.825241e-08   195         NA       NA        0       FALSE
BFGS         0.9998044 0.9996084 3.827383e-08   118         38       NA        0       TRUE
nlminb       1.0000000 1.0000000 2.573782e-20   44          74       35        0       TRUE

kkt2     xtime