n = 1000
mu1 = 99 # Mean IQ of geography professors
mu2 = 150 # Mean IQ of mathematics professors
sd1 = sd2 = 16
phi = 0.3
y = ifelse(runif(n) < phi, rnorm(n, mu1, sd1), rnorm(n, mu2, sd2))
# Good idea to have trace=TRUE:
fit = vglm(y ~ 1, mix2normal1(esd=TRUE), maxit=200)
coef(fit, matrix=TRUE) # the estimates
c(phi, mu1, sd1, mu2, sd2) # the truth
# Plot the results
xx = seq(min(y), max(y), len=200)
plot(xx, (1-phi)*dnorm(xx, mu2, sd2), type="l", xlab="IQ",
main="Red=estimate, blue=truth", col="blue")
phi.est = logit(coef(fit)[1], inverse=TRUE)
sd.est = exp(coef(fit)[3])
lines(xx, phi*dnorm(xx, mu1, sd1), col="blue")
lines(xx, phi.est * dnorm(xx, Coef(fit)[2], sd.est), col="red")
lines(xx, (1-phi.est) * dnorm(xx, Coef(fit)[4], sd.est), col="red")
abline(v=Coef(fit)[c(2,4)], lty=2, col="red")
abline(v=c(mu1, mu2), lty=2, col="blue")
Run the code above in your browser using DataLab