JmO
JmO

Reputation: 572

Fit lognormal distribution with R &nls

Consider I have data like this:

df<-data.frame(x=c(1100,800,600,550,500,350),y=c(0.05,0.17,0.91,0.95,1,0.13))

how can I fit a curve through it based on a log normal shape/distribution

I can use a nls model but get an error always:

fit <-nls(y ~ a*dlnorm(x, mean, sd), data = df, 
    start = list(mean =0, sd = 10,a=1e4))

Thanks a lot!

Upvotes: 2

Views: 1647

Answers (1)

Julius Vainora
Julius Vainora

Reputation: 48241

I'm not sure why nls behaves like that, but you may directly use optim:

opt <- optim(c(1, 1, 1), function(p) sum((dlnorm(df$x, p[1], p[2]) * p[3] - df$y)^2))
opt$par
# [1]   6.3280753   0.2150322 299.3154123

plot(x = df$x, y = df$y, type = 'b', ylim = c(0, 1), xlim = c(0, 1100))
curve(opt$par[3] * dlnorm(x, opt$par[1], opt$par[2]), from = 0, to = 1100, add = TRUE, col = 'red')

enter image description here

Upvotes: 3

Related Questions