Вопрос

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)
Это было полезно?

Решение

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.

Другие советы

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
Лицензировано под: CC-BY-SA с атрибуция
Не связан с StackOverflow
scroll top