Sampling from an inverse gamma distribution in R
Asked Answered
D

2

14

In order to sample from an inverse gamma distribution in R, is the following the correct way to do it:

#I want to sample an inverse-gamma(a,b)

a = 4
b = 9

x = 1/rgamma(1,a,b)
Ditter answered 23/8, 2013 at 5:27 Comment(1)
Yes it is correct.Higginbotham
C
7

Although @Dason and @Stephane already commented that your approach is valid, there are several packages in R that do this (found googling for r inverse gamma:

See also the wikipedia page for the gamma distribution and the inverse gamma distribution for the probability density function of both distributions:

enter image description here

for the gamma distribution versus:

enter image description here

for the inverse gamma.

Cashbook answered 23/8, 2013 at 5:31 Comment(2)
Although they didn't quite get the parameters right I don't quite see why you say "no" since their method is one way of generating an inverse gamma...Inexertion
Edited my answer to be less strict. @Inexertion after doing a bit of research it seemed that the two distributions are quite distinct, but I stand corrected.Cashbook
B
0

Code below is an example to compare simulations from the inverse gamma from various R packages @user2005253 and @Stephane.

@Paul Hiemstra I am not sure about the ringvamma{MCMCpack}

# double check implementations from various packages
library(ggplot2)
alpha = 1
rate = 0.5

# stats library ----------------------------------
library(stats) 
x.base<- 1/rgamma(10000, shape = alpha, rate = rate)
x11()
p.try0<- ggplot(data.frame(x = x.base), aes(x=x)) + geom_density() +
ggtitle(paste("Stats package: shape", alpha, "rate ", rate)) + xlim(c(0, 3))
p.try0

# invgamma library -------------------------------
library(invgamma)
sims.1<- rinvgamma(10000, shape = alpha, rate = rate)
p.try1<- ggplot(data.frame(x = sims.1), aes(x=x)) + geom_density() +
  ggtitle(paste("Package (invgamma) shape", alpha, " rate ", rate, sep = ""))+
  xlim(c(0, 3))
x11()
p.try1

detach("package:invgamma", unload = TRUE) 

# MCMCpack library -------------------------------
library(MCMCpack) # no rate argument - this works only on shape and scale.
                  #That's ok since scale = 1/rate
sims.2<- rinvgamma(10000, shape = alpha, scale = 1/rate)

p.try2<- ggplot(data.frame(x = sims.2), aes(x=x)) + geom_density() + 
  ggtitle(paste("Package MCMCpack: shape", alpha, " scale", 1/rate, sep = "")) +   
  xlim(c(0, 3))

x11()
p.try2

# Implementation of rinvgamma incorrect for MCMC pack? Because this works with
sims.3<- rinvgamma(10000, shape = alpha, scale = rate)

p.try3<- ggplot(data.frame(x = sims.2), aes(x=x)) + geom_density() +
   ggtitle(paste("again MCMCpack: here scale = rate ???")) + xlim(c(0, 3))

x11()
p.try3
Biometry answered 24/10, 2016 at 1:30 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.