rnorm_truncated: Random draw from a truncated normal distribution

View source: R/math.R

rnorm_truncatedR Documentation

Random draw from a truncated normal distribution

Description

rnorm_truncated generates random numbers from a normal distribution using rnorm(), but forced to remain within the specified low/high bounds. All proposals outside the boundaries (exclusive) are discarded, and the sampling is repeated until there are enough values within the specified range. Fully vectorized.

Usage

rnorm_truncated(
  n = 1,
  mean = 0,
  sd = 1,
  low = NULL,
  high = NULL,
  roundToInteger = FALSE,
  invalidArgAction = c("adjust", "abort", "ignore")[1]
)

Arguments

n

the number of values to return

mean

the mean of the normal distribution from which values are generated (vector of length 1 or n)

sd

the standard deviation of the normal distribution from which values are generated (vector of length 1 or n)

low, high

exclusive lower and upper bounds ((vectors of length 1 or n))

roundToInteger

boolean vector of length 1 or n. If TRUE, the corresponding value is rounded to the nearest integer.

invalidArgAction

what to do if an argument is invalid or outside the range in permittedValues: 'adjust' = reset to default value, 'abort' = stop execution, 'ignore' = throw a warning and continue (may crash)

Value

A vector of length n.

Examples

soundgen:::rnorm_truncated(n = 3, mean = 10, sd = 5, low = 7, high = NULL,
  roundToInteger = c(TRUE, FALSE, FALSE))
soundgen:::rnorm_truncated(n = 9, mean = c(10, 50, 100), sd = c(5, 0, 20),
  roundToInteger = TRUE) # vectorized
# in case of conflicts between mean and bounds, either adjust the mean:
soundgen:::rnorm_truncated(n = 3, mean = 10, sd = .1,
  low = c(15, 0, 0), high = c(100, 100, 8), invalidArgAction = 'adjust')
#... or ignore the boundaries
soundgen:::rnorm_truncated(n = 3, mean = 10, sd = .1,
  low = c(15, 0, 0), high = c(100, 100, 8), invalidArgAction = 'ignore')

soundgen documentation built on Sept. 12, 2024, 6:29 a.m.