Skip to content

Instantly share code, notes, and snippets.

@elipousson
Last active December 4, 2022 17:19
Show Gist options
  • Save elipousson/811fcfc463ae5a3ed169ae48a040e0ed to your computer and use it in GitHub Desktop.
Save elipousson/811fcfc463ae5a3ed169ae48a040e0ed to your computer and use it in GitHub Desktop.
nc <- sf::st_read(system.file("shape/nc.shp", package = "sf"))
nc_random_pts <- sf::st_sample(nc, size = 1000)
nc_random_pts <- sf::st_join(sf::st_as_sf(nc_random_pts), nc)
bind_pt_coords <- function(x, ..., .drop = TRUE) {
if (sf::st_geometry_type(x, FALSE) != "POINT") {
coords <- suppressWarnings(sf::st_coordinates(sf::st_centroid(x)))
} else {
coords <- suppressWarnings(sf::st_coordinates(x))
}
if (.drop) {
x <- sf::st_drop_geometry(x)
}
dplyr::bind_cols(
dplyr::select(x, ...),
dplyr::as_tibble(coords)
)
}
nc_lines <-
dplyr::left_join(
bind_pt_coords(nc_random_pts, FIPS),
bind_pt_coords(nc, FIPS),
by = "FIPS",
suffix = c("_from", "_to")
)
nc_lines <- dplyr::rowwise(nc_lines)
nc_lines <- dplyr::mutate(
nc_lines,
geometry = sf::st_cast(
sf::st_combine(
c(
sf::st_point(c(X_from, Y_from)),
sf::st_point(c(X_to, Y_to))
)
),
"LINESTRING"
)
)
nc_lines <- sf::st_as_sf(nc_lines, crs = sf::st_crs(nc))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment