Cumulative Harmonic Mean with {TidyDensity}

code
rtip
tidydensity
Author

Steven P. Sanderson II, MPH

Published

November 16, 2022

Introduction

There can be times in which you may want to see a cumulative statistic, maybe in this particular case it is the harmonic mean. Well with the {TidyDensity} it is possible with a function called chmean()

Let’s take a look at the function.

Function

Here is the function call, it is very simple as it is a vectorized function.

chmean(.x)

The only argument you provide to this function is a numeric vector. Let’s take a quick look at the construction of the function.

chmean <- function(.x) {
  1 / (cumsum(1 / .x))
}

Examples

Let’s take a look at an example.

library(TidyDensity)
library(dplyr)

x <- mtcars$mpg

chmean(x)
 [1] 21.0000000 10.5000000  7.1891892  5.3813575  4.1788087  3.3949947
 [7]  2.7436247  2.4663044  2.2255626  1.9943841  1.7934398  1.6166494
[13]  1.4784877  1.3474251  1.1928760  1.0701322  0.9975150  0.9677213
[19]  0.9378663  0.9126181  0.8754572  0.8286539  0.7858140  0.7419753
[25]  0.7143688  0.6961523  0.6779989  0.6632076  0.6364908  0.6165699
[31]  0.5922267  0.5762786
mtcars %>%
  select(mpg) %>%
  mutate(cum_har_mean = chmean(mpg)) %>%
  head(10)
                   mpg cum_har_mean
Mazda RX4         21.0    21.000000
Mazda RX4 Wag     21.0    10.500000
Datsun 710        22.8     7.189189
Hornet 4 Drive    21.4     5.381358
Hornet Sportabout 18.7     4.178809
Valiant           18.1     3.394995
Duster 360        14.3     2.743625
Merc 240D         24.4     2.466304
Merc 230          22.8     2.225563
Merc 280          19.2     1.994384

Voila!