geomean: Weighted geometric/harmonic mean

Description Usage Arguments Details Value See Also Examples

Description

Calculate a weighted geometric or harmonic mean.

Usage

1
2
3
geomean(x, w, na.rm = FALSE)

harmean(x, w, na.rm = FALSE)

Arguments

x

A numeric vector.

w

An optional vector of (numeric) weights, the same length as x.

na.rm

Should missing values be removed?

Details

The underlying calculation is done with weighted.mean. This means that weights are handled in the same way as weighted.mean.

The implementation and performance is similar to the geometric.mean and harmonic.mean functions in the psych package, and the geoMean function in the EnvStats package, with the exception that weights are allowed.

Value

A numeric value.

See Also

See generalized_mean for making other types of generalized means.

Examples

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
# Geometric mean
geomean(2:3)

# Same as manual calculation
sqrt(6)

# Using prod to calculate geomean manually can give misleading results
prod(1:1000)^(1/1000)
geomean(1:1000)

# Geomean is usually faster anyways
x <- runif(1000000)
system.time(geomean(x))
system.time(prod(x^(1/length(x))))

# Harmonic mean
harmean(2:3)

# Same as manual calculation
(sum((2:3)^(-1)) / 2)^(-1)

marberts/ppd documentation built on March 27, 2020, 7:21 p.m.