Skip to content

Instantly share code, notes, and snippets.

@johnbaums
Last active September 3, 2019 14:01
Show Gist options
  • Save johnbaums/10ab50459b897e8b2260a7eb62f565f5 to your computer and use it in GitHub Desktop.
Save johnbaums/10ab50459b897e8b2260a7eb62f565f5 to your computer and use it in GitHub Desktop.
Return a list of extents for each cell in a raster
cellBoundaries <- function(r, spatial=TRUE) {
# r: a Raster object
# spatial: return an sfc object (TRUE) or a list of extents (FALSE)
require(raster)
if(isTRUE(spatial)) require(sf)
ee <- lapply(seq_along(r), function(i) {
cat(sprintf('\r%0.2f%%', 100*i/ncell(r)))
e <- extentFromCells(r, i)
if(isTRUE(spatial)) {
e <- st_as_sfc(st_bbox(e))
e <- st_set_crs(e, projection(r))
}
e
})
if(isTRUE(spatial)) do.call(c, ee) else ee
}
# Can use raster::rasterToPolygons(r) for this, but will only return
# polys for non-NA cells, so may need to `r2 <- raster(r); r2[] <- 1`
# first.
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment