首页 > 解决方案 > R 错误:向量的长度错误,使用 Geosphere 包时应为 2

问题描述

我正在尝试分析两个位置之间的平均距离,以便为自动批准行驶距离提供可接受的截止值。我已经提到(geosphere distHaversine() & dplyr - error wrong length for vector, should be 2)&(Getting Error in .pointsToMatrix(p1) : Wrong length for a vector, should be 2)但我无法调试错误并完成我的分析。

数据框是这样的,有 10 行数据。

df <- c(lat1,long1,lat2,long2)

具有 10 行数据的 df 矩阵

当我尝试使用以下

df %>% rowwise() %>% mutate(HVRSINE = distHaversine(c(df$long1,df$lat1),c(df$long2,df$lat2)))

错误如下:

Error: Problem with `mutate()` column `HVRSINE`.
x Wrong length for a vector, should be 2

The error occurred in row 1.

当我在 disthaversine 中手动编写 lat,long for 时,输出就像一个魅力。

我究竟做错了什么?

标签: rdataframehaversinegeosphererowwise

解决方案


尝试

library(tidyverse)
df %>%
  mutate(HVRSINE = unlist(pmap(list(a = long1, 
                                    b = lat1, 
                                    x = long2,
                                    y = lat2),
                               ~ distHaversine(c(..1, ..2), c(..3, ..4)))))

推荐阅读