`sample()` gives different values with same `set.seed()`

N8TRO picture N8TRO · Mar 7, 2013 · Viewed 9.1k times · Source

I was creating some random samples and plotting them and noticed a strange behavior. Sampled values were different after loading ggplot2:

set.seed(111)
library(ggplot2)
sample(1:10, 10)
# [1]  8  4  5  3  7  1  6  2 10  9

set.seed(111)
sample(1:10, 10)
#  [1]  6  7  3  4  8 10  1  2  9  5

I can avoid this behavior easily enough, but is there any reason for ggplot2 to change the seed value?

Answer

Ben Bolker picture Ben Bolker · Mar 7, 2013

I think I saw some discussion of this in one of the R chat rooms: ggplot2 calls the random number generator in order to decide whether/which tip it wants to offer.

In particular, this is ggplot2:::.onAttach:

function (...) 
{
    if (!interactive() || stats::runif(1) > 0.1) 
        return()
    tips <- c("Need help? Try the ggplot2 mailing list: http://groups.google.com/group/ggplot2.", 
        paste("Find out what's changed in ggplot2 with\n", "news(Version == \"", 
            utils::packageVersion("ggplot2"), "\", package = \"ggplot2\")", 
            sep = ""), "Use suppressPackageStartupMessages to eliminate package startup messages.")
    tip <- sample(tips, 1)
    packageStartupMessage(tip)
}

It's sort of amusing that one of the randomly generated tips tells you how to turn off the tips ...