Calculate Geometric Mean in R

[This article was first published on Methods – finnstats, 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.

Calculate Geometric Mean in R, Geometric mean is the nth root of the product of n values of a set of observations.

Geometric can be expressed as

GM=(x1, x2, x3, ……, xn)1/n

The advantage of the geometric mean is

  • It is least affected by extreme values
  • It is based on all observations of the set
  • It is suitable for further algebraic treatment.

The disadvantageous of the geometric mean is

  • Calculation is complicated
  • Cannot be calculated if a set of value contains zero If any one or more values are negative, either geometric mean will not be calculated or an absurd value will be obtained.

Decision Trees in R » Classification & Regression »

Calculate Geometric Mean in R

The syntax is as follows,

exp(mean(log(x)))

Approach 1: GM of Vector

Let’s create a vector for geometric mean calculation.

data <- c(1, 15, 12, 5, 18, 11, 12, 15, 18, 25)
exp(mean(log(data)))
10.37383

Log Rank Test in R-Survival Curve Comparison »

Approach 2: GM Vector with Zeros

As mentioned earlier if a set of values contains zero cannot be executed a geometric mean, However, we can ignore zero values and execute GM.

data <- c(1, 15, 12, 5, 0, 18, 11, 12, 15, 18, 25, 0, -11)

The above data set included negative values and zero.

Let’s make use of the below code for GM calculation.

exp(mean(log(data[data>0])))
10.37383

Kruskal Wallis test in R-One-way ANOVA Alternative »

Approach 3: GM Data Frame

Let’s create a data frame for geometric mean calculation.

data<- data.frame(x=c(10, 13, 14, 26, 38, 28, 29),
                 y=c(15, 8, 18, 17, 1, 1, 6),
                 z=c(12, 10, 18, 28, 29, 29, 12))

Calculate the geometric mean for x, y, and z.

apply(data[ , c('x', 'y', 'z')], 2, function(x) exp(mean(log(x))))
    x         y         z
20.379699  5.798203 17.992195

Conclusion

Geometric Mean is considered the most suitable average for index numbers.

Principal component analysis (PCA) in R »

Subscribe to the Newsletter and COMMENT below!

The post Calculate Geometric Mean in R appeared first on finnstats.

To leave a comment for the author, please follow the link and comment on their blog: Methods – finnstats.

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)