[GIS] Centroids of each grid cell

centroidsgrids-graticulesr

I have a grid created by mean the following script:

# My grid [using package 'sf']
worldGrid <- st_make_grid(x = worldMap, what = "polygons", cellsize = 10)
worldGrid <- st_sf(idcell = 1:length(worldGrid), geom = worldGrid) %>% 
st_cast("POLYGON")

What I want to obtain is a SpatialPolygonDataframe with tre columns:
idcell, LONG, LAT

where the coordinates 'LOG' and 'LAT' represent the longitude and latitude of the centroids of each cell of my grid, respectively.

Is that possible in R?

Best Answer

From your question I get that you want to create a raster that has the extent of the entire world. Here is a way that you can use in order to create the raster and find the centroids of each grid cell.

cs = 10.0 # grid cell size 
worldMap <- as( raster::extent(-180, 180, -90, 90), "SpatialPolygons") # Extent of grid to SpatialPolygons
wgs.84 <- "+proj=longlat +datum=WGS84 +no_defs +ellps=WGS84 +towgs84=0,0,0"
proj4string(worldMap) <- crs(wgs.84) 
class(worldMap)
plot(worldMap)
ras <- raster(worldMap, resolution = cs) # Create raster using the extent 
ras[] <- 1:ncell(r)
cat("\n", "Number of cells in raster: ", ncell(ras), "\n")  
mw <- as(ras, "SpatialPixelsDataFrame")
class(mw)
plot( as(mw, "SpatialPolygons") )

grid_center <- coordinates(mw) #Determine centroids of grid cells 
centers<- SpatialPoints(grid_ctr, proj4string = CRS(proj4string(e)))
plot(centers,add=T)