The set.seed function is used to generate a reproducible random result.
For example:
Sampling without set.seed:
s1 <- sample(LETTERS,8)
> s1
[1] "Q" "E" "K" "R" "H" "O" "Y" "L"
> s1 <- sample(LETTERS,8)
> s1
[1] "X" "K" "Y" "J" "D" "P" "G" "I"
Sampling with set.seed:
> set.seed(123)
> s1 <- sample(LETTERS,8)
> s1
[1] "O" "S" "N" "C" "J" "R" "K" "E"
> set.seed(123)
> s1 <- sample(LETTERS,8)
> s1
[1] "O" "S" "N" "C" "J" "R" "K" "E"
Fixing the seed helps in optimizing a function that involves randomly generated numbers. If we do not fix the seed, the variation due to generating different random numbers will probably cause the optimization algorithm to fail.