r - Logarithmic mean of vector -
to follow exact methodology presented in article calculate logarithmic mean of data vector. did not find functions in r, or previous discussions. case 2 numbers clear, not work out efficient method calculate log mean large vector of numbers. suggestions?
# calculating different types of means # data dat <- c(0.008845299, 0.040554701) # arithmetic mean arith.m <- mean(dat) # logarithmic mean # http://en.wikipedia.org/wiki/logarithmic_mean log.m <- (dat[1] - dat[2])/(log(dat[1])-log(dat[2])) # geometric mean # http://stackoverflow.com/questions/2602583/geometric-mean-is-there-a-built-in geo_mean <- function(data) { log_data <- log(data) gm <- exp(mean(log_data[is.finite(log_data)])) return(gm) } geo.m <- geo_mean(dat) # show arithmetic > logarithmic > geometric arith.m; log.m; geo.m # how calculate logarithmic mean vector? dat.n <- c(0.008845299, 0.040554701, 0.047645299, 0.036654701, 0.017345299, 0.018754701, 0.032954701, 0.043145299, 0.026845299, 0.033054701, 0.025554701) update calculation strips out 0 values (but, pointed out below valid?):
# add low number (generally considered 0 in r) nzero <- 1.940656e-324 dat.n <- c(dat.n, nzero) # arithmetic mean arith.m <- mean(dat.n) geo_mean <- function(data) { log_data <- log(data) gm <- exp(mean(log_data[is.finite(log_data)])) return(gm) } geo.m <- geo_mean(dat.n) lmv <- function(x){ ddlog <- function(x){ d <- rep(0, length(x)) (i in 1:length(x)){ d[i] <- prod(x[i] - x[-i]) } sum(log(x)[is.finite(log(x))]/d[is.finite(log(x))]) } n <- length(x[which(x>0)]) - 1 ((-1)^(n+1)*n*ddlog(x))^(-1/n) } log.m <- lmv(dat.n) # show arithmetic > logarithmic > geometric arith.m; log.m; geo.m
followed wiki (generalized (n+1) values):
http://en.wikipedia.org/wiki/divided_difference#expanded_form
http://en.wikipedia.org/wiki/logarithmic_mean#mean_value_theorem_of_differential_calculus_2
ddlog <- function(x){ d <- rep(0, length(x)) (i in 1:length(x)){ d[i] <- prod(x[i] - x[-i]) } sum(log(x)/d) } # ddlog divided difference of logarithm. lmv <- function(x){ n <- length(x) - 1 ((-1)^(n+1)*n*ddlog(x))^(-1/n) } r > <- c(0.008845299, 0.040554701, 0.047645299, 0.036654701, 0.017345299, 0.018754701, 0.032954701, 0.043145299, 0.026845299, 0.033054701, 0.025554701) r > r > lmv(a) [1] 0.0277
Comments
Post a Comment