Generate stochastic random deviations from the density object with R

I have a dd density object created as follows:

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

Ultimately, I would like to get random deviations from this distribution, similar to how rnorm deviates from the normal distribution.

The way I am trying to hack this is to get the CDF of my kernel and then get it to tell me about it if I give it a cumulative probability (reverse CDF). Thus, I can turn the vector of uniform random variations into draws from density.

It seems that what I'm trying to do should be something basic that others did in front of me. Is there a simple way or simple function for this? I hate reinventing the wheel.

FWIW I found this R help article , but I can’t understand what they are doing, and the end result does not seem to give what I follow. But this may be a step along a path that I simply do not understand.

I just looked at the Johnson distribution from the suppdists package , but Johnson will not give me a good bimodal hump, which is my data.

+6
r probability stochastic
source share
2 answers

Alternative approach:

 sample(x, n, replace = TRUE) 
+9
source share

This is just a mixture of normals. So why not something like:

 rmnorm <- function(n,mean, sd,prob) { nmix <- length(mean) if (length(sd)!=nmix) stop("lengths should be the same.") y <- sample(1:nmix,n,prob=prob, replace=TRUE) mean.mix <- mean[y] sd.mix <- sd[y] rnorm(n,mean.mix,sd.mix) } plot(density(rmnorm(10000,mean=c(0,3), sd=c(1,2), prob=c(.5,.5)))) 

This should be good if all you need is samples from this mix distribution.

+2
source share

All Articles