Skip to content

Instantly share code, notes, and snippets.

@srgorelik
Created October 31, 2018 19:03
Show Gist options
  • Save srgorelik/f4682bae09cdeed53fa03a086c70e380 to your computer and use it in GitHub Desktop.
Save srgorelik/f4682bae09cdeed53fa03a086c70e380 to your computer and use it in GitHub Desktop.
Extract grid cells from different layers in a raster stack in R.
extractCellsFromLayers <- function(stack, index) {
# --------------------------------------------------------------------------------
# Purpose:
# Extract grid cells from different layers in a raster stack.
#
# Arguments:
# stack A RasterStack object; the stack from which to extract cell values.
# index A RasterLayer object; the index used to extract cells from the
# stack. Cell values in the index raster indicate from which layer
# in the raster stack to extract the corresponding cell values.
#
# Author:
# Seth Gorelik - October 2018
# --------------------------------------------------------------------------------
require(raster)
if (class(stack) != 'RasterStack') stop(paste0('object "', deparse(substitute(stack)), '" must be a RasterStack.'))
if (class(index) != 'RasterLayer') stop(paste0('object "', deparse(substitute(index)), '" must be a RasterLayer.'))
if (cellStats(index, 'max') > nlayers(stack)) stop('index references layer(s) not found in stack.')
new.raster <- index * 0
tmp.df <- as.data.frame(stack)
new.raster[] <- tmp.df[cbind(1:ncell(index), getValues(index))]
return(new.raster)
}
@srgorelik
Copy link
Author

Conceptual Diagram

method_ann

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