I am looking to minimize a function using optim as follows:

yield <- function(data, par) {
  with(data, par[1] + (par[2] + par[3]/par[4])*(1-exp(-par[4]*maturity))/(par[4]*maturity) - (par[3]*exp(-par[4]*maturity)/par[4]))
min.RSS <- function(data, par) {
  sum((data$price - 100*exp(-data$maturity*yield(data, par)))^2)
result <- optim(par = theta, min.RSS, data = data))

The parameters par[1] and par[4] must be non-negative, while the other two are unconstrained. Is it possible to include these constraints in the optim function?



2 Answers 2


I would recommend re-parametrizing the problem so that it is unconstrained. Say by mapping the non-negative parameter with a log transform.

  • $\begingroup$ I think your idea is feasible, but can you give an example or link? So that I can find a general solution of different object functions $\endgroup$
    – Travis
    Commented Dec 15, 2019 at 11:09

You can set the constraints for the unconstrained parameters to $\pm \infty$ (and the ceiling for the non-negative parameters to $+\infty$).

optim(par=theta, fn=min.RSS, lower=c(0, -Inf, -Inf, 0), upper=rep(Inf, 4),

Technically the upper argument is unnecessary in this case, as its default value is Inf. However I like to be explicit when specifying bounds.


Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.