【问题标题】:efficient sampling from trucnated gamma distribution in R从 R 中截断的 gamma 分布中进行有效采样
【发布时间】:2014-04-18 14:44:20
【问题描述】:

在论坛搜索后,我没有找到类似的问题。如果我错过了,请告诉我。我真的很感激。

我需要使用给定的形状和比例参数以及 R 中的下限/上限从伽马分布中生成 N 个(可以是 10000 个或更多)样本点。

我知道如何通过“for循环”来做到这一点,但是效率不高。

 library(distr)
 get_sample_gamma(shape, scale, lb, ub)
 {
    v <- rgamma(n = 10000, shape, scale)
    # check the elements of v to be located [lb, ub]
    # if not in the range, count the number of points in the range as M
    # generate the remaining N - M points until all N points are got. 
 }

这不是有效的。

任何更有效的解决方案都会受到赞赏。

【问题讨论】:

  • truncdist 包中使用rtrunc(...)。见this answer

标签: r distribution gamma-distribution


【解决方案1】:

参见 Saralees Nadarajah 和 Samuel Kotz 的 R Programs for Truncated Distributions

page 4 上使用他们的code

qtrunc <- function(p, spec, a = -Inf, b = Inf, ...) {
    tt <- p
    G <- get(paste("p", spec, sep = ""), mode = "function")
    Gin <- get(paste("q", spec, sep = ""), mode = "function")
    tt <- Gin(G(a, ...) + p*(G(b, ...) - G(a, ...)), ...)
    return(tt)
}
rtrunc <- function(n, spec, a = -Inf, b = Inf, ...) {
    x <- u <- runif(n, min = 0, max = 1)
    x <- qtrunc(u, spec, a = a, b = b,...)
    return(x)
}

现在v &lt;- rtrunc(10000, "gamma", lb, ub, shape=shape, scale=scale) 应该可以完成这项工作。

【讨论】:

最近更新 更多