You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

使用R语言geosphere::distHaversine计算经纬度距离报错求助

解决distHaversine计算逐行坐标距离的错误

错误原因

distHaversine要求传入的坐标是每行对应一对(经度,纬度)的矩阵/数据框,你当前用c(park_long, park_lat)把整列合并成了一个长向量,不是按行配对的坐标对,导致函数识别到长度不符合要求,触发报错。

两种修正方案

方案1:按行分组计算

适合理解逻辑,用rowwise()让mutate逐行处理,传入每行的坐标对:

library(tidyverse)
library(geosphere)

MLB_Locations <- tibble(park_long =1:3,
                        park_lat = 1:3, 
                        city_long = 5:7,
                        city_lat = 10:12)

MLB_Locations <- MLB_Locations %>%
  rowwise() %>%
  mutate(distance = distHaversine(c(park_long, park_lat), c(city_long, city_lat))) %>%
  ungroup() # 处理完取消行分组,避免后续操作受影响

方案2:矩阵传入(更高效)

直接将坐标列转为矩阵,distHaversine会自动按行匹配计算距离,无需分组,适合大数据集:

library(tidyverse)
library(geosphere)

MLB_Locations <- tibble(park_long =1:3,
                        park_lat = 1:3, 
                        city_long = 5:7,
                        city_lat = 10:12)

MLB_Locations <- MLB_Locations %>%
  mutate(distance = distHaversine(
    matrix(c(park_long, park_lat), ncol = 2),
    matrix(c(city_long, city_lat), ncol = 2)
  ))

补充说明

distHaversine返回的距离单位是米,如果需要转换为公里,可以除以1000:

# 转换为公里
MLB_Locations <- MLB_Locations %>% mutate(distance_km = distance / 1000)

内容的提问来源于stack exchange,提问作者Miles Zeller

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.16 15:00:03