It does not appear you can extract such a location (which might not be unique, BTW) from the output of ks.test
, but by emulating the key calculation there you can obtain the answer:
compare <- function(x, y) {
n <- length(x); m <- length(y)
w <- c(x, y)
o <- order(w)
z <- cumsum(ifelse(o <= n, m, -n))
i <- which.max(abs(z))
w[o[i]]
}
The calculation through z <- ...
is from the ks.test
source, while the last two lines (fairly clearly) find the location where the maximum deviation is attained.
As an example, let's generate two datasets and compare them:
set.seed(17)
x <- rnorm(30)
y <- rnorm(20, sd=2/3)
u <- compare(x,y)
The reported value of u
is 0.04946235
. To see whether this is correct, check it against the ECDFs and the output of ks.test
:
e.x <- ecdf(x)
e.y <- ecdf(y)
abs(e.x(u) - e.y(u))
ks.test(x,y)$statistic
The output in both cases is 0.4166667
, indicating perfect agreement. A plot of the situation will clarify what is going on:
plot(e.x, col="Blue", main="ECDF", xlab="Value", ylab="Probability")
plot(e.y, add=TRUE, col="Red")
lines(c(u,u), c(0,1), col="Gray")
lines(c(u,u), c(e.x(u), e.y(u)), lwd=2)
It shows both ECDFs and marks the location found by compare
(namely, u
) with a vertical line: it is supposed to indicate the place where the two graphs attain their greatest vertical separation.
ks.test
) as a plan for obtaining the answer (and indeed it turned out to be a good idea). It's difficult to conceive of how one would present any kind of useful code to represent partial progress in this case.