Normalizes a numeric vector to sum to 1, creating a valid probability
distribution.
Usage
normalize_prob(x, na.rm = FALSE)
Arguments
- x
Numeric vector (non-negative values expected)
- na.rm
Logical; remove NA values before normalizing?
Value
Numeric vector summing to 1 (or containing NAs if input had NAs
and na.rm = FALSE)
Details
If all values are zero or if sum is zero, returns uniform distribution.
Negative values are set to zero with a warning.
Examples
normalize_prob(c(1, 2, 3, 4))
#> [1] 0.1 0.2 0.3 0.4
normalize_prob(c(10, 20, 30))
#> [1] 0.1666667 0.3333333 0.5000000
normalize_prob(c(0, 0, 0)) # Returns uniform
#> [1] 0.3333333 0.3333333 0.3333333