我想做的:
我有一个sf对象,它有许多点的位置。对于每个位置,我想使用openrouteservice-r包生成具有不同参数的等时线。
对象看起来像这样:
library(sf)
library(dplyr)
library(openrouteservice)
dd <- data.frame(x = c(-89.33, -89.33, -89.33, -89.33, -89.55, -89.55, -89.55, -89.55),
y = c(43.12, 43.12, 43.12, 43.12, 43.12, 43.12, 43.12, 43.12),
bike_type = c("bike", "bike", "e-bike", "e-bike", "bike", "bike", "e-bike", "e-bike"),
time = c(300, 600, 300, 600, 300, 600, 300, 600))
df <- st_as_sf(dd, coords = c("x","y"))
df
我创建了一个辅助函数,它接受三个参数,通过ors_isochrones
运行它们并返回等时线的几何形状(多边形):
# requires API key: https://openrouteservice.org/dev/#/login
# ors_api_key(key, service = "openrouteservice")
create_iso <- function(location, profile_1 = "e-bike", range_1){
iso <- ors_isochrones(locations = st_coordinates(location),
profile = ors_profile(mode = profile_1),
range = range_1,
output = "sf")
iso$geometry
}
我的想法是,现在我可以从mutate
内调用函数到位置数据帧:
df %>%
mutate(iso = create_iso(geometry, profile, time))
<标题>哪些是有效的方式:- 为单行
df
执行此操作:
> df[1,] %>%
+ mutate(iso = create_iso(geometry, bike_type, time))
[1] 300
Simple feature collection with 1 feature and 2 fields
Active geometry column: geometry
Geometry type: POINT
Dimension: XY
Bounding box: xmin: -89.33044 ymin: 43.12018 xmax: -89.33044 ymax: 43.12018
CRS: NA
bike_type time geometry iso
1 bike 300 POINT (-89.33044 43.12018) POLYGON ((-89.34975 43.1200...
- 为
df
的多行执行此操作,同时保持其他两个参数固定:
df[4:7,] %>%
mutate(iso = create_iso(geometry, "e-bike", 100))
什么不工作
为多行执行此操作,同时提供所有三个参数
df[4:7,] %>%
+ mutate(iso = create_iso(geometry, bike_type, time))
[1] 600 300 600 300
Error in `stopifnot()`:
! Problem while computing `iso = create_iso(geometry, bike_type,
time)`.
Caused by error in `match.arg()`:
! 'arg' must be of length 1
Run `rlang::last_error()` to see where the error occurred.
Called from: signal_abort(cnd, .file)
<标题>全reprex h1> sup>由reprex包(v2.0.1)创建于2022-04-14
标题>标题>要将自定义函数应用于data.frame的每一行,可以使用rowwise()
:
library(dplyr)
df %>%
rowwise() %>%
mutate(iso = create_iso(geometry, bike_type, time))