Andrew,

being a novice when it comes to R programming, I was not aware of how to use 
"outer".  I looked at the possibility of just eliminating the inner loop of 
your function.  I compared your original function, gmd, with the version 
submitted by Deepayan Sarkar , which I called gmd.1, and my version 
eliminating the inner loop, gmd.2.  (See below)

The timings suggest that gmd.2 may be a little faster than gmd.1, and the 
memory utilization may be better (I am not exactly sure how to compare the 
memory footprints).  I did try running my version on a vector of 
length=10,000 and it ran in about 10 seconds on a 1.4MHz Pentium IV with 256k 
of RAM.

I hope this may be of some help; I know I learned while looking at this 
problem.

Dan Nordlund



## original Gini-mean-difference function 
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))
}

## function using outer as per Deepayan Sarkar
gmd.1 <- 
   function(x, w) 0.5 * sqrt(pi) * sum(w * abs(outer(x, x, "-"))) /
       ((length(x)-1)*sum(w))

## function eliminating only the inner loop
gmd.2 <- function(x, w) { # x=data vector, w=weights vector
   n <- length(x)
   tmp <- 0
   for (i in 1:n) tmp <- tmp + sum(w[i]*abs(x[i]-x))
   retval <- 0.5*sqrt(pi)*tmp/((n-1)*sum(w))
}

##results of running the three functions on vector of length=1000
>w<-runif(1000)
>z<-rnorm(1000)

> system.time(gmd(z, w))
[1] 18.48  0.26 19.41    NA    NA

> system.time(gmd.1(z, w))
[1] 0.97 0.02 1.01   NA   NA

> system.time(gmd.2(z, w))
[1] 0.14 0.00 0.15   NA   NA
>

	[[alternate HTML version deleted]]

