[R] sampling from a mixture distribution

Liaw, Andy andy_liaw at merck.com
Wed Mar 23 15:24:00 CET 2005


Here's one possible way:

rmix2 <- function(n, p1, rF1, rF2, argF1=NULL, argF2=NULL) {
    ## n is the number of deviates to simulate
    ## p1 is the probability of a point coming from the 1st component
    ## rF1, rF2 are functions for generating random deviates
    ##     from the two components
    ## argF1, argF2 are lists of arguments to rF1 and rF2
    n1 <- rbinom(1, n, p1)
    n2 <- n - n1
    x1 <- do.call("rF1", c(list(n1), argF1))
    x2 <- do.call("rF2", c(list(n2), argF2))
    c(x1, x2)
}

To test:

   x <- rmix2(1000, 0.3, rnorm, rnorm, list(mean=5))
   hist(x)

HTH,
Andy

> From: Vumani Dlamini
> 
> 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 at 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
> 
> 
>




More information about the R-help mailing list