# R optim function - Setting constraints for individual parameters

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]))
}
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?

Thanks

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.