R 如何在单独的数据帧中测量点之间的距离?
我用geom列(点类型)创建了2个数据帧。现在,我想计算每对点之间的距离,例如,第一个df中第一行的点与第二个df中第一行的点之间的距离等。以下是我的数据帧:R 如何在单独的数据帧中测量点之间的距离?,r,geospatial,sf,R,Geospatial,Sf,我用geom列(点类型)创建了2个数据帧。现在,我想计算每对点之间的距离,例如,第一个df中第一行的点与第二个df中第一行的点之间的距离等。以下是我的数据帧: df1 <- table %>% st_as_sf(coords = c("lonCust","latCust"), crs = 4326) df2 <- table %>% st_as_sf(coords = c("lonApp","
df1 <- table %>%
st_as_sf(coords = c("lonCust","latCust"), crs = 4326)
df2 <- table %>%
st_as_sf(coords = c("lonApp","latApp"), crs = 4326)
但我得到了一个矩阵,其中计算了两个geom列中每对的距离:
[,1] [,2] [,3] [,4] [,5] ...
[1,] 139.7924 7735.5718 15225.02995 558.104089 1016.58121
[2,] 8503.0544 755.2915 8764.75396 7957.289600 8788.02800
[3,] 15306.5855 9336.9008 18.96914 14876.589918 15929.51643
[4,] 548.3045 7232.0164 14898.70637 8.094068 1078.38236
[5,] 911.5635 8084.3086 15993.36365 1127.730022 46.97799
.
.
我希望在一列中计算距离,仅在相应的geom行之间:
[,1]
[1,] 139.7924
[2,] 8503.0544
[3,] 15306.5855
[4,] 548.3045
[5,] 911.5635
.
.
我读过关于
geosphere
软件包,但是sf
有非常好的st_distance
功能来测量距离,我想用它。最重要的是,我是否需要首先加入这些数据帧?简单的internal_join
fromdplyr
不允许连接两个空间数据帧,st_join
另一方面对我来说不是一个选项,因为我不想通过几何体连接(两个数据帧中的几何体完全不同)正如@mrhellmann提到的,您可以通过_element=T添加,这应该会起作用。如果速度仍然是个问题,我建议使用geosphere
包中的DistGeo()
。但请务必查看文档,以确定您的数据是否适合此功能
library(geosphere)
library(tidyverse)
library(sf)
df1 <- table %>%
st_as_sf(coords = c("lonCust","latCust"), crs = 4326)
doParallel::registerDoParallel()
df_crs4326 <- df1 %>%
group_by(your_id_here) %>%
mutate(
lonCust = map(geometry, 2) %>% unlist(),
latCust= map(geometry, 1) %>% unlist(),
# geometry_2 = st_as_sfc(coords = c("lonApp","latApp"), crs = 4326)
) %>%
mutate(
distance_to_next = distGeo(c(lonCust, latCust), c(lonApp, latApp)) %>% set_units(m),
# distance_2 = st_distance(geometry, geometry_2, by_element = TRUE)
) %>%
ungroup()
库(geosphere)
图书馆(tidyverse)
图书馆(sf)
df1%
st_as_sf(coords=c(“lonCust”、“latCust”),crs=4326)
doParallel::registerDoParallel()
df_crs4326%
分组依据(此处为您的id)%>%
变异(
lonCust=map(几何体,2)%>%unlist(),
latCust=map(几何体,1)%>%unlist(),
#几何体2=st\U as\U sfc(坐标=c(“lonApp”,“latApp”),crs=4326)
) %>%
变异(
距离_至_next=distGeo(c(lonCust,latCust),c(lonApp,latApp))%>%set_单位(m),
#距离_2=st_距离(几何体,几何体_2,按元素=真)
) %>%
解组()
请注意,如果没有对可复制数据进行测试,我不确定注释掉的零件是否正常工作。很接近<代码>st_距离(df1$geometry,df2$geometry,by_element=TRUE)
谢谢!顺便说一句,我有大约25000行,计算速度非常慢,我认为最好在服务器端计算距离库(geodist)
对于这类事情可能更快,并且它可以直接对数据.frames
进行操作。查看geodist()
和/或geodist_vec()
,然后设置paired=TRUE
。
library(geosphere)
library(tidyverse)
library(sf)
df1 <- table %>%
st_as_sf(coords = c("lonCust","latCust"), crs = 4326)
doParallel::registerDoParallel()
df_crs4326 <- df1 %>%
group_by(your_id_here) %>%
mutate(
lonCust = map(geometry, 2) %>% unlist(),
latCust= map(geometry, 1) %>% unlist(),
# geometry_2 = st_as_sfc(coords = c("lonApp","latApp"), crs = 4326)
) %>%
mutate(
distance_to_next = distGeo(c(lonCust, latCust), c(lonApp, latApp)) %>% set_units(m),
# distance_2 = st_distance(geometry, geometry_2, by_element = TRUE)
) %>%
ungroup()