Question

I have a dataframe consisting of three columns, "Point_name" "longitude" and "latitude"

Point_Name              Longitude   Latitude
University of Arkansas  36.067832   -94.173655
Lehigh University       40.601458   -75.360063
Harvard University      42.379393   -71.115897

Is there an R package I can use to calculate distances between each point? The aim is to get R to "measure" the distance between points and then produce either a dataframe of points that have another point within "X" (eg. 500 meters) distance radius or produce a dataframe like this one...

Point_Name              Longitude   Latitude    Nearest_Point       Distance_km
University of Arkansas  36.067832   -94.173655  Lehigh University   1750        
Lehigh University       40.601458   -75.360063  Harvard University  450
Harvard University      42.379393   -71.115897  Lehigh University   450
Was it helpful?

Solution

How about this

df<-read.table(header=T, text="Point_Name|Longitude|Latitude
University of Arkansas|36.067832|-94.173655
Lehigh University|40.601458|-75.360063
Harvard University|42.379393|-71.115897", sep="|")

great_circle_distance <- function(lat1, long1, lat2, long2) {
  a <- sin(0.5 * (lat2*pi/180 - lat1*pi/180))
  b <- sin(0.5 * (long2*pi/180 - long1*pi/180))
  12742 * asin(sqrt(a * a + cos(lat1*pi/180) * cos(lat2*pi/180) * b * b))
}

cross<-expand.grid(1:nrow(df),1:nrow(df))

cross$dist<-apply(cross,1,function(x){great_circle_distance(df[x[1],3],
                                               df[x[1],2],
                                               df[x[2],3],
                                               df[x[2],2])
}
      )

cross$from<-df[cross$Var1,1]
cross$to<-df[cross$Var2,1]

require(plyr)
ddply(cross[cross$Var1!=cross$Var2,],.(from),summarise,min(dist),to[dist==min(dist)])

from       ..1                ..2
1     Harvard University  475.3078  Lehigh University
2      Lehigh University  475.3078 Harvard University
3 University of Arkansas 2090.8387  Lehigh University
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top