0

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

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

这效率不高。

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

4

1 回答 1

2

请参阅Saralees Nadarajah 和 Samuel Kotz 的用于截断分布的 R 程序。

第 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)应该做的工作。

于 2014-04-18T15:21:56.867 回答