How do you set the random seed in R language?
In R language, we can use the set.seed() function to specify the random number seed. The parameter for this function is an integer, which can be any integer. By calling set.seed() with the same integer, R will produce the same random number sequence every time.
Here is an example of setting a random number seed:
set.seed(123) # 设置随机数种子为123
random_numbers <- rnorm(5) # 生成5个服从标准正态分布的随机数
print(random_numbers)
set.seed(123) # 再次设置随机数种子为123
random_numbers <- rnorm(5) # 再次生成5个服从标准正态分布的随机数
print(random_numbers)
In the code above, we first set the random number seed to 123 using set.seed(123), then generate 5 random numbers following a standard normal distribution using the rnorm() function and store them in the random_numbers variable. Next, we set the random number seed to 123 again with set.seed(123) and generate 5 more random numbers following a standard normal distribution. Because the seed was set the same way both times, the generated random number sequences are also the same.