Reputation:
Is there a way to calculate a weighted geometric average in R?
I know rogiersbart/rtoolz has an extension to the package Devtools, so you can use the function:
weighted.geomean(x, w, ...)
Unfortunately, I cannot use this extension. So is there an other way to calculate a weighted geometric average in R? Maybe manually?
Upvotes: 1
Views: 2458
Reputation: 7941
The Github that you refer to has the source code that is used in that function, so you can easily reuse it in your code. For completeness, the author defines weighted.geomean
as:
weighted.geomean <- function(x, w, ...)
{
return(prod(x^w, ...)^(1/sum(w)))
}
An alternative, mathematically equivalent version would be:
weighted.geomean <- function(x, w, ...) exp(weighted.mean(log(x), w, ...))
Once you've run either of the blocks above, you've now defined a function that calculates the weighted mean. You can use this for example data by running the commands
myvariable <- c(1,2,3,4) ##Some data to average
myweight <- c(1,1,1,3) ##Weights
weighted.geomean(myvariable, myweight)
# [1] 2.696012
Upvotes: 5