# How do I generate random integers within a specific range in R?

I want to generate 100 random integers from an exponential distribution in R, where each integer is between 10 and 50 (hence 10, 11, 12, ..., 49, 50). How can I do this in R?

• This appears more to be a question of "what to name a distribution with these parameters" than how to generate a subsection of an exponential distribution. – Carl Witthoft May 14 at 11:49

You know the quantiles to which $$10$$ and $$50$$ correspond, right? These are given by pexp(10, rate) and pexp(50, rate), respectively. With a rate of $$1$$, I get quantiles of $$0.9999546$$ and $$\sim 1$$, so you want exponential values between those quantiles.

Simulate from a uniform distribution with those values as the endpoints: values <- runif(N, pexp(10, rate), pexp(50, rate)). These will be the exponential quantiles of your simulated data.

Now pass those quantiles through the exponential quantile function: x <- qexp(values, rate) to look up their values.

This should generate exponential-y data that are limited to your range.

As has been noted, however, if you limit your range like this, you no longer have exponential data.

EDIT

Round as Henry describes if you are determined to have integers.

• Thanks for your answer. Do I still have exponential data if I transform them linearly, for example with +20 of each integer? – Tino May 13 at 20:24
• @Tino If you limit your values beyond “all positive reals” then you do not have exponential data. // Depending on the rate parameter, a range from $10$ to $50$ is really far out in the tail. It makes me wonder if you have something else in mind. – Dave May 13 at 20:26
• I have generated some exponential data with set.seed and I checked that all values are between 0 and 12. My question is if I can transform them linearly (+20) to make them larger. Do I still have exponential data? – Tino May 13 at 20:32
• That’s iffy. You could call it a shifted exponential (I would), but the classical exponential distribution has a lower bound of $0$, not $20$. – Dave May 13 at 20:45
• This will not give integers: one approach would be to take your algorithm on the interval $[10,51)$ and then round down. You actually get a truncated geometric distribution – Henry May 14 at 9:59

You can't "cap off" an exponential distribution. If you limit its values to a certain range it stops being an exponential distribution.

Here's a working example with the uniform distribution:

floor(runif(100, min = 10, max = 51))