Last active
September 3, 2019 14:01
-
-
Save johnbaums/10ab50459b897e8b2260a7eb62f565f5 to your computer and use it in GitHub Desktop.
Return a list of extents for each cell in a raster
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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