[R] randomness using runif

David Winsemius dwinsemius at comcast.net
Fri Jul 23 17:29:20 CEST 2010


On Jul 23, 2010, at 11:16 AM, Brigid Mooney wrote:

> I'm  working on a problem where I'm introducing random error and have
> been using the built in function runif to provide that random error.
> However, I realized that I seem to be getting some unexpected behavior
> out of the function and was hoping someone could share some insight.
>
> I don't know the runif algorithm at all, but from the behavior I'm
> seeing, it seems that whenever I open a new R console, the function
> runif gets "reset" to some initial value.

?set.seed

 From the help page for set.seed:

Note
"Initially, there is no seed; a new one is created from the current  
time when one is required. Hence, different sessions started at  
(sufficiently) different times will give different simulation results,  
by default. However, the seed might be restored from a previous  
session if a previously saved workspace is restored."

So you probably have saved a value in your workspace.



-- 

David.


>  For example...
>
> In a NEW R console, enter the following:
>
> x1 <- runif(1000, -1, 1)
> x2 <- runif(1000, -1, 1)
>
> x1[1:5]
> x2[1:5]
>
> objectsToSave <- c("x1", "x2")
> filename <- "C:\\Documents\\x1x2file.Rdata"
>
> save(list=objectsToSave, file=filename, envir = parent.frame())
>
>
> Then in a different NEW R console, enter this:
>
> x3 <- runif(1000, -1, 1)
> x4 <- runif(1000, -1, 1)
>
> x3[1:5]
> x4[1:5]
> # For me, the values look identical to x1 and x2, but let's check by
> loading the x1x2 file and comparing them directly...
>
> filename <- "C:\\Documents\\x1x2file.Rdata"
>
> load(filename)
>
> sum(x1==x3)
> sum(x2==x4)
>
>
> For my results, I get that x1=x3 for all 1000 elements in the vector,
> and x2=x4 for all 1000 elements in that vector.
>
> Does anyone have insight into what's going on here?  Am I doing
> something wrong here, or is this a quirk of the runif algorithm?  Is
> there a better function out there for seeding truly random error?
>
> For what it's worth, here's my R version info:
>
> platform       i386-pc-mingw32
> arch           i386
> os             mingw32
> system         i386, mingw32
> status
> major          2
> minor          8.1
> year           2008
> month          12
> day            22
> svn rev        47281
> language       R
> version.string R version 2.8.1 (2008-12-22)
>
> Thanks for the help,
> Brigid
>
> ______________________________________________
> R-help at r-project.org mailing list
> https://stat.ethz.ch/mailman/listinfo/r-help
> PLEASE do read the posting guide http://www.R-project.org/posting-guide.html
> and provide commented, minimal, self-contained, reproducible code.

David Winsemius, MD
West Hartford, CT



More information about the R-help mailing list