RE: [R] sampling from a mixture distribution

From: Liaw, Andy <andy_liaw_at_merck.com>
Date: Thu 24 Mar 2005 - 01:24:00 EST


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@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:44:14 2005

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