jeudi 15 avril 2021

How to fix the random seed of sample function in R

I am wondering how to fix the random seed of sample function in R.

An easy example is here:

set.seed(1)
tmp <- c(1, 2, 3, 4, 5, 6, 7, 8, 9, 10)
sample(tmp, size = 3)       # (*)
#[1] 9 4 7
sample(tmp, size = 3)       # (**)
#[1] 1 2 5
sample(tmp, size = 3)       # (***)
#[1] 7 2 3
sample(tmp, size = 3)       # (****)
#[1] 3 1 5

# retry set the random seed
set.seed(1)
sample(tmp, size = 3)       # (*)
#[1] 9 4 7
sample(tmp, size = 3)       # (**)
#[1] 1 2 5
sample(tmp, size = 3)       # (***)
#[1] 7 2 3
sample(tmp, size = 3)       # (****)
#[1] 3 1 5

Then, when I repeat the sample function, the returned values change, although pattern of the change is uniform.

I cannot understand why sample function is differently affected from the set.seed. How can I fix the return from sample function?

Thank you for your time to spend to read this question.




Aucun commentaire:

Enregistrer un commentaire