从R中的反伽马分布中采样

时间:2013-08-23 05:27:32

标签: r random gamma-distribution

为了从R中的反伽马分布进行采样,以下是正确的方法:

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

a = 4
b = 9

x = 1/rgamma(1,a,b)

2 个答案:

答案 0 :(得分:6)

虽然@Dason和@Stephane已经评论过你的方法是有效的,但R中有几个包可以做到这一点(找到了r inverse gamma的Google搜索:

另见gamma distribution的维基百科页面和两个发行版的概率密度函数的inverse gamma distribution

enter image description here

用于伽马分布:

enter image description here

用于反伽马。

答案 1 :(得分:-1)

以下代码是比较来自各种R包@ user2005253和@Stephane的反伽马模拟的示例。

@Paul Hiemstra我不确定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