Skip to content

Instantly share code, notes, and snippets.

@JonasMoss
Last active February 13, 2018 17:39
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 JonasMoss/c1eb6083ad79be3dbea8a6df02e21345 to your computer and use it in GitHub Desktop.
Save JonasMoss/c1eb6083ad79be3dbea8a6df02e21345 to your computer and use it in GitHub Desktop.
Sampling from a Gaussian kernel density estimate in R.
## 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