[R] geometric mean to handle large number and negative values

Daren Tan darentan76 at gmail.com
Wed Apr 15 10:48:40 CEST 2009


I have created two functions to compute geometric means. Method 1 can
handle even number of negative values but not large number, vice versa
for method 2. How can I merge both functions so that both large number
and negative values can be handled ?

> geometric.mean1 <- function(x) prod(x)^(1/length(x))
> geometric.mean2 <- function(x) exp(mean(log(x)))

> geometric.mean1(1:10000000)
[1] Inf
> geometric.mean2(1:10000000)
[1] 3678798

> geometric.mean1(c(-5,-4,4,5))
[1] 4.472136
> geometric.mean2(c(-5,-4,4,5))
[1] NaN
Warning message:
In log(x) : NaNs produced




More information about the R-help mailing list