[R-sig-eco] Two-Dimenstional Kolmogorov-Smirnov Test

Ben Bolker bbolker at gmail.com
Sat Jul 17 16:06:46 CEST 2010


Derek Ogle <DOgle at ...> writes:

> 
> Has anyone seen an R function or code to perform the Two-Dimenstional
Kolmogorov-Smirnov (2DKS) test
> described in this reference ...
> 
> James E. Garvey, Elizabeth A. Marschall, Russell A. Wright (1998) FROM STAR
CHARTS TO STONEFLIES:
> DETECTING RELATIONSHIPS IN CONTINUOUS BIVARIATE DATA. Ecology: Vol. 79, No. 2,
pp. 442-447.
> 

  
  It wouldn't be that hard to implement in R -- here's a start.


x1 <- runif(100)
y1 <- runif(100)
x2 <- runif(100)
y2 <- runif(100)

x0 <- x1[1]
y0 <- y1[1]

## compute densities in each quadrat around (x0,y0) and
## find the difference
quad_dens <- function(x0,y0,x,y) {
  (table(factor(sign(x-x0),levels=-1:1),
        factor(sign(y-y0),levels=-1:1))[c(1,3),c(1,3)])/length(x)
}

diff1 <- apply(cbind(x1,y1),1,
      function(z) {
        q1 <- quad_dens(z[1],z[2],x1,y1)
        q2 <- quad_dens(z[1],z[2],x2,y2)
        q1 - q2
      })


diff2 <- apply(cbind(x2,y2),1,
      function(z) {
        q1 <- quad_dens(z[1],z[2],x1,y1)
        q2 <- quad_dens(z[1],z[2],x2,y2)
        q1 - q2
      })

(max(abs(diff1))+max(abs(diff2)))/2

   The next challenge is to dig out the KS statistic -- it's
computed in C code which is called from inside ks.test ...

  Ben Bolker



More information about the R-sig-ecology mailing list