I'd like to set seeds in R only locally (inside functions), but it seems that R sets seeds not only locally, but also globally. Here's a simple example of what I'm trying (not) to do.
我想在R中仅在本地设置种子(内部函数),但似乎R不仅在本地设置种子,而且在全局设置种子。这是我正在尝试(不)做的一个简单示例。
myfunction <- function () {
set.seed(2)
}
# now, whenever I run the two commands below I'll get the same answer
myfunction()
runif(1)
So, my questions are: why does R set the seed globally and not only inside my function? And how I can make R to set the seed only inside my function?
所以,我的问题是:为什么R在全局设置种子而不仅仅是在我的函数中?我怎样才能让R只在我的函数中设置种子?
1 个解决方案
#1
33
Something like this does it for me:
像这样的东西对我来说:
myfunction <- function () {
old <- .Random.seed
set.seed(2)
res <- runif(1)
.Random.seed <<- old
res
}
Or perhaps more elegantly:
或者更优雅:
myfunction <- function () {
old <- .Random.seed
on.exit( { .Random.seed <<- old } )
set.seed(2)
runif(1)
}
For example:
例如:
> myfunction()
[1] 0.1848823
> runif(1)
[1] 0.3472722
> myfunction()
[1] 0.1848823
> runif(1)
[1] 0.4887732
#1
33
Something like this does it for me:
像这样的东西对我来说:
myfunction <- function () {
old <- .Random.seed
set.seed(2)
res <- runif(1)
.Random.seed <<- old
res
}
Or perhaps more elegantly:
或者更优雅:
myfunction <- function () {
old <- .Random.seed
on.exit( { .Random.seed <<- old } )
set.seed(2)
runif(1)
}
For example:
例如:
> myfunction()
[1] 0.1848823
> runif(1)
[1] 0.3472722
> myfunction()
[1] 0.1848823
> runif(1)
[1] 0.4887732