我正在尝试计算两组经度和纬度坐标之间的距离。
我正在使用 geosphere 包中的函数 distm() 来执行此操作。
如果我手动将值放入 distm() 函数中,它工作正常,但我无法让它在我的 mutate 命令中工作。
在 mutate 函数中运行它时,出现错误:
Error in mutate_impl(.data, dots) :
Evaluation error: Wrong length for a vector, should be 2.
Run Code Online (Sandbox Code Playgroud)
@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 )
Run Code Online (Sandbox Code Playgroud)
也许我们可以使用 pmap
library(purrr)
pmap_dbl(DF, ~ distm(x = c(..1, ..2), y = c(..3, ..4),
fun = distHaversine) %>% c)
Run Code Online (Sandbox Code Playgroud)
当与 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.
Run Code Online (Sandbox Code Playgroud)