问题
Every time one opens a R console, the random seed is set to the same value. On my computer (it might be the same on your machine), if I run rnorm(1)
, I always get 0.1777571
at the first call.
I tried to automatically set the random seed using the computer current time by adding something like
set.seed(
as.integer(
as.numeric(
gsub("[^0-9]","",paste(format(Sys.time(), "%Y %X %x")))
)%%.Machine$integer.max
)
)
in the file .Rprofile
but it does not change anything. The first call to rnorm(1)
always return 0.1777571
.
How can I automatically set the random seed to the computer current time?
EDIT
I open R session directly on the terminal. I just hit r
and do not explicitly load any previous workspace.
回答1:
The documentation for set.seed
says a couple of interesting things:
Initially, there is no seed; a new one is created from the current time and the process ID when one is required. Hence different sessions will give different simulation results, by default. However, the seed might be restored from a previous session if a previously saved workspace is restored.
The behavior that you describe is consistent with a previous version of .Random.seed
being restored when a previous workspace is loaded, which seems like it must be after the code that you have in .RProfile
is run.
Another interesting thing is that the documentation suggests that simply using set.seed(NULL)
will do the sort of thing you want with less work.
Here is a thread from an R mailing list which discusses this: https://stat.ethz.ch/pipermail/r-help/2010-October/255734.html
来源:https://stackoverflow.com/questions/42982672/how-to-automatically-set-the-random-seed-on-current-time