How to automatically set a random seed to the current time?
Every time the R console is opened, a random seed is set to the same value. On my computer (it might be the same on your computer), if I run rnorm(1)
, I always get 0.1777571
on the first call.
I tried to automatically set a random seed using the current computer 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 won't change anything. The first call rnorm(1)
always returns 0.1777571
.
How can I automatically set a random seed to the current computer time?
EDIT
I open an R session directly on the terminal. I just clicked r
and didn't load the explicit workspace.
source to share
The documentation for set.seed
says a few interesting things:
Initially there is no seed; a new one is created from the current time and process id when required. Hence, different sessions will give different default simulation results. However, seeds can be restored from a previous session if a previously saved workspace is restored.
The behavior you're describing is consistent with the previous version .Random.seed
being restored when the previous workspace is loaded, which seems to have to be executed after the code you have in has run .RProfile
.
Another interesting thing is that the documentation suggests that just using set.seed(NULL)
will do what you want with less work.
Here is a thread from the R mailing list that discusses the following: https://stat.ethz.ch/pipermail/r-help/2010-October/255734.html
source to share