R set.seed() Function - Setting Random Seed

R 语言实例R Language Examples

The R set.seed() function is used to set the seed for the random number generator.

After setting the seed, the sequence of "random numbers" generated is the same each time, ensuring the reproducibility of experimental results.

The syntax of the set.seed() function is as follows:

set.seed(seed)

Parameter description:

  • seedAn integer, used as the starting value for the random number generator. The same seed always generates the same sequence.

Example

# Without setting 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, results are reproducible
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))

Running the above code produces the following output:

[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 语言实例R Language Examples

Other Extensions