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

Address: Kapucijnenvoer 35, Leuven, Belgium

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


> 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
> PLEASE do read the posting guide!
> http://www.R-project.org/posting-guide.html
>



R-help@stat.math.ethz.ch mailing list
https://stat.ethz.ch/mailman/listinfo/r-help PLEASE do read the posting guide! http://www.R-project.org/posting-guide.html 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