Skip to content

Instantly share code, notes, and snippets.

@tim-salabim
Last active May 23, 2017 07:51
Show Gist options
  • Save tim-salabim/57d69e3a1cf64ff386205f528e218ef3 to your computer and use it in GitHub Desktop.
Save tim-salabim/57d69e3a1cf64ff386205f528e218ef3 to your computer and use it in GitHub Desktop.
st_explode
library(sf)
library(mapview)
library(data.table)
lns = st_cast(trails, "LINESTRING")
# lns = lns[rep(seq_len(nrow(lns)), 1000),]
pts = st_cast(st_line_sample(lns, n = 1), "POINT")
st_explode = function(x) {
if (!inherits(st_geometry(x), "sfc_LINESTRING"))
x = st_cast(x, "LINESTRING")
crds = st_coordinates(x)[, 1:2]
mat = lapply(seq(nrow(crds) - 1), function(i) {
st_linestring(rbind(crds[i, ], crds[i + 1, ]))
})
st_sfc(mat, crs = st_crs(x))
}
extract_segment = function(ln, pt, radius) {
ln_ex = st_explode(ln)
ind = st_intersects(st_buffer(pt, radius), ln_ex)[[1]]
st_sfc(ln_ex[[ind]], crs = st_crs(ln))
}
system.time({
tst = st_as_sf(rbindlist(lapply(seq(nrow(lns)), function(i) {
print(i)
geom = extract_segment(lns[i, ], pts[i], 0.0001)
as.data.table(st_sf(id = i, geom))
})))
})
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment