How to Generate a Random Sample in R

05.01.2021

Generating a random sample is a common task in statistics. You use random samples to conducts tests, simulate probabilities and much more. In this article, we will learn how to generate a random sample in R.

To generate a random sample in R, we can use the sample method. The default signature for this method is sample(sampleSpace, numberOfSamples). For example, if we wanted to generate samples of rolling a die, we could pass a vector of numbers from 1:6.

sample.space = c(1:6)
number.samples = 6

sample(sample.space, number.samples)

# [1] 2 4 5 6 3 1

However, by default, the sample function pulls without replacement. If we want to simulate rolling a die, we would sample with replacement because we always have six sides. We can pass the replace=TRUE option to the sample method.

sample.space = c(1:6)
number.samples = 20

sample(sample.space, number.samples, replace=TRUE)

#  [1] 6 1 4 1 6 2 3 2 6 6 2 5 2 6 6 6 1 3 3 6

Above, we can see we simulated one sample of rolling a 6 sided die 20 times.