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 1 10 1 5 5 1 3 8 2
#> Error in sample.int(length(x), size, replace, prob): cannot take a sample larger than the population when 'replace = FALSE'
#> [1] 1 4 4 10 8 4 10 3 1 1 6 6 1 1 6 4 5 4
#> [19] 9 5
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
#> 797 809 803 863 881 847
#> rolls_from_sample.int
#> 1 2 3 4 5 6
#> 848 829 818 839 828 838
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.