R set.seed() Function - Setting the Random Seed
The R set.seed() function is used to set the seed of the random number generator.
After setting the seed, each run generates the same sequence of "random numbers", ensuring reproducible experimental results.
The syntax of the set.seed() function is as follows:
set.seed(seed)
Parameter Description:
-
seed An integer used as the starting value of the random number generator. The same seed always generates the same sequence.
Example
Without a seed, results differ each time
(
"First run (no seed):"
)
(
rnorm
(
5
)
)
(
"Second run (no seed):"
)
(
rnorm
(
5
)
)
Set a seed for reproducible results
set.seed
(
123
)
(
"First run (seed 123):"
)
(
round
(
rnorm
(
5
)
,
4
)
)
set.seed
(
123
)
(
"Second run (seed 123, same result):"
)
(
round
(
rnorm
(
5
)
,
4
)
)
set.seed
(
456
)
(
"Third run (seed 456, different result):"
)
(
round
(
rnorm
(
5
)
,
4
)
)
The output of the code above is:
[1] "第一次运行(无种子):"
[1] 1.3709584 -0.5646982 0.3631284 0.6328626 0.4042683
[1] "第二次运行(无种子):"
[1] -0.1061245 1.5115220 -0.0946590 2.0184237 -0.0627141
[1] "第一次运行(种子 123):"
[1] -0.5605 -0.2302 1.5587 0.0705 0.1293
[1] "第二次运行(种子 123,相同结果):"
[1] -0.5605 -0.2302 1.5587 0.0705 0.1293
[1] "第三次运行(种子 456,不同结果):"
[1] -0.0429 -0.8505 0.3032 1.6108 -0.3880
R Language Examples