Re: [R] Distances between two datasets of x and y co-ordinates

From: Liaw, Andy <andy_liaw_at_merck.com>
Date: Fri, 14 Mar 2008 10:52:21 -0400

From: adrian_at_maths.uwa.edu.au  

> Andrew McFadden <Andrew.McFadden@maf.govt.nz> writes:
>
> > I am trying to determine the distances between two datasets
> of x and y
> > points.
>
> This can be done efficiently in the package 'spatstat'.
>
> library(spatstat)
> crossdist(x1, y1, x2, y2)
>
> where x1, y1 are vectors of coordinates for the first set of points
> and x2, y2 for the second set. See help(crossdist.default)
>
> This is executed in C and is faster than using outer() or apply().

The margin may not be as large as you imagine:

crossdist2 <- function(x1, y1, x2, y2) {
    c1 <- complex(real=x1, imaginary=y1)
    c2 <- complex(real=x2, imaginary=y2)
    dist <- outer(c1, c2, function(z1, z2) Mod(z1-z2))     dist
}
R> set.seed(17)
R> n <- 1000
R> x1 <- rnorm(n)
R> y1 <- rnorm(n)
R> x2 <- rnorm(n)
R> y2 <- rnorm(n)
R> system.time(d2 <- crossdist2(x1, y1, x2, y2))

   user system elapsed
   1.03 0.09 1.17
R> library(spatstat)
R> system.time(d1 <- crossdist2(x1, y1, x2, y2))

   user system elapsed
   1.08 0.03 1.12
R> all.equal(d1, d2)
[1] TRUE Andy  

> The result is a matrix giving the distance between each pair of points
> (the first point in the first dataset and the second point in
> the second
> set). If these datasets are large, you can of course run into
> trouble with
> the size of this matrix.
>
> If you just wanted to find the distance to the *nearest* point
> (or identify which point is nearest), use the function nncross().
>
> Adrian Baddeley
>
> ______________________________________________
> R-help_at_r-project.org mailing list
> https://stat.ethz.ch/mailman/listinfo/r-help
> PLEASE do read the posting guide
> http://www.R-project.org/posting-guide.html
> and provide commented, minimal, self-contained, reproducible code.
>
>
>



Notice: This e-mail message, together with any attachme...{{dropped:15}}

R-help_at_r-project.org mailing list
https://stat.ethz.ch/mailman/listinfo/r-help PLEASE do read the posting guide http://www.R-project.org/posting-guide.html and provide commented, minimal, self-contained, reproducible code. Received on Fri 14 Mar 2008 - 15:05:28 GMT

Archive maintained by Robert King, hosted by the discipline of statistics at the University of Newcastle, Australia.
Archive generated by hypermail 2.2.0, at Fri 14 Mar 2008 - 15:30:23 GMT.

Mailing list information is available at https://stat.ethz.ch/mailman/listinfo/r-help. Please read the posting guide before posting to the list.

list of date sections of archive