Skip to content
Related Articles

Related Articles

Compute Harmonic Mean of Vector in R

View Discussion
Improve Article
Save Article
  • Last Updated : 02 Jun, 2022

In this article, we will see how to find the harmonic mean of the vector in R Programming Language.

The harmonic mean is used when an average of rates is required, below is the formula. 

Harmonic mean of n numbers x1, x2, x3, . . ., xn can written as below.

Harmonic mean = n / ((1/x1) + (1/x2) + (1/x3) + . . . + (1/xn))

In R, we can compute the harmonic mean by using harmonic.mean() function.

Syntax: harmonic.mean(vector)

where, vector is an input vector.

But this method is available in psych package. so we have to install and import it.

Install - install.packages("psych")              
Import - library("psych")   

Example 1:

In this example, we are going to find the harmonic mean of a vector with 4 elements.

R




# load the library
library("psych")  
  
# create vector
vector1=c(2,3,4,5)
  
# harmonic mean
print(harmonic.mean(vector1))


Output:

[1] 3.116883

Example 2:

In this example, we are going to find the harmonic mean of a vector with 10 elements.

R




# load the library
library("psych")  
  
# create vector
vector1=c(12:21)
  
# harmonic mean
print(harmonic.mean(vector1))


Output:

[1] 15.98769
My Personal Notes arrow_drop_up
Recommended Articles
Page :

Start Your Coding Journey Now!