# Re: [R] sampling from a mixture distribution

From: Dimitris Rizopoulos <dimitris.rizopoulos_at_med.kuleuven.ac.be>
Date: Thu 24 Mar 2005 - 01:14:44 EST

you have also to sample the mixture compoment membership; check this for a mixtrue of two normals:

rnorm.mixture <- function(n, prob=0.5, mu1=0, sigma1=1, mu2=0, sigma2=1){

u <- runif(n)
out <- numeric(n)
for(i in 1:n) out[i] <- if(u[i] < prob) rnorm(1, mu1, sigma1) else rnorm(1, mu2, sigma2)

out
}
########
hist(rnorm.mixture(1000, prob=0.6, mu1=-1, sigma1=0.5, mu2=2, sigma2=0.5))

I hope it helps.

Best,
Dimitris

Dimitris Rizopoulos
Ph.D. Student
Biostatistical Centre
School of Public Health
Catholic University of Leuven

```Tel: +32/16/336899
Fax: +32/16/337015
Web: http://www.med.kuleuven.ac.be/biostat/
http://www.student.kuleuven.ac.be/~m0390867/dimitris.htm

```
• Original Message ----- From: "Vumani Dlamini" <dvumani@hotmail.com> To: <r-help@stat.math.ethz.ch> Sent: Wednesday, March 23, 2005 2:53 PM Subject: [R] sampling from a mixture distribution

> Dear R users,
> I would like to sample from a mixture distribution
> p1*f(x1)+p2*f(x2). I usually sample variates from both distributions
> and weight them with their respective probabilities, but someone
> told me that was wrong. What is the correct way?
> Vumani
>
> ______________________________________________
> R-help@stat.math.ethz.ch mailing list
> https://stat.ethz.ch/mailman/listinfo/r-help