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 5 2 1 1 4 7 8 1 2
#> Error in sample.int(length(x), size, replace, prob): cannot take a sample larger than the population when 'replace = FALSE'
#> [1] 10 4 4 10 1 7 9 1 1 8 5 2 4 7 10 6 3 5
#> [19] 9 3
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
#> 871 803 819 828 841 838
#> rolls_from_sample.int
#> 1 2 3 4 5 6
#> 823 830 824 860 845 818
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.