[R] sampling from a mixture distribution

Rolf Turner rolf at math.unb.ca
Wed Mar 23 16:03:01 CET 2005


> 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 at math.unb.ca




More information about the R-help mailing list