R/set_init_seed.R

Defines functions set_init_seed

Documented in set_init_seed

# ---------------------------------------------------------------------------- #
#' Set RNG seed
#'
#' Sets the RNG (random number generator) seed.
#'
#' @param seed_val One of the following:\itemize{
#'   \item{A single value (which can be interpreted as an integer) to set the
#'   RNG;}
#'   \item{The character literal "random" (to set a random seed);}
#'   \item{\code{NULL}, to re-initialize the RNG as if no seed had yet been set
#'   (see 'Details' in \code{\link{set.seed}}); or}
#'   \item{\code{NA}, in which case the function will return without any change
#'   to the seed.}
#'   }
#'
#' @return The value of \code{seed_val} (either user-supplied or set from
#'   within the function), invisibly.
#'
#' @keywords random seed, RNG
#' @seealso \code{\link{set.seed}}, \code{\link{get_random_seed_val}}
#'
#' @examples
#' \dontrun{
#' set_init_seed(1) # => Set seed to a specific value
#' set_init_seed("random") # => Set seed to a randomly-generated value
#' set_init_seed(NULL) # => Re-initialize seed as if none had yet been set
#' set_init_seed(NA) # => Return immediately without changing seed
#' }
#'
#' @export
#'
set_init_seed <- function(seed_val) {

  is_null_or_na <- function(x) is.null(x) || test_scalar_na(x)

  is_valid_seed <- function(x) {
    is_null_or_na(x) || x == "random" || test_integerish(x)
  }

  if (length(seed_val) > 1 || !is_valid_seed(seed_val)) {
    cli_abort(c(
      paste(
        "{.var seed_val} must be NULL, NA, the keyword 'random' or a",
        "single value interpretable as an integer"
      ),
      "x" = "You've supplied '{style_cli_vec(seed_val)}'."
    ),
    class = "jute_error"
    )
  }

  if (!is.null(seed_val) && is.na(seed_val)) {
    # requested seed is NA; return without setting seed
    return(invisible(NULL))
  }

  if (identical(seed_val, "random")) {
    seed_val <- get_random_seed_val()
  }

  # If seed_val is NULL, RNG seed will be re-initialized (i.e. set to NULL);
  # otherwise it will be set to the value of seed_val
  set.seed(seed_val)

  invisible(seed_val)
}

# ---------------------------------------------------------------------------- #
toniprice/jute documentation built on Jan. 11, 2023, 8:23 a.m.