从R中的trucnated伽马分布中有效采样

时间:2014-04-18 14:44:20

标签: r distribution gamma-distribution

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

我需要从给定形状和比例参数以及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. 
 }

效率不高。

任何更有效的解决方案都将得到推广。

1 个答案:

答案 0 :(得分:2)

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

code上使用page 4

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 <- rtrunc(10000, "gamma", lb, ub, shape=shape, scale=scale)应该完成这项工作。