A Solution: Simulations

A.1 Solution Simulation - replacement

The option replace=TRUE activates sampling with replacement (i.e. the numbers that are picked are put back and can be picked again).

The option replace=FALSE activates sampling without replacement (i.e. the numbers that are picked are not put back and cannot be picked again).

Let’s try this out:

x <- c(1, 2, 2, 3, 4, 1, 6, 7, 8, 10, 5, 5, 1, 4, 9)

# Working example
sample(x, 10, replace = FALSE)
#>  [1] 4 8 1 4 5 1 1 2 7 5
# This will cause an error
sample(x, 20, replace = FALSE)
#> Error in `sample.int()`:
#> ! cannot take a sample larger than the population when 'replace = FALSE'
# Fix it
sample(x, 20, replace = TRUE)
#>  [1]  4  4  1  9  6  2  5  4  4  8  2  7  4  6  2  5 10  1
#> [19]  5  1

A.2 Solution Simulation - using sample

rolls_from_sample <- sample(c(1:6), size = 5000, replace = TRUE)
rolls_from_sample.int <- sample(6, size = 5000, replace = TRUE)

table(rolls_from_sample)
#> rolls_from_sample
#>   1   2   3   4   5   6 
#> 872 846 818 790 833 841
table(rolls_from_sample.int)
#> rolls_from_sample.int
#>   1   2   3   4   5   6 
#> 902 826 774 841 816 841

Both gives a uniform distribution over the numbers 1-6. The function sample.int is a specialised version of sample for sampling integers. Many R libraries have specialised versions of more general functions to do specific tasks under certain conditions.