使用经纬度计算距离时出错

Error in calculating distance using latitude and longitude

我有一个包含 4 列的数据集:

start_lat 41.90687, 41.94367, 41.93259, 41.89076

start_lng -87.62622, -87.64895, -87.63643, -87.63170

end_lat 41.90672, 41.98404, 41.93650, 41.91831

end_lng -87.63483, -87.66027, -87.64754

我想添加名为 distance 的第 5 列,我使用以下公式,但出现以下错误:

trips_202007 <- trips_202007 %>%
  rowwise()
  mutate(distance = distm(c(trips_202007["start_lng"], trips_202007["start_lat"]), c(trips_202007["end_lng"], trips_202007["end_lat"]), fun=distHaversine))

.pointsToMatrix(x) 中的错误:'list' 对象无法强制键入 'double'

有没有办法避免这个错误?

非常感谢您的建议。

这是我在 dput(trips_202007, file="trips_202007.txt") 之后得到的文件:https://drive.google.com/file/d/1lnXeNqIRCDad0WotgoUQhrfPg0AXApLr/view?usp=sharing

您有以下错误:

Error in .pointsToMatrix(x) : 'list' object cannot be coerced to type 'double'

这是因为您的函数正在尝试计算矩阵。您问 R 是否会将结果放入一个单元格中,而 R 不希望那样。对于这种情况,我发现以下函数正在运行:

    dt.haversine <- function(lat_from, lon_from, lat_to, lon_to, r = 6378137){
          radians <- pi/180
          lat_to <- lat_to * radians
          lat_from <- lat_from * radians
          lon_to <- lon_to * radians
          lon_from <- lon_from * radians
          dLat <- (lat_to - lat_from)
          dLon <- (lon_to - lon_from)
          a <- (sin(dLat/2)^2) + (cos(lat_from) * cos(lat_to)) * (sin(dLon/2)^2)
          return(2 * atan2(sqrt(a), sqrt(1 - a)) * r)
}

首先阅读那个函数我找到了它,然后用这段代码再次开始我们的计算:

trips_202007 <- trips_202007 %>%
          mutate(distance = dt.haversine(start_lat, start_lng, end_lat, end_lng))
trips_202007