R/random.R

Defines functions which.weight localRNG

Documented in which.weight

localRNG = function(seed = NULL, expr) {
  if (is.null(seed)) {
    force(expr)
    return(invisible())
  } else {
    if (exists('.Random.seed')) {
      prevSeed = .Random.seed
      set.seed(seed)
      force(expr)
      .Random.seed = prevSeed
    }
    else {
      # nocov start
      set.seed(seed)
      force(expr)
      # nocov end
    }
  }
}

#' @export
#' @title Sample an index of a vector weighted by the elements
#' @description Returns a random index, weighted by the element magnitudes. This function is intended to be used as an optional strategy for [trajectoryAssignments], resulting in randomly sampled cluster membership.
#' @param x A positive `numeric vector`.
#' @return An `integer` giving the index of the sampled element.
#' @examples
#' x = c(.01, .69, .3)
#' which.weight(x) #1, 2, or 3
which.weight = function(x) {
  sample.int(length(x), size = 1, prob = x)
}

Try the latrend package in your browser

Any scripts or data that you put into this service are public.

latrend documentation built on March 31, 2023, 5:45 p.m.