Geometric and harmonic means in R

[This article was first published on Statistic on aiR, and kindly contributed to R-bloggers]. (You can report issue about the content on this page here)
Want to share your content on R-bloggers? click here if you have a blog, or here if you don't.

Compute the geometric mean and harmonic mean in R of this sequence.

10, 2, 19, 24, 6, 23, 47, 24, 54, 77

These features are not present in the standard package of R, although they are easily available in some packets.
However, it is easy to calculate these values simply by remembering the mathematical formulas, and applying them in R.

$$H = \frac{n}{\frac{1}{x_1} + \frac{1}{x_2} + \cdots + \frac{1}{x_n}} = \frac{n}{\sum_{i=1}^n \frac{1}{x_i}}, \qquad x_i > 0 \text{ for all } i.$$

In R language:


a = c(10, 2, 19, 24, 6, 23, 47, 24, 54, 77)

1/mean(1/a) #compute the harmonic mean
[1] 10.01109

$$\overline{a}_{geom}=\bigg(\prod_{i=1}^n a_i \bigg)^{1/n} = \sqrt[n]{a_1 \cdot a_2 \cdots a_n}$$

In R language


a = c(10, 2, 19, 24, 6, 23, 47, 24, 54, 77)

n = length(a) #now n is equal to the number of elements in a

prod(a)^(1/n) #compute the geometric mean
[1] 18.92809

To leave a comment for the author, please follow the link and comment on their blog: Statistic on aiR.

R-bloggers.com offers daily e-mail updates about R news and tutorials about learning R and many other topics. Click here if you're looking to post or find an R/data-science job.
Want to share your content on R-bloggers? click here if you have a blog, or here if you don't.

Never miss an update!
Subscribe to R-bloggers to receive
e-mails with the latest R posts.
(You will not see this message again.)

Click here to close (This popup will not appear again)