samedi 19 septembre 2020

How many times to use set.seed in R

I'm working on a little demonstration that says adding constant numbers to variables doesn't change their correlations.

For reproducibility purposes, I use a set.seed(1). When I use rnorm(), I get the expected correlations to match (see DEMO 1).

But when I use MASS::mvrnorm() it seems I must use set.seed(1) two times to obtain expected correlations to match (see DEMO 2).

Why this is happening? What should I learn about set.seed() to know how many times I need to use it for similar demonstrations?

## DEMO 1:
gamma_00 = 10
gamma_10 = 2

set.seed(1)
U0j = rnorm(9, sd = 2) 
U1j = rnorm(9, sd = 3) 

cor(U0j,U1j) # -0.2946243

B0j = gamma_00 + U0j
B1j = gamma_10 + U1j

cor(B0j,B1j) # -0.2946243


## DEMO 2:
G = matrix(c(4,.2,.2,5),2)

set.seed(1)
Uj = MASS::mvrnorm(9, mu = c(0,0), Sigma = G)

cor(Uj) # 0.2052711

set.seed(1)
Bj = MASS::mvrnorm(9, mu=c(2,3), Sigma = G)

cor(Bj) # 0.2052711



Aucun commentaire:

Enregistrer un commentaire