使用 for 循环估计 r 中一个参考列和多个列之间的距离?

Estimate distance between one reference column and several columns in r using a for loop?

我有一个具有以下结构的数据框 (df):

ID   Long_Ref   Lat_Ref    Long_1   Lat_1    Long_2   Lat_2
A    -71.69     -33.39    -70.29   -33.39   -71.69   -34.19
B    -72.39     -34.34    -74.29   -31.19   -70.54   -33.38
C    -70.14     -32.38    -70.62   -32.37   -69.76   -32.22
D    -70.39     -33.54    -70.42   -34.99   -68.69   -32.33

我正在尝试使用 distHaversine 将新列附加到我现有的数据框中,其中 Ref 和 1、Ref 和 2 之间的距离等。

这是我到目前为止使用的代码:

for (i in 1:2){
for (j in 1:nrow(df)){
df[,paste("Dist_Mts_",i,sep="")][j]<-distHaversine(matrix(c(df$Long_Ref,df$Lat_Ref),ncol=2),
                      matrix(c(as.matrix(df[,paste("Long_",i,sep="")]),
                               as.matrix(df[,paste("Lat_",i,sep="")])),ncol=2))
 }
}

但是,我不断收到以下错误:

Error in .pointsToMatrix(p2) * toRad : 
  non-numeric argument to binary operator
In addition: Warning message:
In .pointsToMatrix(p2) : NAs introduced by coercion

如有任何帮助,我将不胜感激。谢谢。

假设你有一些可能大于 2 的点,你想计算它们的距离,你可以做这样的事情(不使用 for 循环):

point.no <- 1:2 # depending on how many points you have

library(tidyverse)
point.no %>% 
  map(~ paste0(c('Long_', 'Lat_'), .x)) %>% 
  setNames(paste0('Dist_Mts_', point.no)) %>% 
  map_df(~ distHaversine(df[c('Long_Ref', 'Lat_Ref')], df[.x]))

如果您只需要计算到那两个点的距离,那么您可以这样写:

list(Dist_Mts_1=c('Long_1', 'Lat_1'), Dist_Mts_2=c('Long_2', 'Lat_2')) %>% 
  map_df(~ distHaversine(df[c('Long_Ref', 'Lat_Ref')], df[.x]))

输出:

# A tibble: 4 x 2
  Dist_Mts_1 Dist_Mts_2
       <dbl>      <dbl>
1     130123      89056
2     393159     201653
3      45141      39946
4     161437     208248