Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Are random seeds "spent" in some way?

Tags:

random

r

I expected this code to give me the same number each time:

set.seed(1)
sample(rep(1:100), size = 1)

However, it doesn't. Here's is how it behaves: it gives me the same number if I run the two lines directly after each other, however, if I then run the second line once again, it gives me something different. Does that mean the seed is "spent" after running sample() once?

I need to produce code that includes random sampling, but which is reproducible. How can I make sure the same, random number is produced each time?

like image 407
histelheim Avatar asked Nov 28 '22 16:11

histelheim


1 Answers

This isn't exactly how things really work, but it helps for understanding.

Imagine that we're drawing numbers between 0 and 9 by looking them up in a pre-generated book of random numbers. A really long book with lots and lots of random draws made by some bored undergraduate intern with a fair 10-sided die. What R normally does is look at the number following whatever the previous random number was in the book. So if the book starts 4, 5, 2, 8, 3, 4, 4, 1, 7, 0, 4, ... the first random number will be 4, then 5 etc.

The results will be as random as the book is---no matter where in the book we start. Typically, you don't know what you're going to get because you have no idea where in the book R is currently at, maybe page 103, maybe page 10003. Setting the seed tells R to start at a specific place. So set.seed(1) says "start on page 1", so you now can count on that "4" being first, and then followed by a 5, and so forth.

like image 81
Gregor Thomas Avatar answered Dec 05 '22 06:12

Gregor Thomas