forestgeo / learn

Links to interesting articles, videos, tutorials, tips, and more
5 stars 8 forks source link

Setting a new seed inside a function and restoring it at the end #117

Open maurolepore opened 6 years ago

maurolepore commented 6 years ago
consistent_kmeans <- function(x, centers) {
  # Show original seed
  cat(head(.Random.seed), "\n")

  # Store original seed to restore it later
  original_seed <- get(".Random.seed", .GlobalEnv)

  # Set a new seed for consistent output of kmeans()
  set.seed(1)

  out <- stats::kmeans(x, centers)$cluster

  # Restore original seed
  assign(".Randon.seed", original_seed, .GlobalEnv)
  # Show to confirm that it is the original seed
  cat(head(.Random.seed), "\n")

  out
}

consistent_kmeans(1:4, 2)
#> 403 10 -632390908 227133511 -1818534115 3425684 
#> 403 2 1654269195 -1877109783 -961256264 1403523942 
#> [1] 1 1 2 2
consistent_kmeans(1:4, 2)
#> 403 2 1654269195 -1877109783 -961256264 1403523942 
#> 403 2 1654269195 -1877109783 -961256264 1403523942 
#> [1] 1 1 2 2
consistent_kmeans(1:4, 2)
# 403 2 1654269195 -1877109783 -961256264 1403523942 
# 403 2 1654269195 -1877109783 -961256264 1403523942 
# [1] 1 1 2 2
consistent_kmeans(1:4, 2)
#> 403 2 1654269195 -1877109783 -961256264 1403523942 
#> 403 2 1654269195 -1877109783 -961256264 1403523942 
#> [1] 1 1 2 2
consistent_kmeans(1:4, 2)
#> 403 2 1654269195 -1877109783 -961256264 1403523942 
#> 403 2 1654269195 -1877109783 -961256264 1403523942 
#> [1] 1 1 2 2
maurolepore commented 6 years ago

The real implemetation looks like this:

consistent_kmeans <- function(x, centers) {
  old_seed <- get(".Random.seed", .GlobalEnv)
  on.exit(assign(".Randon.seed", old_seed, .GlobalEnv))
  set.seed(1)

 ...
}