[R] Estimating a Normal Mixture Distribution
andreas.danis at univie.ac.at
Fri Apr 20 21:57:39 CEST 2007
I am using R 2.4.1 on a MacOS X ("Tiger") operating system. In the
last few day I was trying to estimate the parameters of a mixture of
two normal distributions using Maximum Likelihood.
The code is from Modern Applied Statistics with S (4th edition),
chapter 16 ("Optimization"), the dataset is available under MASS in
R. Unfortunately, when I tried out the code from the book it didn´t
work out, although I tried to copy the code as accurately as possible:
# loading dataset.
# defining start values for the five parameters.
# defining the objective function (=log-likelihood function).
e<-p*dnorm((x-p)/p)/p + (1-p)*dnorm((x-p)/p)/p
if (any(e<=0)) Inf
# define two functions to calculate the first derivatives of the
lmix2a<-deriv(~ -log(p*dnorm((x-u1)/s1)/s1 + (1-p)*dnorm((x-u2)/s2)/
s2), c("p","u1","s1","u2","s2"), function(x,p,u1,s1,u2,s2) NULL)
# finally, the optimization using the Broyden-Fletcher-Goldfarb-
The output is given as:
p u1 s1
0.361204 50.000000 5.000000 80.000000 5.000000
Unfortunately, these are exactly the same parameter values which I
have specified as starting values under "p0".
Thank you very much for your help, best regards,
More information about the R-help