Re: [R] sampling from a mixture distribution

From: Rolf Turner <rolf_at_math.unb.ca>
Date: Thu 24 Mar 2005 - 02:03:01 EST

> I would like to sample from a mixture distribution p1*f(x1)+p2*f(x2).

        ***Surely*** you mean ``p1*f1(x)+p2*f2(x)'' !!!

> 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?

        If you want a sample of size n, first generate n1 by

                n1 <- rbinom(1,n,p1)

	Then generate a vector x1 equal to n1 observations from the
	f1(x) distribution and a vector x2 equal to n2 = n-n1
	observations from the f2(x) distribution.  Finally combine
	the two vectors of observations into a single vector:

		x <- c(x1,x2)

	You can then shuffle the order of x

		x <- sample(x,n)

	if you want to be obsessive about it.

				cheers,

					Rolf Turner
					rolf@math.unb.ca

______________________________________________
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 02:12:05 2005

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