jimifiki
jimifiki

Reputation: 5534

R: sample from independent random generators

I have an R code like this.

D1 <- runif(0,1); 
D2 <- runif(0,1); 
U1 <- runif(0,1); 
U2 <- runif(0,1); 

but I don't want Ds and Us to consume the same distribution!!

How can I do something behaving like this?

distrD <- rand(seed1) 
distrU <- rand(seed2) 

D1 <- distrD.runif(0,1); 
D2 <- distrD.runif(0,1); 
U1 <- distrU.runif(0,1); 
U2 <- distrU.runif(0,1); 

distr_D <- rand(seed1) 
distr_U <- rand(seed2) 

nD1 <- distr_D.runif(0,1); 
nU1 <- distr_U.runif(0,1); 
nU2 <- distr_U.runif(0,1); 
nD2 <- distr_D.runif(0,1); 

giving random numbers fulfilling this:

nD1 == D1 
nD2 == D2 
nU1 == U1 
nU2 == U2 

I don't know in advance how many times each distribution is asked for a new number. So I cannot store it in an array.

Suggestions?

Upvotes: 0

Views: 131

Answers (1)

Roland
Roland

Reputation: 132706

Maybe like this:

library(rngtools)

Dseeds <- RNGseq(2, seed = 1)
Useeds <- RNGseq(2, seed = 2)

RNGseed(Dseeds[[1]])
D1 <- runif(1, 0, 1)
RNGseed(Dseeds[[2]])
D2 <- runif(1, 0, 1)
RNGseed(Useeds[[1]])
U1 <- runif(1, 0, 1) 
RNGseed(Useeds[[2]])
U2 <- runif(1, 0, 1) 

RNGseed(Dseeds[[1]])
nD1 <- runif(1, 0, 1)
RNGseed(Useeds[[1]])
nU1 <- runif(1, 0, 1)
RNGseed(Useeds[[2]])
nU2 <- runif(1, 0, 1)
RNGseed(Dseeds[[2]])
nD2 <- runif(1, 0, 1)

nD1 == D1 
#[1] TRUE
nD2 == D2 
#[1] TRUE
nU1 == U1 
#[1] TRUE
nU2 == U2 
#[1] TRUE

Draw as many seeds as you think you might need (an overestimate should be possible). If you need more you can use something like RNGseq(n, Dseeds[[2]])[-1].

Of course, it would be better to draw two samples of random numbers (setting the seed each time) and store the seed after producing each of them in order to reset the seed to that value when you'd need to produce additional randoms for one of the samples.

Upvotes: 1

Related Questions