R – Draw a Spatial Grid with the Lat/Longs at the Center of the Grid Using R

bufferpolygonrsfvector-grid

I looked through multiple posts on the same, and most of them end up drawing a grid connnecting the points or a grid connecting the bounding box of the coordinates.

I need a grid with each of these points at the centre of the grid. This is what I have so far:

library(sf)
library(ggplot2)

points <- data.frame(long = c(76.75,77.25,76.75,77.25,77.75),
                     lat = c(11.25,10.75,10.25,10.25,10.25)) %>% st_as_sf(coords=c('long','lat'), crs=4326)

a <- st_make_grid(points, what="polygons", cellsize=0.5)

ggplot() +
  geom_sf(data = points, color = 'red', size = 1.7) + 
  geom_sf(data = a, fill = 'transparent', lwd = 0.3) +
  coord_sf(datum = NA)  +
  labs(x = "") +
  labs(y = "")

s

Best Answer

Make a grid by extending the bounds of your points out by half a cell size in all directions:

> cellsize = 0.5
> g2 = st_make_grid(
         st_as_sfc(
           st_bbox(points) + 
              c(-cellsize/2, -cellsize/2,
                 cellsize/2, cellsize/2)),
        what="polygons", cellsize=cellsize)

Then your points are at the centres of your cells:

> plot(g2)
> plot(points, add=TRUE)

points centred on grid

Related Question