I was wondering if there is a way to create linestring
from two points given in the same row in a dataframe in a new geometry column. In other words longitudes and latitudes of the two points are given in a dataframe like the following:
df <- data.frame(id = c("a", "b"), lon1 = c(1,2), lat1 = c(3,4), lon2 = c(5,6), lat2 = c(7,8))
where lon1
and lat1
represent the coordinates of the first point and lon2
and lat2
are the coordinates of the second point. The desired dataframe would have two rows and two columns - the id
column and a geometry
column.
I tried with sf::st_linestring
but seems this function only works with matrices.
Desired dataframe:
desired_df <- data.frame(id = c("a", "a", "b", "b"), lon = c(1,2,5,6), lat = c(3,4,7,8)) %>% st_as_sf(coords = c("lon", "lat"), dim = "XY") %>% st_set_crs(4236) %>% group_by(id) %>% summarise(geometry = st_union(geometry), do_union = FALSE) %>% st_cast("LINESTRING")