sample not respecting set.seed (R 3.5.2)?

I'm trying to use sample_n to randomly select some rows from a dataframe, but want these to be reproducible (at least for now), so I'm using set.seed, but I can't get reproducible selections from my dataframe or something simpler like a vector using sample. Am I missing something? I know there was recent changes in v3.6.0 to how sampling works but FWIW I'm on v3.5.2

set.seed(1)
x <- 1:10
sample(x, 1)
#> [1] 3

sample(x, 1)
#> [1] 4

Created on 2019-05-31 by the reprex package (v0.2.1)

To get the sample() command to return the same value, you need to first run the set.seed() command again.

1 Like

Thanks pete. That appears to be the case:

set.seed(1)
x <- 1:10
sample(x,1)
#> [1] 3

sample(x,1)
#> [1] 4

set.seed(1)
sample(x,1)
#> [1] 3

Created on 2019-05-31 by the reprex package (v0.2.1)

So that leads to another question: is there a way to set set.seed globally? I'm currently working with bookdown and would like to be able to define set.seed once for multiple .Rmd files...

I think this question is sufficiently different that you should start a new thread. It should probably go either in General or R Markdown, since it's not directly related to the tidyverse. :slightly_smiling_face:

This topic was automatically closed 7 days after the last reply. New replies are no longer allowed.