1

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?

  • 1
    I would use raster package for this, but try st_centroid(worldGrid) and then st_coordinates() on that to get a matrix. Using sf here is really round-about though, raster(xmn, xmx, ymn, ymn, nrow, ncol) and then coordinates() is far simpler. – mdsumner Jan 15 '18 at 20:54
  • Thanks for the rapid reply. Unfortunately, st_centroid() does not work. The error wich I obtain is: "st_centroid does not give correct centroids for longitude/latitude data" – Marco Jan 15 '18 at 20:58
  • 2
    That's not an error, it's a warning - can you confirm? Just ignore it, my take is that there's no such thing as "correct" for centroid, there are many definitions and different contexts and I think in your case it's obvious and uncontroversial. – mdsumner Jan 15 '18 at 21:12
  • It's just a warning on my system and it provides centroids without any other transforms: st_centroid(st_make_grid(x = st_as_sf(maps::map("world", fill=TRUE, plot=FALSE)), what = "polygons", cellsize = 10)) – hrbrmstr Jan 15 '18 at 21:16
  • Both of you are absolutely right: the code "st_centroid(worldGrid) " works, it was just a 'warning'. I obtain the coordinates, but only as matrix and not as SpatialPolygonDataframe. – Marco Jan 15 '18 at 21:24
0

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)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.