Computes the geometric mean of the positive values in x.
Negative values are not allowed: if any negative value is present (ignoring
NAs), the function returns NaN.
Arguments
- x
A numeric (or coercible-to-numeric) vector.
- na.rm
Logical; if
TRUE, removeNAvalues before computation. IfFALSEand anyNAis present, returnsNA_real_. Default isFALSE.- zero.propagate
Logical; if
TRUE, return0when any value inxis exactly zero (after NA handling). IfFALSE, zeros are ignored and only positive values contribute. Default isFALSE.
Details
By default, if na.rm = FALSE and any NA is present, the function
returns NA_real_. If na.rm = TRUE, NAs are removed before
computation.
Zeros are excluded from the mean calculation unless zero.propagate = TRUE,
in which case the function returns 0 if any zero is present (after NA
handling).
If, after filtering, there are no positive values to average (e.g., x
contains only 0s and/or NAs), the function returns NaN.
Examples
gm_mean(c(1, 4, 16))
#> [1] 4
gm_mean(c(1, NA, 4)) # Returns NA
#> [1] NA
gm_mean(c(1, NA, 4), na.rm = TRUE)
#> [1] 2
gm_mean(c(0, 1, 4)) # zeros ignored by default
#> [1] 2
gm_mean(c(0, 1, 4), zero.propagate = TRUE) # returns 0
#> [1] 0
gm_mean(c(-1, 1, 4)) # negatives not allowed -> NaN
#> [1] NaN
gm_mean(c(0, 0)) # no positive values -> NaN
#> [1] NaN