Is_PhD
Is_PhD

Reputation: 21

Fitting a mixture of gamma and normal distribution to data in R

I would like to fit a mixture of gamma and normal distribution to my data in R.

The data:

dput(A)
0.0838, 0.081, 0.0816, 0.0838, 0.0824, 0.0871, 0.0899, 0.0938, 0.099, 0.1018, 0.0998, 0.1, 0.0955, 0.0972

Based on the data I believe (by looking at the histogram) a mixture of gamma and normal distribution is the best candidate.

I used the following codes to fit the mixture distribution using fitdist function from fitdistrplus package:

# Define the quantile
qgm_normal <- function(p, 
                   w_gm=0.5,
                   par_shape=2,
                   par_rate=1,
                   mean=0,
                   sd=1) {
  w_normal=1-w_gm
  qgm=qgamma(p,shape=shape, rate=rate)
  qnormal=qnorm(p,mean =mean,sd = sd)
  return(w_gm*qgm+w_normal*qnormal)
}

# Define the distribution function
pgm_normal <- function(q, 
                   w_gm=0.5,
                   par_shape=2,
                   par_rate=1,
                   mean=0,
                   sd=1) {
  w_normal=1-w_gm
  pgm=pgamma(q,shape=shape, rate=rate)
  pnormal=pnorm(q,mean =mean,sd = sd)
  return(w_gm*pgm+w_norm*pnormal)
}

# Define the density
dgm_normal <-function(x,
                  w_gm=0.5,
                  par_shape=2,
                  par_rate=1,
                  mean=0,
                  sd=1) {
  w_normal=1-w_gm
  dgm=dgamma(x,shape=par_shape, rate=par_rate)
  dnormal=dnorm(x,mean =mean,sd = sd)
  return(w_gm*dgm+w_normal*dnormal)
}

fit_A <- fitdist(A, "gm_normal",start=list(w_gm=0.5, par_shape=2,par_rate=1, mean=0, sd=1))

I've read the question posted here R - fitting a mixture distribution with fitdistrplus but I've got the following error:

Error in fitdist(A, "gm_normal", start = list(w_gm = 0.5, par_shape = 100,  : the function mle failed to estimate the parameters, 
            with the error code 1

I could probably didn't fully understand the solution posted there. If someone could provide some help would be very grateful. Thanks in advance!

Upvotes: 2

Views: 1560

Answers (1)

Just saying
Just saying

Reputation: 11

For anyone wanting to do something similar, this code example works if you just replace par_shape and par_rate with shape and rate, respectively.

The issue was that the rate and shape parameters in the function calls are not defined since he denotes them as par_rate and par_shape.

Also add lower=c(0,0,0,0,0), upper=c(1,1000,1000,1000,1000) to the fitdist call to make sure the mixing parameter stays in [0,1]. Best of luck.

Upvotes: 1

Related Questions