nass
nass

Reputation: 3

Create polygon from lines in R

I have a dataset that contains coordinates of the start point and the stop point of a trajectory.

First, I have created a sf object as follow to have the geometry of each point as "line" :

CRSWGS84 = CRS("+proj=longlat +datum=WGS84 +no_defs +ellps=WGS84 +towgs84=0,0,0")

df$geom = sprintf("LINESTRING(%s %s, %s %s)", df$start_lon, df$start_lat, df$stop_lon, df$stop_lat) df_sf = st_as_sf(df, wkt = "geom", crs = CRSWGS84)

Then when I plot the geometry I obtain a graph of all the lines which is the result i am looking for since I want to have the trajectory from the start to the stop. However, I would like to be able to connect the end point of the lines in order to construct a polygon.

Is it possible to do it ?

Thank you

Upvotes: 0

Views: 3126

Answers (1)

Jindra Lacko
Jindra Lacko

Reputation: 8699

Sure, it is not only possible but also quite straightforward. All you need to do is sf::st_cast() your line object to geometry type "POLYGON".

Consider this code, with the lines object borrowed from Count number of times that sf linestrings intersect grid cell in r

library(sf)

#creating data example
id <- c("844", "844", "844", "844", "844","855", "855", "855", "855", "855")

lat <- c(-30.6456, -29.5648, -28.6667, -31.5587, -30.6934, -29.3147, -28.0538, 
         -26.5877, -26.6923, -27.40865)
long <- c(-50.4879, -49.8715, -51.8716, -50.4456, -50.9842, -51.9787, -47.2343, 
          -49.2859, -48.19599, -49.64302)

df <- data.frame(id = as.factor(id), lat, long)

#converting to sf
df.sf <- df %>% 
  sf::st_as_sf(coords = c("long", "lat"), crs = 4326)

#creating linestrings
df.line <- df.sf %>% 
  dplyr::group_by(id) %>%
  dplyr::summarize() %>%
  sf::st_cast("LINESTRING") 


plot(df.line)

enter image description here

# cast to polygons
polygon <- df.line %>% 
  st_cast("POLYGON")

plot(polygon)

enter image description here

Upvotes: 4

Related Questions