简体   繁体   English

如何在特定代码行之后停止set.seed()?

[英]How do I stop set.seed() after a specific line of code?

I would like to end the scope of set.seed() after a specific line in order to have real randomization for the rest of the code. 我想在特定行之后结束set.seed()的范围,以便对其余代码进行实际随机化。 Here is an example in which I want set.seed() to work for "rnorm" (line 4), but not for "nrow" (line 9) 这是一个例子,我希望set.seed()用于“rnorm”(第4行),但不是“nrow”(第9行)

set.seed(2014)
f<-function(x){0.5*x+2}
datax<-1:100
datay<-f(datax)+rnorm(100,0,5)
daten<-data.frame(datax,datay)
model<-lm(datay~datax)
plot(datax,datay)
abline(model)
a<-daten[sample(nrow(daten),20),]
points(a,col="red",pch=16)
modela<-lm(a$datay~a$datax)
abline(modela, col="red")

Thanks for suggestions, indeed! 真的感谢您的建议!

Simply use the current system time to "undo" the seed by introducing a new unique random seed: 只需使用当前系统时间通过引入新的唯一随机种子来“撤消”种子:

set.seed(Sys.time())

If you need more precision, consider fetching the system timestamp by millisecond (use R's system(..., intern = TRUE) function). 如果您需要更高的精度,请考虑以毫秒为单位获取系统时间戳 (使用R的system(..., intern = TRUE)函数)。

set.seed() only works for the next execution. set.seed()仅适用于下一次执行。 so what you want is already happening. 所以你想要的已经发生了。

see this example 看这个例子

set.seed(12)
sample(1:15, 5)

[1] 2 12 13 4 15 [1] 2 12 13 4 15

sample(1:15, 5) # run the same code again you will see different results

[1] 1 3 9 15 12 [1] 1 3 9 15 12

set.seed(12)#set seed again to see first set of results
sample(1:15, 5)

[1] 2 12 13 4 15 [1] 2 12 13 4 15

set.seed(NULL)

See help documents - ?set.seed : 请参阅帮助文档 - ?set.seed

"If called with seed = NULL it re-initializes (see 'Note') as if no seed had yet been set." “如果使用seed = NULL调用它,则会重新初始化(请参阅'注意'),就好像还没有设置种子一样。”

set.seed() just works for the first line containing randomly sample, and will not influence the next following command. set.seed()只适用于包含随机样本的第一行,不会影响下一个命令。 If you want it to work for the other lines, you must call the set.seed function with the same "seed"-the parameter. 如果希望它适用于其他行,则必须使用相同的“种子” - 参数调用set.seed函数。

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

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