In R, we use sample() function whenever to want to generate a random sample of a specified from dataset. This can be done with or without replacement. We can create a numeric or character vector sample using sample() function.
Whenever you are generating random sample, you are using an algorithm that requires a seed whose function is to initialise. These numbers are actually pseudorandom numbers which can be predicted if we know the seed and the generator.
Setting a seed means iniltialising a pseudorandom generator. We set a seed when we need the same output of numbers everytime you want to generate random numbers. If we don't set a seed, the generated pseudorandom numbers are different on each execution.
In most of the simulation methods in statistics, random numbers are used to mimic the properties of uniform or normal distribution in a certain interval.
In this recipe, you will learn how to use sample() function by setting a seed.
Generating a sample of 10 random numbers between 1 and 30 by setting a seed without replacement (i.e. every value will be unique)
Syntax: sample(x, size = , replace = )
We use set.seed() function to set a seed. We specify any integer in the function as a seed.
# setting a seed set.seed(20) # Generating a sample of 10 random numbers between 1 and 30 by setting a seed without replacement (i.e. every value will be unique) sample(1:30, 10, replace = FALSE)
6 11 24 2 25 27 13 9 3 28
Note: The random numbers generated remains constant even after multiple executions.