Set.seed, ggplot2 and reprex

Inspired by LucyStat's tweet about set.seed and library(ggplot2) I wrote this example

set.seed(42)
runif(1)
set.seed(42)
1+1
runif(1)
set.seed(42)
library("ggplot2")
runif(1)

in which the third call to runif gives a different number than the first two, which was expected. This only works in a new session. I wanted to illustrate it using reprex::reprex() but here is the output.

set.seed(42)
runif(1)
#> [1] 0.914806
set.seed(42)
1+1
#> [1] 2
runif(1)
#> [1] 0.914806
set.seed(42)
library("ggplot2")
runif(1)
#> [1] 0.914806

Am I doing something wrong?

5 Likes

From this line of code, ggplot2 only picks a random tip if the R session is interactive. From reprex::reprex(x = interactive()), you will see that reprex does not run an interactive session.

3 Likes

Aaah this makes sense! Thanks a ton!

2 Likes

You're welcome! I think this is an important edge case, so I submitted an issue: https://github.com/tidyverse/reprex/issues/167.

2 Likes

Jim Hester seems to have fixed the set.seed ordering issue: https://github.com/tidyverse/ggplot2/pull/2409/commits

3 Likes