Geometric Mean: is there a built-in?

前端 未结 9 1713
走了就别回头了
走了就别回头了 2020-11-28 20:45

I tried to find a built-in for geometric mean but couldn\'t.

(Obviously a built-in isn\'t going to save me any time while working in the shell, nor do I suspect ther

相关标签:
9条回答
  • 2020-11-28 21:16

    The

    exp(mean(log(x)))
    

    will work unless there is a 0 in x. If so, the log will produce -Inf (-Infinite) which always results in a geometric mean of 0.

    One solution is to remove the -Inf value before calculating the mean:

    geo_mean <- function(data) {
        log_data <- log(data)
        gm <- exp(mean(log_data[is.finite(log_data)]))
        return(gm)
    }
    

    You can use a one-liner to do this but it means calculating the log twice which is inefficient.

    exp(mean(log(i[is.finite(log(i))])))
    
    0 讨论(0)
  • 2020-11-28 21:17

    We can use psych package and call geometric.mean function.

    0 讨论(0)
  • 2020-11-28 21:25

    No, but there are a few people who have written one, such as here.

    Another possibility is to use this:

    exp(mean(log(x)))
    
    0 讨论(0)
提交回复
热议问题