# Optimization using the optim function in R with a two parameter exponential distribution

I'm having trouble trying to optimize a two-parameter exponential distribution, by finding the maximum likelihood function and then using the function optim() in R log.lik.exp <- function(x, parametros){
n<-length(x)
y <- -1 *(n*log(parametros)-parametros*(sum(x)-n*parametros))
}
lambda<-2
gamma<-1
mydata <- rand.exp(100, gamma, 1/lambda)
optim(par=c(1,1),fn=log.lik.exp,x=mydata)$par  I'm also trying to use the function persp() to build a 3d plot to get a better look at the maximum values but I keep getting errors. Thank you in advance, G. • It seems this question is mostly about the optim function, and thus might be off topic. But to answer your question, you should check that$\min (x) > \gamma$. If it is not, then you should return$-\infty$. Also, your function technically returns the negative log likelihood. I think it is possibly better to use return the log-likelihood and use the "fnscale" option in optim to perform maximization. Dec 1, 2018 at 21:00 • Is your$f(t)$probability density function (pdf)? I did not get the integral = 1. Dec 1, 2018 at 21:57 • If$t \leq \gamma$, then the exponential term is positive for all$t \neq \gamma$, and you can see that you'll maximize the likelihood function by making$\gamma$as large as possible. Dec 1, 2018 at 22:07 ## 1 Answer As has been pointed out already, the issue is that you are not taking the bounds into consideration. You can fix this by adding an if-statement to your log likelihood function. log.lik.exp <- function(x, parametros){ n<-length(x) if(min(x) < parametros){ return(-Inf) } y <- n*log(parametros) - parametros*sum(x-parametros) } lambda <- 2 gamma <- 1 mydata <- rand.exp(100, gamma, 1/lambda) optim(par=c(1,1), fn=log.lik.exp, x=mydata, control=list(fnscale=-1))$par


I have also added an argument to optim() so that you are maximizing the log-likelihood rather than minimizing the negative log-likelihood. These are of course equivalent, but intuitively I prefer the first.

While we're at it, technically you could get an error if optim proposes a negative value for $$\lambda$$. This can be fixed in many ways. The simplest of which is to optimize over $$\lambda_\star = log(\lambda)$$ which can take any real value. Then just back transform, i.e. $$\lambda = e^{\lambda_\star}$$ at the end.

• I know this comment box says to avoid comments like 'thanks' but I really wanna thank you for your help, I was stuck in this for days and now I can continue! Dec 2, 2018 at 20:35