Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Generate stochastic random deviates from a density object with R

I have a density object dd created like this:

x1 <- rnorm(1000) 
x2 <- rnorm(1000, 3, 2) 
x <- rbind(x1, x2)
dd <- density(x) 
plot(dd)

Which produces this very non-Gaussian distribution:

alt text http://www.cerebralmastication.com/wp-content/uploads/2009/09/nongaus.png

I would ultimately like to get random deviates from this distribution similar to how rnorm gets deviates from a normal distribution.

The way I am trying to crack this is to get the CDF of my kernel and then get it to tell me the variate if I pass it a cumulative probability (inverse CDF). That way I can turn a vector of uniform random variates into draws from the density.

It seems like what I am trying to do should be something basic that others have done before me. Is there a simple way or a simple function to do this? I hate reinventing the wheel.

FWIW I found this R Help article but I can't grok what they are doing and the final output does not seem to produce what I am after. But it could be a step along the way that I just don't understand.

I've considered just going with a Johnson distribution from the suppdists package but Johnson won't give me the nice bimodal hump which my data has.

like image 772
JD Long Avatar asked Sep 14 '09 15:09

JD Long


1 Answers

Alternative approach:

sample(x, n, replace = TRUE)
like image 64
hadley Avatar answered Sep 29 '22 16:09

hadley