library(cheapr)
# Using `with_local_seed()`
# The below 2 statements are equivalent
# Statement 1
set.seed(123456789)
res <- rnorm(10)
# Statement 2
res2 <- with_local_seed(rnorm(10), .seed = 123456789)
# They are the same
identical(res, res2)
# As an example we can see that the RNG is unaffected by generating
# random uniform deviates in batches between calls to `with_local_seed()`
# and comparing to the first result
set.seed(123456789)
batch1 <- rnorm(2)
with_local_seed(runif(10))
batch2 <- rnorm(2)
with_local_seed(runif(10))
batch3 <- rnorm(1)
with_local_seed(runif(10))
batch4 <- rnorm(5)
# Combining the batches produces the same result
# therefore `with_local_seed` did not interrupt the rng sequence
identical(c(batch1, batch2, batch3, batch4), res)
# It can be useful in multiple comparisons
out1 <- with_local_seed(rnorm(5))
out2 <- with_local_seed(rnorm(5))
out3 <- with_local_seed(rnorm(5))
identical(out1, out2)
identical(out1, out3)
Run the code above in your browser using DataLab