Re: [R] sampling from a mixture distribution

From: Dimitris Rizopoulos <>
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)

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

I hope it helps.


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

Address: Kapucijnenvoer 35, Leuven, Belgium

Tel: +32/16/336899
Fax: +32/16/337015

> 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
> ______________________________________________
> mailing list
> PLEASE do read the posting guide!
> mailing list PLEASE do read the posting guide! Received on Thu Mar 24 01:18:58 2005

This archive was generated by hypermail 2.1.8 : Fri 03 Mar 2006 - 03:30:55 EST