我正在尝试计算两组经度和纬度坐标之间的距离。
我正在使用包geosphere中的函数distm()来执行此操作。
如果我手动输入distm()函数中的值,它可以正常工作,但是我无法在mutate命令中使用它。
在mutate函数中运行时,我收到错误:
Error in mutate_impl(.data, dots) :
Evaluation error: Wrong length for a vector, should be 2.
@Dotpi在评论中写道"小记。 geosphere方法:distm没有矢量化。要进行矢量化,请使用应用函数。" 当他在此帖子中回复时(Function to calculate geospatial distance between two points (lat,long) using R)
由此我猜测这是导致mutate函数错误的原因,但我不知道如何解决它。我更喜欢一个整体解决方案,但任何帮助都表示赞赏。
下面是一个测试数据框,首先是产生错误的代码,然后是一个工作示例,我手动插入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 )
答案 0 :(得分:3)
也许我们可以使用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.