繁体   English   中英

使用mutate中的distm函数计算两点之间的距离

[英]Calculating distance between two points using the distm function inside mutate

我正在尝试计算两组经度和纬度坐标之间的距离。

我正在使用来自封装地理层的函数distm()来执行此操作。

如果我在distm()函数中手动输入值,它会很好地工作,但是我无法在mutate命令中使用它。

在mutate函数中运行它时,出现错误:

Error in mutate_impl(.data, dots) : 
Evaluation error: Wrong length for a vector, should be 2.

@Dotpi在评论中写道: “请注意,geosphere:distm方法未向量化。要对其向量化,请使用apply函数。” 当他在此线程中回复时(使用R计算两点(纬度,经度)之间的地理空间距离的函数

据此,我猜测这是导致mutate函数错误的原因,但我不知道如何解决。 我希望使用tidyverse解决方案,但是可以提供任何帮助。

下面是一个测试数据框,其中首先包含产生错误的代码,然后是一个工作示例,在该示例中,我手动从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.

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM