Last active
February 13, 2018 17:39
-
-
Save JonasMoss/c1eb6083ad79be3dbea8a6df02e21345 to your computer and use it in GitHub Desktop.
Sampling from a Gaussian kernel density estimate 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
## Make a function rkde that samples from a kernel density | |
#' Sample from a kernel density. | |
#' | |
#' @param n Number of observations to sample. | |
#' @param x The data from which the estimate is to be computed. | |
#' @param bw Desired bandwidth. | |
#' @return A numeric vector with n sampled data points from the kernel | |
#' density estimator. | |
rkde = function(n, x, bw) rnorm(n, mean = sample(x, n, replace = TRUE), sd = bw) | |
## Take a data set and find a suitable bandwidth with density. | |
data = airquality$Wind | |
bw = density(data)$bw | |
## Check that it works. | |
set.seed(313) | |
n = 1000000 | |
samples = rkde(n, data, bw) | |
hist(samples, breaks = 1000, freq = FALSE) | |
lines(density(data), lwd = 2, col = "red") |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment