[英]efficient sampling from trucnated gamma distribution in R
在論壇中搜索后,我沒有找到類似的問題。 如果我錯過了,請告訴我。 我真的很感激。
我需要從給定形狀和比例參數以及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.
}
這效率不高。
任何更有效的解決方案都將得到推廣。
參見Saralees Nadarajah和Samuel Kotz 關於截斷分布的R程序 。
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)
應該完成這項工作。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.