Chapter 9 Random Sampling in R

We use random sampling for a lot of things in statistics. Anytime we use random sampling we need to set a random seed.

set.seed(100)

This ensures that if you run the code again, you will get the same results.

9.1 The Sample Function

Most of the time when we create a random sample, we use the sample function. It has three inputs:

sample( What I am sampling from? , How many samples do I want?, Do I want to sample with Replacement?)

For example, suppose I want to choose 3 random numbers between 1 and 10, but I do not want any duplicates. My inputs are then:

  • What I am sampling from? 1:10
  • How many samples do I want? 3
  • Do I want to sample with replacement? No, so replace = FALSE

This means that the code I need is

# Set my random seed 
set.seed(100)

# Draw the random sample 
sample( 1:10 , 3, replace = FALSE)