Error: Assigned data `distHaversine(dtrav)` must be compatible with existing data

Error: Assigned data `distHaversine(dtrav)` must be compatible with existing data

我只是想用 longitude/latitude 点来计算行进距离。我有 2983223 行数据。我不断收到此错误,并且我的距离列在整个 df 中重复相同的值。

library(geosphere)

dtrav <- matrix(c(df$start_lng,df$start_lat), c(df$end_lng, df$end_lat), nrow=2983223,ncol=2)

df$distance <- distHaversine(dtrav)

Error: Assigned data `distHaversine(dtrav)` must be compatible with existing data.
x Existing data has 2983223 rows.
x Assigned data has 2983222 rows.
ℹ Only vectors of size 1 are recycled.

您应该分开起点和终点矩阵,否则 distHaversine 计算行之间的距离,这导致 n 行的距离为 n-1,因此出现错误消息。

df$distance = distHaversine(cbind(c(df$start_lng,df$start_lat)),
                            cbind(c(df$end_lng, df$end_lat)))