15.1 C
London
Friday, July 5, 2024
HomeRDescriptive Statistics in RHow to Calculate Geometric Mean in R (With Examples)

How to Calculate Geometric Mean in R (With Examples)

Related stories

Learn About Opening an Automobile Repair Shop in India

Starting a car repair shop is quite a good...

Unlocking the Power: Embracing the Benefits of Tax-Free Investing

  Unlocking the Power: Embracing the Benefits of Tax-Free Investing For...

Income Splitting in Canada for 2023

  Income Splitting in Canada for 2023 The federal government’s expanded...

Can I Deduct Home Office Expenses on my Tax Return 2023?

Can I Deduct Home Office Expenses on my Tax...

Canadian Tax – Personal Tax Deadline 2022

  Canadian Tax – Personal Tax Deadline 2022 Resources and Tools...

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 #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 #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 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 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

Subscribe

- Never miss a story with notifications

- Gain full access to our premium content

- Browse free from up to 5 devices at once

Latest stories