Skip to content

Instantly share code, notes, and snippets.

@mdsumner
Last active April 9, 2018 20:41
Show Gist options
  • Star 2 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save mdsumner/d0b26238321a5d2c2c2ba663ff684183 to your computer and use it in GitHub Desktop.
Save mdsumner/d0b26238321a5d2c2c2ba663ff684183 to your computer and use it in GitHub Desktop.
fast_extract <- function(x, y, ...) {
## BEWARE no extract options are respected
raster::extract(x, sfpoly_cells(x, y))
}
sfpoly_cells <- function(rast, sfpoly) {
## BEWARE, could be a big-data, this is not
## sparsely specified, so it's wasteful on memory, but fast (if you have the mem)
which(!is.na(fasterize::fasterize(sfpoly, rast)[]))
}
data("wrld_simpl", package = "maptools")
w <- raster(wrld_simpl, nrows = 150, ncols = 300)
w[] <- rnorm(prod(dim(w)))
p <- sf::st_as_sf(wrld_simpl)
system.time(fast_extract(w, p))
#user system elapsed
#0.041 0.000 0.042
system.time(raster::extract(w, wrld_simpl))
# user system elapsed
# 14.673 0.002 14.679
@mdsumner
Copy link
Author

If you are interested, this is WIP. It needs polygon grouping but that is trivial. Direct first use will be in tabularaster

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment