Generating random samples
In this section, we will introduce how to generate random samples from a given population with the sample
and sample.int
functions.
Getting ready
In this recipe, you need to prepare your environment with R installed.
How to do it…
Please perform the following steps to generate random samples.
First, generate random samples from
1
to10
:> sample(10)
If you would like to reproduce the same samples, you can set the random seed beforehand:
> set.seed(123) > sample(10) [1] 3 8 4 7 6 1 10 9 2 5
You can then randomly choose two samples from
1
to10
:> sample(10,2) [1] 10 5
If the population and sample size are required arguments, you can also use the
sample.int
function:> sample.int(10,size=2) [1] 7 6
For example, one can simulate a lottery game and generate six random samples from a given population with a size of
42
:> sample.int(42,6) [1] 5 37 10 2 13 36
Alternatively, one can generate random samples with replacements by setting the
replace...