[R] Fitting distribution in range

saray sarai.shai at gmail.com
Fri Feb 25 15:59:09 CET 2011


Hello.

I am trying to fit my data sample x with different distributions such that
the integral from min(x) to max(x) of the fitted distribution will be one.
Therefore I have wrote my own log-likelihood functions and then I am using
mle {stats4}. So, for example: 

ll_gamma <- function(a,b) {
    integrand <- function(y){dgamma(y, shape=a, rate=b)}
    integ_res <- tryCatch({integrate(integrand,min_x,max_x)$value},
error=function(err){0});
    if (integ_res == 0) { return(NA) }
    C = 1 / integ_res
    res = -(sum(log(C*dgamma(x,shape=a,rate=b))))
    return(res)
}

m <- mean(x)
v <- var(x)
fit <- mle(minuslog=ll_gamma,start=list(a=m^2/v,b=m/v)) 

Now, for some reason I get very weird results. I have tested it by sampling
random numbers from gamma distribution, for example, and then try to fit it
with the algorithm I wrote.

Am I doing something wrong? do I need to first fit the sample with regular
gamma distribution and then calculate the normalisation factor C (I think
not. i.e. - I think that the normalisation factor should be included in the
log-likelihood function). Please note that I don't know what is the best fit
for my data. So I am trying to fit it with several distributions and choose
the best using AIC.

Any comments will be very appreciated. 
Please let me know if any of you have ever ran into a similar problem....

Thank you in advance,
Saray







-- 
View this message in context: http://r.789695.n4.nabble.com/Fitting-distribution-in-range-tp3324579p3324579.html
Sent from the R help mailing list archive at Nabble.com.



More information about the R-help mailing list