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

Richard.Cotton at hsl.gov.uk Richard.Cotton at hsl.gov.uk
Wed Apr 15 11:26:55 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

Geometric mean is usually restricted to positive inputs, because otherwise 
the answer can have an imaginary component.  If you really want the 
geometric mean of negative inputs, use the second method but convert the 
input to be a complex number first.

comp.x <- as.complex(c(-5,-4,4,5))
geometric.mean2(comp.x)
# [1] 0+4.472136i

Regards,
Richie.

Mathematical Sciences Unit
HSL


------------------------------------------------------------------------
ATTENTION:

This message contains privileged and confidential inform...{{dropped:20}}




More information about the R-help mailing list