Computes arithmetic means (or other averages) with minimal requirements for valid values or maximum allowed NAs.

average(x, min_valid, max_na, func = mean)

Arguments

x

Vector of numeric values.

min_valid

Minimal number of valid values that is required for calculating the mean. A value between 0 and 1 indicates a proportion of values (e.g., 0.5 = 50 percent of values have to be valid).

max_na

Maximum number of NAs that are allowed before returning NA. A value between 0 and 1 indicates a proportion of values (e.g., 0.5 = 50 percent NAs are allowed).

func

A function for calculating the average. Default is mean().

Value

A numeric value representing the average, or NA if the conditions are not met.

Details

If the number of valid values is below min_valid or the number of NAs is above max_na, the function returns NA. Otherwise, it computes the average using the specified function func.

If both min_valid and max_na are provided, both conditions have to be met for the calculation to proceed. Missing values (NAs) are ignored in the calculation of the average. If the conditions for min_valid or max_na are not met, NA is returned.

Author

Juergen Wilbert

Examples

dat <- c(1:5, NA, NA)
average(dat, min_valid = 5)
#> [1] 3
average(dat, min_valid = 6)
#> [1] NA
average(dat, max_na = 2)
#> [1] 3
average(dat, max_na = 1)
#> [1] NA
average(dat, min_valid = 0.5, func = median)
#> [1] 3
average(dat, min_valid = 0.9)
#> [1] NA