[R] MLE with optim
Sundar Dorai-Raj
sundar.dorai-raj at pdf.com
Wed Jun 29 17:28:43 CEST 2005
Carsten Steinhoff wrote:
> Hello,
>
> I tried to fit a lognormal distribution by using optim. But sadly the output
> seems to be incorrect.
> Who can tell me where the "bug" is?
>
> test = rlnorm(100,5,3)
> logL = function(parm, x,...) -sum(log(dlnorm(x,parm,...)))
> start = list(meanlog=5, sdlog=3)
> optim(start,logL,x=test)$par
>
> Carsten.
>
You are only supplying the meanlog argument to dlnorm. Also you can set
log = TRUE in dlnorm to avoid the log computation after calling dlnorm.
set.seed(1)
x <- rlnorm(100, 5, 3)
logL <- function(par, x) -sum(dlnorm(x, par[1], par[2], TRUE))
start <- list(meanlog = 5, sdlog = 2)
optim(start, logL, x = x)
Why not just use MASS::fitdistr instead?
library(MASS)
fitdistr(x, dlnorm, start)
HTH,
--sundar
More information about the R-help
mailing list