R How to Set a Random Seed Using set.seed() Function (Example Code)

In this tutorial you’ll learn how to specify a random seed using the set.seed() function in the R programming language.

Example: Sampling Data with & without Random Seed

sample(LETTERS, 4)        # Sampling without seed
# [1] "A" "E" "Q" "I"
sample(LETTERS, 4)        # Sampling again without seed (different output)
# [1] "J" "V" "Y" "O"
set.seed(9267482)         # Setting seed in R
sample(LETTERS, 4)        # Sampling with seed
# [1] "P" "A" "Q" "T"
set.seed(9267482)         # Setting seed again
sample(LETTERS, 4)        # Same output
# [1] "P" "A" "Q" "T"

Leave a Reply

Your email address will not be published. Required fields are marked *

Fill out this field
Fill out this field
Please enter a valid email address.
You need to agree with the terms to proceed

Menu
Top