I have a probability density function in R and I want to draw a single sample from it. How do I do that?
My current solution (and the one Google keeps giving me) is to evaluate the function for a dense set of values (x
) giving the associated probabilities (px
) and then draw a sample using sample(x, size=1, prob=px)
. Since I draw thousands of samples this way, simulating the distribution is really computationally heavy and is discrete even though it should be continuous.
Specifically, I'm writing my own Gibbs sampler to infer which means and standard deviations could have caused a vector of observations (bayesian inference). I sample from the distribution made up of likelihood * prior. Here's a minimal example of the loop-in-loop version I'm currently doing:
# values to assign posterior probabilities to. here 1000 values are used to simulate continuity.
mu.x = seq(from=0.001, to=20, length.out=1000)
# the likelihood distribution which will be called for varying mu and a fixed sigma and fixed D.
likelihoodMu = function(mu, sigma, D) mu.likelihood = ((2 * pi * sigma^2) ^ (-length(D) / 2)) * exp(-1 / (2 * sigma^2) * sum((D - mu)^2))
# will collect samples
mySamples = rep(NA, length(mu.x))
# Draw 5000 samples
for(i in 1:5000) {
# Loop over mu.x and get likelihood for each value
mu.likelihoodDistribution = sapply(mu.x, likelihoodMu, sigma=2, D=c(1,2,3))
# Draw a sample from the likelihood distribution calculated above
mySample = sample(mu.x, size=1, prob=mu.likelihoodDistribution)
}
I'm looking for a way to sample directly from the likelihood function in R instead of going through the discrete and computationally heavy seq-sapply-sample simulation. In the example above, something like sample('mu', FUN=likelihoodMu, sigma=2, D=c(1,2,3), size=1) would be nice. It should preferably be general, as I'm sampling from different kinds of distributions.