0 votes
1 view
in R Programming by (7.3k points)

Many times I have seen the set.seed function in R, before starting the program. I know it's basically used for the random number generation. Is there any specific need to set this?

1 Answer

0 votes
by (25.4k points)

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.

Welcome to Intellipaat Community. Get your technical queries answered by top developers !


Categories

...