【发布时间】:2018-10-09 19:52:33
【问题描述】:
我想计算两个数据框的每行和列之间的最小地理距离。 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 中的每个机构,并将 DF2 到 DF1 的距离和 ID 添加。虽然我知道如何计算成对距离,但我无法计算从 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 的第 1 行和矢量化事件。
#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))
我的猜测是,该解决方案需要对数据进行重塑和应用。此外,考虑到观察次数,循环是非常糟糕的做法,而且速度太慢。
非常感谢任何帮助。
【问题讨论】: