[英]Return minimum distance between each row and each column of two long lat coordinates in two dataframes
我想计算两个数据框的每一行和每一列之间的最小地理距离。 DF1有许多机构,DF2有许多事件。 像这样:
#DF1 (institutions)
DF1 <- data.frame(latitude=c(41.49532, 36.26906, 40.06599),
longitude=c(-98.77298, -101.40585, -80.72291))
DF1$institution <- letters[seq( from = 1, to = nrow(DF1))]
#DF2 (events)
DF2 <- data.frame(latitude=c(32.05, 32.62, 30.23), longitude=c(-86.82,
-87.67, -88.02))
DF2$ID <- seq_len(nrow(DF1)
我想以最小的距离返回事件到DF1中的每个机构,并将距离和ID从DF2添加到DF1。 虽然我知道如何计算两两之间的距离,但我无法计算从DF [1,]到DF2的所有距离并返回最小值等等。
这就是我尝试过的(失败了)。
library(geosphere)
#Define a function
distanceCALC <- function(x, y) { distm(x = x, y = y,
fun = distHaversine)}
#Define vector of events
DF2_vec <- DF2[, c('longitude', 'latitude')]
#Define df to hold distances
shrtdist <- data.frame()
现在,我的尝试是将distanceCALC与DF1的row1和矢量化事件一起传递。
#Loop through every row in DF1 and calculate all the distances to instutions a, b, c. Append to DF1 smallest distance + DF2$ID.
#This only gives me the pairwise distance
for (i in nrow(DF1)){
result <- distanceCALC(DF1[i,c('longitude', 'latitude')], DF2_vec)
}
#Somehow take shortest distance for each row*column distance matrix
shrtdist <- rbind(shrtdist, min(result[,], na.rm = T))
我的猜测是,该解决方案需要对数据进行整形并无效处理。 同样,循环是非常不好的做法,并且鉴于观察到的数目,循环太慢了。
任何帮助是极大的赞赏。
这是使用outer
函数解决此问题的简单方法
squared_distance <- function(x, y ) (x - y)^2
lat <- outer(DF1$latitude, DF2$latitude, squared_distance)
long <- outer(DF1$longitude, DF2$longitude, squared_distance)
pairwise_dist <- sqrt(lat + long)
rownames(pairwise_dist) <- DF1$institution
colnames(pairwise_dist) <- DF2$ID
pairwise_dist
这为您提供了每个机构(行)与事件(列)之间的距离的矩阵。 要获取df1中的距离和事件,我们可以
df1$min_dist <- apply(pairwise_dist, 1, min)
df1$min_inst <- apply(pairwise_dist, 1, min)
请注意,第二个方法在这种情况下起作用的原因是事件用数字标记。 如果您的真实数据不具备该便捷功能,我们需要
df1$min_inst <- colnames(pairwise_dist)[apply(pairwise_dist, 1, which.min)]
我尚未对此进行测试,但我认为这应该可行。 同样,输出将是一个矩阵。
gcd.hf <- function(DF1, DF2) {
sin2.long <- sin(outer(DF1$longitude, DF2$longitude, "-") / 2)^2
sin2.lat <- outer(DF1$latitude, DF2$latitude, "-")
cos.lat <- outer(cos(DF1$latitude), cos(DF2$latitude), "*")
a <- sin2.long + sin2.lat * cos.lat # we do this cell-wise
cir <- 2 * asin(pmin(1, sqrt(a))) # I never assign anything to "c" since that's concatenate. Rename this variable as appropriate (I have no idea if it's related to the circumference or not.)
cir * 6371
}
pairwise_dist <- gcd.hf(DF1, DF2)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.