3

I use the following code:

set.seed(74)
length = 10
W = rep(0,length)
W[1] = 0
for (i in 1:length){ 
W[i+1] = W[i]+ rnorm(1)
}`

with the aim to always generate the same range of W when using the seed 74. Now, I want to add another vector, called Z but keep the same W:

set.seed(74)
length = 10
W = rep(0,length)
Z = rep(0,length)
W[1] = 0
Z[1] = 0
for (i in 1:length){ 
W[i+1] = W[i]+ rnorm(1)
Z[i+1] = Z[i] + rnorm(1)
}`

Now, the problem occurs that W is changing, but I want the same W as in the first code and an additional random Z. Actually, I do not get what the command set.seed() is really doing.

I would appreciate any help. `

Stephanie
  • 63
  • 1
  • 3
  • https://stackoverflow.com/questions/13605271/reasons-for-using-the-set-seed-function for the second question. – user202729 Jul 16 '18 at 01:49

1 Answers1

3

set.seed() sets the seed of the (pseudo) random number generator that is used to produce the values called by rnorm(). It can be thought of as the starting place for a predetermined list of random numbers to be generated. If you pick a seed, say 100 (the value is completely arbitrary), and run

set.seed(100); rnorm(10)

you will get the exact same results as when you set the seed to the same value and run the same command. If you set a different seed, you will (likely) get a different string of numbers.

Thinking of the random numbers as a long, predetermined list will help you understand why the second block of code produces different values for W than the first block. Imagine that for each random number you draw, you move one down the list. With the first block of code, you select 10 random numbers and set them in W. In the second block of code, you select one random number and set it to W, then another random number and set it to Z, and so on. The positions of the random numbers generated for W are different between the two blocks.; all 10 of them go to W in the first block, but only half of them go to W in the second block (the other half go to Z).

Although, note that W[2] is the same between both blocks; in both cases, this is the first random number generated after setting the seed. The second number goes to Z. In the first block, if you take W[3]-W[2], which gives you value of the second random number drawn after setting the seed, you'll see that this is equal to Z[2] in the second block, which is also the second number drawn after setting the seed.

To get the same results in W each time, you need to make sure the order of the random numbers is respected. This means instead of the second block, you should run the first block once for W and once for Z (only setting the seed once, i.e., only before W).

Noah
  • 3,437
  • 1
  • 11
  • 27