0

After searching in the forum, I did not find similar questions. If I missed it, please let me know. I would really appreciate.

I need to generate N (can be 10000 or more) sample points from gamma distribution wth given shape and scale parameters and lower/upper bound in R.

I know how to do it by "for loop" but, it is not efficient.

 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. 
 }

This is not efficient.

Any more efficient solutions would be apprecaited.

Jake Burkhead
  • 6,435
  • 2
  • 21
  • 32
user3440244
  • 371
  • 1
  • 3
  • 15
  • 1
    Use `rtrunc(...)` in the `truncdist` package. See [this answer](http://stackoverflow.com/questions/22685549/simulation-to-generate-random-numbers-from-a-truncated-logistic-distribution-in/22693701#22693701). – jlhoward Apr 18 '14 at 15:04

1 Answers1

2

See R Programs for Truncated Distributions by Saralees Nadarajah and Samuel Kotz.

Using their code on 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)
}

Now v <- rtrunc(10000, "gamma", lb, ub, shape=shape, scale=scale) should do the job.

user1197460
  • 108
  • 6
  • 1
    Why would you do this when there is a package available? – jlhoward Apr 18 '14 at 17:28
  • Good point, wasn't aware of its existence as I only searched on the [CRAN Probability Distributions Task View](http://cran.r-project.org/web/views/Distributions.html). [`truncdist`](http://cran.r-project.org/web/packages/truncdist/) is by the same authors, I guess, not surprisingly... – user1197460 Apr 25 '14 at 08:15