简体   繁体   English

使用set.seed函数生成可重现的结果

[英]Generate reproducible results using the set.seed function

If you want to generate 50 reproducible samples, should you use set.seed function in the first way or the second way? 如果要生成50个可重现的样本,应该以第一方式还是第二方式使用set.seed函数?

set.seed(1000)
for(i in 1:50)
  sample(x,10)

or 要么

for(i in 1:50)
  set.seed(1000)
  sample(x,10)

First way 第一种方式

the first sets a starting point for a string of pseudo random numbers to be used in the loop. 第一个为循环中使用的伪随机数字符串设置起点。

the second way sets the same starting point at each run of the loop and will give the same number giving the same result 1:50 times. 第二种方法在循环的每次运行中设置相同的起点,并将给出相同的数字,得出相同的结果1:50倍。

say set.seed(1000) gives a set of random numbers (1,2,3,4,5...,50) 说set.seed(1000)给出一组随机数(1,2,3,4,5 ...,50)

then in the first example you will get a sample corresponding to 1,2,3....,50 然后在第一个示例中,您将获得一个对应于1,2,3 ....,50的样本

but in the second example you will get a sample corresponding to 1,1,1....,1 但在第二个示例中,您将获得一个对应于1,1,1 ....,1的样本

The first method will work if you run all lines at the same time. 如果您同时运行所有行,则第一种方法将起作用。 If you ran the loop a second time without resetting the seed to 1000, or if you had another random event between setting the seed and sampling then you will get different answers. 如果您第二次运行循环而没有将种子重置为1000,或者在设置种子和采样之间还有另一个随机事件,那么您将获得不同的答案。

The second method doesn't work as it will return an identical sample set 50 times. 第二种方法不起作用,因为它将返回相同的样本集50次。

For reproducible samples I would do it this way, (I have set the number of samples, x, equal to 10) 对于可重现的样本,我将以这种方式进行(我将样本数设置为x,等于10)

x=10
for(i in 1:50){
  set.seed(i)
  print(sample(x,10))
}

This will give you 50 different sample sets that will also be exactly the same next time you run the code 这将为您提供50个不同的样本集,这些样本集在您下次运行代码时也将完全相同

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM