Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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?

like image 337
N8TRO Avatar asked Mar 07 '13 01:03

N8TRO


People also ask

Does set seed work with sample?

set. seed has an effect on all random number draws. sample uses random number draws.

Can you set seed for sample in R?

In R, we can set a random seed to make the output of our R code reproducible. By setting a specific seed, the random processes in our script always start at the same point and hence lead to the same result.

What is the set seed () function used for?

The set. seed() function sets the starting number used to generate a sequence of random numbers – it ensures that you get the same result if you start with that same seed each time you run the same process.


1 Answers

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 ...

like image 75
Ben Bolker Avatar answered Sep 19 '22 17:09

Ben Bolker