[R] Fast R implementation of Gini mean difference
Andrew C. Ward
s195404 at student.uq.edu.au
Thu Apr 24 05:17:57 CEST 2003
I have written the following function to calculate the weighted mean
difference for univariate data (see
http://www.xycoon.com/gini_mean_difference.htm for a related
formula). Unsurprisingly, the function is slow (compared to sd or mad)
for long vectors. I wonder if there's a way to make the function
faster, short of creating an external C function. Thanks very much
for your advice.
gmd <- function(x, w) { # x=data vector, w=weights vector
n <- length(x)
tmp <- 0
for (i in 1:n) {
for (j in 1:n) {
tmp <- tmp + w[i]*abs(x[i]-x[j])
}
}
retval <- 0.5*sqrt(pi)*tmp/((n-1)*sum(w))
}
gmd(rnorm(100))
Regards,
Andrew C. Ward
CAPE Centre
Department of Chemical Engineering
The University of Queensland
Brisbane Qld 4072 Australia
andreww at cheque.uq.edu.au
More information about the R-help
mailing list