I have a set of begin and end coordinates that look like this:
begin.coord <- data.frame(lon=c(-85.76,-85.46,-85.89), lat=c(38.34,38.76,38.31))
end.coord <- data.frame(lon=c(-85.72,-85.42,-85.85), lat=c(38.38,38.76,38.32))
I am trying to create a set of 3 line segments by connecting each begin point to its corresponding end point. I would like the end product to be a SpatialLines
object so that I can use the it with over
function in the sp
package.
These days (2020) I would do this with sfheaders:
begin.coord <- data.frame(lon=c(-85.76,-85.46,-85.89), lat=c(38.34,38.76,38.31))
end.coord <- data.frame(lon=c(-85.72,-85.42,-85.85), lat=c(38.38,38.76,38.32))
begin.coord$linestring_id <- end.coord$linestring_id <- seq_len(nrow(begin.coord))
library(dplyr)
sfheaders::sf_linestring(bind_rows(begin.coord, end.coord) %>% arrange(linestring_id),
x = "lon", y = "lat", linestring_id = "linestring_id")
#> linestring_id geometry
#> 1 1 -85.76, -85.72, 38.34, 38.38
#> 2 2 -85.46, -85.42, 38.76, 38.76
#> 3 3 -85.89, -85.85, 38.31, 38.32
Created on 2020-04-01 by the reprex package (v0.3.0)
One could also use the sf
package to build a list of sfc
class and then convert it to SpatialLines
object:
# the given data
begin.coord <- data.frame(lon=c(-85.76,-85.46,-85.89), lat=c(38.34,38.76,38.31))
end.coord <- data.frame(lon=c(-85.72,-85.42,-85.85), lat=c(38.38,38.76,38.32))
library(sf)
# Create list of simple feature geometries (linestrings)
l_sf <- vector("list", nrow(begin.coord))
for (i in seq_along(l_sf)){
l_sf[[i]] <- st_linestring(as.matrix(rbind(begin.coord[i, ], end.coord[i,])))
}
# Create simple feature geometry list column
l_sfc <- st_sfc(l_sf, crs = "+proj=longlat +datum=WGS84")
# Convert to `sp` object if needed
lines_sp <- as(l_sfc, "Spatial")
Extra/Optional:
# - create a sf object from the `sfc` list of linestrings
lines_sf = st_sf(id = 1:3, geometry = l_sfc)
# - visualize the `sfc` list of linestrings
plot(l_sfc)
library(mapview)
mapview(l_sfc, lwd = 5)
# or mapview(lines_sp, lwd = 5)
# or mapview(lines_sf, lwd = 5)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With