How To Choose A Random Number in R
How To Choose A Random Number in R
How To Choose A Random Number in R
The answer depends on what kind of random number you want to generate. Let's illustrate by
example.
If you want to generate a decimal number where any value (including fractional values)
between the stated minimum and maximum is equally likely, use the runif function. This
function generates values from the Uniform distribution. Here's how to generate one random
number between 5.0 and 7.5:
Of course, when you run this, you'll get a different number, but it will definitely be between
5.0 and 7.5. You won't get the values 5.0 or 7.5 exactly, either.
If you want to generate multiple random values, don't use a loop. You can generate several
values at once by specifying the number of values you want as the first argument to runif.
Here's how to generate 10 values between 5.0 and 7.5:
This looks like the same exercise as the last one, but now we only want whole numbers, not
fractional values. For that, we use the sample function:
Note the number 6 appears twice in the 5 numbers generated. (Here's a fun exercise: what is
the probability of running this command and having no repeats in the 5 numbers generated?)
If you wanted to simulate the lotto game common to many countries, where you randomly
select 6 balls from 40 (each labelled with a number from 1 to 40), you'd again use the sample
function, but this time without replacement:
You'll get a different 6 numbers when you run this, but they'll all be between 1 and 40
(inclusive), and no number will repeat. Also, you don't actually need to include the
replace=F option -- sampling without replacement is the default -- but it doesn't hurt to
include it for clarity.
You can use this same idea to generate a random subset of any vector, even one that doesn't
contain numbers. For example, to select 10 distinct states of the US at random:
You can't sample more values than you have without allowing replacements:
You could also have just used sample(state.name) for the same result -- sampling as
many values as provided is the default.
Further reading
For more information about how R generates random numbers, check out the following help
pages:
> ?runif
> ?sample
> ?.Random.seed
The last of these provides technical detail on the random number generator R uses, and how
you can set the random seed to recreate strings of random numbers.