【问题标题】:Error in calculating distance using latitude and longitude使用经纬度计算距离时出错
【发布时间】:2021-10-18 08:13:36
【问题描述】:

我有一个包含 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之后得到的文件

【问题讨论】:

  • 能否通过dput(trips_202007)提供数据集?
  • @pbraeutigm 我已经更新了帖子并包含了文件。
  • 哦,这个数据集真的很大。我想了大概 10 行来测试。你能用 dput(head(trips_202007)) 更新它吗?我下载了 txt,但它对于测试来说太大了
  • @pbraeutigm 这里是链接。谢谢! drive.google.com/file/d/1lnXeNqIRCDad0WotgoUQhrfPg0AXApLr/…
  • 好的,我明白了。对于您的下一篇文章,您可以将此结构与您的第二个链接中的一些数据直接集成到您的问题中。这有助于解决问题。我现在明白了,正在寻找答案。

标签: r error-handling


【解决方案1】:

您遇到以下错误:

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)
}

先看那个函数我找到了here,然后用这段代码重新开始我们的计算:

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

【讨论】:

猜你喜欢
  • 2018-09-02
  • 2013-04-16
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2023-03-10
  • 2021-05-10
  • 2021-09-05
  • 1970-01-01
相关资源
最近更新 更多