您可以在函数的开头设置种子,然后在退出时恢复旧种子。这是一个快速演示,在函数之后进行了测试。
rnorm_seed <- function(n, mean = 0, sd = 1, seed = NULL) {
if (!is.null(seed)) {
# reinstate system seed after simulation
sysSeed <- .GlobalEnv$.Random.seed
on.exit({
if (!is.null(sysSeed)) {
.GlobalEnv$.Random.seed <- sysSeed
} else {
rm(".Random.seed", envir = .GlobalEnv)
}
})
set.seed(seed, kind = "Mersenne-Twister", normal.kind = "Inversion")
}
rnorm(n, mean, sd)
}
# test
set.seed(8675309)
rnorm(1) # -0.9965824
rnorm(1) # 0.7218241
rnorm(1) # -0.6172088
set.seed(8675309)
rnorm(1) # -0.9965824
rnorm(1) # 0.7218241
rnorm_seed(1, seed = 8675309) # -0.9965824
rnorm(1) # -0.6172088