Created
June 8, 2016 21:47
-
-
Save cbare/1437ce16d4300724e9e65e48b6b5d8a2 to your computer and use it in GitHub Desktop.
Sample from an estimated probability density in R
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
## 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") |
Author
cbare
commented
Jun 8, 2016
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment