[R] calculate spatial distance

Sarah Goslee sarah.goslee at gmail.com
Tue Oct 30 20:19:31 CET 2007

I don't know of such a function, but you have several options:

1. Assume that Euclidean distance is "good enough" - probably
reasonable over a limited geographic region (and commonly done).
2. Use your GIS software to do the calculations since it already
"understands" projections and distances on a sphere.
3. Write a function to do this yourself and make it available to
other researchers who need this capability. Assuming that
great circle distances on a perfect sphere are good enough, it
isn't that hard to do.

Eh, I talked myself into it (runs, but otherwise untested):

geogdist <- function(lat1, lon1, lat2, lon2)
# takes latitude and longitue for points 1 and 2
# returns great circle distances in km
# south and west are negative

rad <- function(x) { (x/360) * 2 * pi }
deg <- function(x) { (x/(2 * pi)) * 360 }

gd <- (sin(rad(lat1)) * sin(rad(lat2))) + (cos(rad(lat1)) *
cos(rad(lat2)) * cos(rad(abs(lon2-lon1))))

gd <- deg(acos(gd))

111.23 * gd


On Oct 30, 2007 11:49 AM,  <robert.ptacnik at niva.no> wrote:
> Hi,
> I have a set of locations defined by longitude and latitude (in degrees),
> and want to calculate the spatial (or geographic) distance among all
> locations.
> I did not find such a function in the spatial-related packages. (I *cannot*
> use 'dist', as I have geographic, not cartesian coordinates).
> thanks!
> Robert

Sarah Goslee

More information about the R-help mailing list