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.

gm_mean(x, na.rm = FALSE, zero.propagate = FALSE)

Arguments

x

A numeric (or coercible-to-numeric) vector.

na.rm

Logical; if TRUE, remove NA values before computation. If FALSE and any NA is present, returns NA_real_. Default is FALSE.

zero.propagate

Logical; if TRUE, return 0 when any value in x is exactly zero (after NA handling). If FALSE, zeros are ignored and only positive values contribute. Default is FALSE.

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))
#> Error in gm_mean(c(1, 4, 16)): could not find function "gm_mean"

gm_mean(c(1, NA, 4)) # Returns NA
#> Error in gm_mean(c(1, NA, 4)): could not find function "gm_mean"
gm_mean(c(1, NA, 4), na.rm = TRUE)
#> Error in gm_mean(c(1, NA, 4), na.rm = TRUE): could not find function "gm_mean"

gm_mean(c(0, 1, 4)) # zeros ignored by default
#> Error in gm_mean(c(0, 1, 4)): could not find function "gm_mean"
gm_mean(c(0, 1, 4), zero.propagate = TRUE)  # returns 0
#> Error in gm_mean(c(0, 1, 4), zero.propagate = TRUE): could not find function "gm_mean"

gm_mean(c(-1, 1, 4)) # negatives not allowed -> NaN
#> Error in gm_mean(c(-1, 1, 4)): could not find function "gm_mean"
gm_mean(c(0, 0)) # no positive values -> NaN
#> Error in gm_mean(c(0, 0)): could not find function "gm_mean"