I'm trying to convert a regular 1-degree by 1-degree geographic grid to polygons while maintaining the data associated with each grid point using the R sf package.
Example code:
library(tidyverse)
library(sf)
library(sfheaders)
library(sfheaders)
# latitude
lldata <- tibble(lat=as.numeric(rep(seq(40,49.5),10)))
# Longitude + add data
lldata <- lldata %>%
group_by(lat) %>%
mutate(lon = -90 + row_number()-1,
data = runif(1))
#Plot the grid as points
lldata %>%
ggplot() +
geom_point(aes(x=lon,y=lat,color=data))
# Attempt #1
#https://stackoverflow.com/questions/48383990/convert-sequence-of-longitude-and-latitude-to-polygon-via-sf-in-r
lldata %>% arrange(lat,-lon) %>%
st_as_sf(coords = c("lon", "lat"), crs = 4326) %>%
summarise(geometry = st_combine(geometry)) %>%
st_cast("POLYGON") %>%
ggplot() +
geom_sf()
# Also tried
poly <- st_sf(st_sfc(st_make_valid(st_polygon(list(as.matrix(lldata))))), crs = 4326)
# error that the polygon is not closed
# Attempt #2
# https://stackoverflow.com/questions/52669779/convert-sets-of-spatial-coordinates-to-polygons-in-r-using-sf/52671103
sf <- sfheaders::sf_polygon(
obj = lldata
, x = "lon"
, y = "lat"
)
# Same result as above
sf %>%
ggplot() +
geom_sf()
I'm expecting a polygon whose boundaries are defined by the regular grid but the boundaries of each polygon are not being closed. Is there a simple solution in the SF package I'm missing?
Also, when creating the polygon, I'd like for the variable "data" to be associated with each polygon. I have not made it that far, however.