使用mutate中的distm函数计算两点之间的距离 [英] Calculating distance between two points using the distm function inside mutate
问题描述
我正在尝试计算两组经度和纬度坐标之间的距离.
I am trying to calculate the distance between two sets of longitude and latitude coordinates.
我正在使用封装地理层中的distm()函数来完成此操作.
I am using the function distm() from the package geosphere to do this.
如果我手动在distm()函数中输入值,效果很好,但是我无法在mutate命令中使用它.
It works fine if I manually put in the values in the distm() function, but I can't get it to work inside my mutate command.
在mutate函数中运行它时,出现错误:
When running it inside a mutate function I get the error:
Error in mutate_impl(.data, dots) :
Evaluation error: Wrong length for a vector, should be 2.
@Dotpi在评论中写道小注释.未对geosphere:distm方法进行矢量化.要对其进行矢量化,请使用apply函数." 在此线程中回答(用于计算两点之间的地理空间距离(纬度,经度),使用R )
@Dotpi wrote in a comment "A small note. The method geosphere:distm is not vectorized. To vectorize it use the apply functions." when he replied in this thread (Function to calculate geospatial distance between two points (lat,long) using R)
据此,我猜测这是导致mutate函数错误的原因,但我不知道如何解决.我希望使用tidyverse解决方案,但会有所帮助.
From that I am guessing that this is what is causing the error in the mutate function, but I don't know how to solve it. I would prefer a tidyverse solution, but any help is appreciated.
下面是一个测试数据帧,其中首先包含产生错误的代码,然后是一个工作示例,在该示例中,我手动从DF的第一行插入了值.
Below is a test dataframe with first the code that produces the error, and then a working example where I manually insert the values from the first row in DF.
library(tidyverse)
library(geosphere)
set.seed(1)
DF <- tibble(
Long1 = sample(1:10),
Lat1 = sample(1:10),
Long2 = sample(1:10),
Lat2 = sample(1:10))
DF %>% mutate(
Dist = distm(x= c(Long1, Lat1), y=c(Long2, Lat2), fun = distHaversine ))
distm( x = c(3, 3), y = c(10, 5), fun = distHaversine )
推荐答案
也许我们可以使用 pmap
library(purrr)
pmap_dbl(DF, ~ distm(x = c(..1, ..2), y = c(..3, ..4),
fun = distHaversine) %>% c)
与 mutate
library(dplyr)
DF %>%
mutate(Dist = pmap_dbl(., ~
distm(x = c(..1, ..2), y = c(..3, ..4), fun = distHaversine)))
# A tibble: 10 x 5
# Long1 Lat1 Long2 Lat2 Dist
# <int> <int> <int> <int> <dbl>
# 1 3 3 10 5 808552.
# 2 4 2 2 6 497573.
# 3 5 6 6 4 248726.
# 4 7 10 1 2 1110668.
# 5 2 5 9 10 951974.
# 6 8 7 8 8 111319.
# 7 9 8 7 9 246730.
# 8 6 4 5 1 351986.
# 9 10 1 3 7 1024599.
#10 1 9 4 3 745867.
这篇关于使用mutate中的distm函数计算两点之间的距离的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!