calculate harmonic mean in r

To calculate the harmonic mean in R, you can use the mean() function with the argument 1/x to invert each element of your vector x, then calculate the mean of these inverted values.

Here is an example code:

main.r
# Example vector
x <- c(2, 3, 4, 5, 6)

# Calculation of harmonic mean
harmonic_mean <- mean(1/x)

# Printing the result
harmonic_mean
135 chars
9 lines

The output should be:

main.r
[1] 3.207547
13 chars
2 lines

Note that the harmonic mean is often used for calculating the average rate or speed in situations where different rates are being combined.

gistlibby LogSnag