Private archive copy · Unofficial site · Content copyright belongs to Runoob Tutorial and the original authors · View Original

R set.seed() Function - Setting the Random Seed

R set.seed() Function - Setting the Random Seed

R Language Examples R Language Examples

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:

Example

Without a seed, results differ each time

print

(

"First run (no seed):"

)

print

(

rnorm

(

5

)

)

print

(

"Second run (no seed):"

)

print

(

rnorm

(

5

)

)

Set a seed for reproducible results

set.seed

(

123

)

print

(

"First run (seed 123):"

)

print

(

round

(

rnorm

(

5

)

,

4

)

)

set.seed

(

123

)

print

(

"Second run (seed 123, same result):"

)

print

(

round

(

rnorm

(

5

)

,

4

)

)

set.seed

(

456

)

print

(

"Third run (seed 456, different result):"

)

print

(

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 R Language Examples