Search code examples
rgeolocationgeospatialr-sfrgdal

How to create a spatial gridlines using Latitude and Longitude in R


How to create a gridline of 7*7 sqkm using Latitude and Longitude values. These values should be the centroid value of a single square in the grid. I am not sure if I am doing it in the right way. I tried st_make_grid from sf (Simple Features) library but that shows me an empty plot.

MyGrid <- st_make_grid(DF, cellsize = c(0.07, 0.07), square = TRUE, crs = 4326) 

Below is my example DF

DF <- structure(list(lat = c(43.25724, 43.25724, 43.25724, 43.25616, 
43.25616, 43.25616), lon = c(-96.01955, -95.98172, -95.92336, 
-96.40973, -96.25733, -96.17735)), class = "data.frame", row.names = c(NA, 
6L))
## > DF
##        lat       lon
## 1 43.25724 -96.01955
## 2 43.25724 -95.98172
## 3 43.25724 -95.92336
## 4 43.25616 -96.40973
## 5 43.25616 -96.25733
## 6 43.25616 -96.17735

Thanks


Solution

  • from the documentation of st_make_grid:

    Create a square or hexagonal grid covering the bounding box of the geometry of an sf or sfc object

    • so you need to convert your dataframe of point coordinates to an sf-object "the_points" (and reproject to a projection accepting metric length units):
    library(sf)
    
    the_points <- 
        st_sf(geometry = DF[c('lon', 'lat')] |>
                  as.matrix() |>
                  st_multipoint() |>
                  st_sfc() |>
                  st_cast('POINT'),
              crs = 4326 ## geographic data (in degrees)
              ) |>
        ## convert to projected coordinates (to specify dimensions in m
        ## take Google Mercator as first guess (EPSG-code 3857)
        st_transform(3857)
    
    • create grid (note that your points have only about 100 m latitudinal range):
    the_grid <- 
        st_make_grid(n = c(10, 1), cellsize = 7e3 ## 7000 km)
    
    • inspect result:
    plot(the_grid)
    plot(the_points, add = TRUE)
    

    st_make_grid result