Is there a function or an easier way to computer geometric means of each rows in a nxn matrix and spit out in an 1xn matrix ? -- Edward Chen [[alternative HTML version deleted]]
set.seed(1) x <- matrix(runif(1000), 100) system.time(tmp1 <- exp(rowMeans(log(x)))) system.time(tmp2 <- apply(x, 1, function(y) prod(y)^(1/length(y)))) all.equal(tmp1, tmp2) ## tmp1 is more robust, btw On Aug 20, 2009, at 3:22 PM, Edward Chen wrote:> Is there a function or an easier way to computer geometric means of > each > rows in a nxn matrix and spit out in an 1xn matrix ? > > -- > Edward Chen > > [[alternative HTML version deleted]] > > ______________________________________________ > R-help at r-project.org mailing list > https://stat.ethz.ch/mailman/listinfo/r-help > PLEASE do read the posting guide http://www.R-project.org/posting-guide.html > and provide commented, minimal, self-contained, reproducible code.
On Aug 20, 2009, at 2:22 PM, Edward Chen wrote:> Is there a function or an easier way to computer geometric means of > each > rows in a nxn matrix and spit out in an 1xn matrix ?> xx <- matrix(10+rnorm(100), 10) > apply(xx, 1, function(x) exp(mean(log(x))) ) [1] 10.084711 10.034054 9.622909 9.780703 10.085467 9.800346 10.283556 9.666453 9.802996 [10] 9.917821 This of course will return NaN if there are any negative values. There are also several implementations of geometric mean functions that can be found with the obvious search strategy at: http://search.r-project.org/nmz.html -- David Winsemius, MD Heritage Laboratories West Hartford, CT