我有一个由三列组成的数据框,“Point_name”“经度”和“纬度”
Point_Name Longitude Latitude
University of Arkansas 36.067832 -94.173655
Lehigh University 40.601458 -75.360063
Harvard University 42.379393 -71.115897
我可以使用R包来计算每个点之间的距离吗?目的是让R“测量”点之间的距离,然后产生在“X”(例如500米)距离半径内具有另一个点的点的数据帧,或者产生像这样的数据帧......
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
答案 0 :(得分:0)
这个怎么样
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