Intellipaat Back

Explore Courses Blog Tutorials Interview Questions
0 votes
4 views
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

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.

31k questions

32.8k answers

501 comments

693 users

Browse Categories

...