How to Calculate Geometric Mean in R (With Examples)


You can use the following syntax to calculate the geometric mean of a set of numbers in R:

exp(mean(log(x)))

The following examples show how to use this function in practice.

Example 1: Calculate Geometric Mean of Vector

The following code shows how to calculate the geometric mean for a single vector in R:

#define vector
x <- c(4, 8, 9, 9, 12, 14, 17)

#calculate geometric mean of values in vector
exp(mean(log(x)))

[1] 9.579479

Example 2: Calculate Geometric Mean of Vector with Zeros

If your vector contains zeros or negative numbers, the formula above will return a 0 or a NaN.

To ignore zeros and negative numbers when calculating the geometric mean, you can use the following formula:

#define vector with some zeros and negative numbers
x <- c(4, 8, 9, 9, 12, 14, 17, 0, -4)

#calculate geometric mean of values in vector
exp(mean(log(x[x>0])))

[1] 9.579479

Example 3: Calculate Geometric Mean of Columns in Data Frame

The following code shows how to calculate the geometric mean of a column in a data frame:

#define data frame
df <- data.frame(a=c(1, 3, 4, 6, 8, 8, 9),
                 b=c(7, 8, 8, 7, 13, 14, 16),
                 c=c(11, 13, 13, 18, 19, 19, 22),
                 d=c(4, 8, 9, 9, 12, 14, 17))

#calculate geometric mean of values in column 'a'
exp(mean(log(df$a)))

[1] 4.567508

And the following code shows how to calculate the geometric mean of multiple columns in a data frame:

#define data frame
df <- data.frame(a=c(1, 3, 4, 6, 8, 8, 9),
                 b=c(7, 8, 8, 7, 13, 14, 16),
                 c=c(11, 13, 13, 18, 19, 19, 22),
                 d=c(4, 8, 9, 9, 12, 14, 17))

#calculate geometric mean of values in column 'a', 'b', and 'd'
apply(df[ , c('a', 'b', 'd')], 2, function(x) exp(mean(log(x))))

       a        b        d 
4.567508 9.871128 9.579479 

Additional Resources

How to Calculate the Mean by Group in R
How to Calculate a Weighted Mean in R
How to Calculate Standard Error of Mean in R

Leave a Reply

Your email address will not be published.