Solved – Sampling from the normal-gamma distribution in R

bayesiandistributionsgamma distributionnormal distributionr

Does anyone know of a way to sample from the normal-gamma bivariate distribution or the normal-inverse-gamma bivariate distribution in R?

I could create the distribution myself as a function, but then I would not know what to do to sample from it.

Best Answer

Sampling from normal-gamma distribution is easy, and in fact the algorithm is described on Wikipedia:

Generation of random variates is straightforward:

  • Sample $\tau$ from a gamma distribution with parameters $\alpha$ and $\beta$
  • Sample $x$ from a normal distribution with mean $\mu$ and variance $1/(\lambda \tau)$

What leads to the following function:

rnormgamma <- function(n, mu, lambda, alpha, beta) {
  if (length(n) > 1) 
    n <- length(n)
  tau <- rgamma(n, alpha, beta)
  x <- rnorm(n, mu, sqrt(1/(lambda*tau)))
  data.frame(tau = tau, x = x)
}
Related Question