问题是sf 对象一次只能有一个geom 列处于活动状态。要解决这个问题,只需调用 sf 对象 test1 和 test2 就可以了。
请在下面找到修改后的代码和相应的输出。
routes <- comb %>%
mutate(distances = osrmRoute(
src = test_1,
dst = test_2,
returnclass = "sf"
)$distance)
routes
# A tibble: 4 x 5
name_1 geom_1 name_2 geom_2 distances
<chr> <POINT [°]> <chr> <POINT [°]> <dbl>
1 a (13.37187 52.52129) c (13.40122 52.51947) 4.35
2 a (13.37187 52.52129) d (13.34921 52.51495) 4.35
3 b (13.44586 52.50369) c (13.40122 52.51947) 4.35
4 b (13.44586 52.50369) d (13.34921 52.51495) 4.35
或者,您可以在sf 对象comb 中指定哪个geom 列处于活动状态,您将获得与上述相同的结果。
routes <- comb %>% mutate(distances = osrmRoute(
src = st_sf(.,sf_column_name = "geom_1"),
dst = st_sf(.,sf_column_name = "geom_2"),
returnclass = "sf"
)$distance)
编辑
作为我与@Jindra Lacko(参见下面的 cmets)交流的后续行动,我提出了一个 computeDistances() 函数,它可以帮助你得到你想要的。请使用您的对象comb在下面找到函数的代码及其输出
computeDistances <- function(x){
distances <- data.frame(Distances = numeric())
for (i in seq(x)){
distances[i,"Distances"] <- osrmRoute(
src = st_sf(x,sf_column_name = "geom_1")[i,],
dst = st_sf(x,sf_column_name = "geom_2")[i,],
returnclass = "sf"
)$distance
}
results <- st_sf(cbind(x, distances))
return(results)
}
computeDistances(comb)
Simple feature collection with 4 features and 3 fields
Active geometry column: geom_1
Geometry type: POINT
Dimension: XY
Bounding box: xmin: 13.37187 ymin: 52.50369 xmax: 13.44586 ymax: 52.52129
Geodetic CRS: WGS 84
name_1 name_2 Distances geom_1 geom_2
1 a c 4.3543 POINT (13.37187 52.52129) POINT (13.40122 52.51947)
2 a d 2.6576 POINT (13.37187 52.52129) POINT (13.34921 52.51495)
3 b c 4.4650 POINT (13.44586 52.50369) POINT (13.40122 52.51947)
4 b d 8.1611 POINT (13.44586 52.50369) POINT (13.34921 52.51495)