# 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)) %>%
``````                   mpg cum_har_mean