📚 R Programming Tutorial

R Programming

Learn R programming concepts with simple explanations, examples, techniques and practical notes.

← Back to R Programming

Ensuring Consistency in Debugging Simulation Code

If you are doing anything with random numbers, you will need to be able to reproduce the same stream of numbers each time you run your program during the debugging session. Without this, your bugs may not be reproducible, making them even harder to fix.

The set.seed() function controls this by reinitializing the random number sequence to a given value.

Consider this example:

> runif(3)
[1] 0.5775979 0.4588383 0.8354707
> runif(3)
[1] 0.4155105 0.4852900 0.6591892
> runif(3)
> set.seed(8888)
> runif(3)
[1] 0.5775979 0.4588383 0.8354707
> set.seed(8888)
> runif(3)
[1] 0.5775979 0.4588383 0.8354707

The call runif(3) generates three random numbers from the uniform distribution on the interval (0,1). Each time we make that call, we will get a different set of three numbers. But with set.seed(), we can start over and get the same sequence of numbers.