R/rand_vect.R

Defines functions rand_vect

Documented in rand_vect

#' Internal to simulate_non_independence
#'
#' Generates multinomial draws for group-switching
#'
#' @keywords internal
rand_vect <- function(N, M, sd = 1, pos.only = TRUE) {
  vec <- stats::rnorm(N, M/N, sd)
  if (abs(sum(vec)) < 0.01) vec <- vec + 1
  vec <- round(vec / sum(vec) * M)
  deviation <- M - sum(vec)
  for (. in seq_len(abs(deviation))) {
    vec[i] <- vec[i <- sample(N, 1)] + sign(deviation)
  }
  if (pos.only) while (any(vec < 0)) {
    negs <- vec < 0
    pos  <- vec > 0
    vec[negs][i] <- vec[negs][i <- sample(sum(negs), 1)] + 1
    vec[pos][i]  <- vec[pos ][i <- sample(sum(pos ), 1)] - 1
  }
  vec
}
gavincotterill/modulr documentation built on Nov. 30, 2022, 11:15 p.m.