Skip to content

Instantly share code, notes, and snippets.

@cbare
Created June 8, 2016 21:47
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save cbare/1437ce16d4300724e9e65e48b6b5d8a2 to your computer and use it in GitHub Desktop.
Save cbare/1437ce16d4300724e9e65e48b6b5d8a2 to your computer and use it in GitHub Desktop.
Sample from an estimated probability density in R
## Sample from an estimated probability density
sample.density <- function(dd, size, jitter=FALSE) {
x <- sample(dd$x, size=size, prob=dd$y, replace=TRUE)
if (dd$n < 2) jitter=FALSE
if (jitter) {
w <- mean(dd$x[2:length(dd$x)] - dd$x[1:(length(dd$x)-1)]) / 2.0
x <- x + runif(size,-w,w)
}
return(x)
}
## pretend this is measured data and we don't know the PDF
dat <- c(rnorm(40), rnorm(40,3,2), runif(20,0,2))
dd <- density(dat)
plot(dd)
for (i in 1:100) {
s1 <- sample.density(dd, size=1000, jitter=TRUE)
lines(density(s1), col="#33669980")
}
lines(dd, col="blue")
@cbare
Copy link
Author

cbare commented Jun 8, 2016

sample_density

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment