R 忽略.Random.seed
lapply 内部的设置。但是,使用set.seed
效果很好。
一些代码:
# I can save the state of the RNG for a few seeds
seed.list <- lapply( 1:5, function(x) {
set.seed(x)
seed.state <- .Random.seed
print( rnorm(1) )
return( seed.state )})
#[1] -0.6264538
#[1] -0.8969145
#[1] -0.9619334
# But I get different numbers if I try to restore
# the state of the RNG inside of an lapply
tmp.rest.state <- lapply(1:5, function(x) {
.Random.seed <- seed.list[[x]]
print(rnorm(1))})
# [1] -0.2925257
# [1] 0.2587882
# [1] -1.152132
# lapply is just ignoring the assignment of .Random.seed
.Random.seed <- seed.list[[3]]
print( rnorm(1) ) # The last printed value from seed.list
# [1] -0.9619334
print( rnorm(1) ) # The first value in tmp.rest.state
# [1] -0.2925257
我的目标是检查点 MCMC 运行,以便它们可以准确地恢复。我可以轻松保存 RNG 的状态,只是无法让 R 在 lapply 循环中加载它!
有没有办法强制 R 注意到设置.Random.seed
?或者有没有更简单的方法来实现这一点?
万一这很重要,我使用的是 64 位 R:
R version 2.15.1 (2012-06-22) -- "Roasted Marshmallows"
Platform: x86_64-pc-linux-gnu (64-bit)
在 Ubuntu 12.04 LTS 上:
nathanvan@nathanvan-N61Jq:~$ uname -a
Linux nathanvan-N61Jq 3.2.0-26-generic #41-Ubuntu SMP Thu Jun 14 17:49:24 UTC 2012 x86_64 x86_64 x86_64 GNU/Linux