Learn R Programming

disaggregation (version 0.1.4)

parallelExtract: Parallel extraction of raster stack by shape file.

Description

Parallelisation is performed across rasters, not shapes. So this function is only useful if you are extracting data from many raster layers. As the overhead for parallel computation in windows is high it only makes sense to parallelise in this way.

Usage

parallelExtract(raster, shape, fun = mean, id = "OBJECTID", ...)

Value

A data.frame with columns of polygon id, cell id (if fun = NULL) and a column for each raster in the stack

Arguments

raster

A RasterBrick or RasterStack object.

shape

A SpatialPolygons object.

fun

The function used to aggregate the pixel data. If NULL, raw pixel data is returned.

id

Name of column in shape object to be used to bind an ID column to output.

...

Other arguments to raster::extract.

Examples

Run this code
 if (FALSE) {
  polygons <- list()
  for(i in 1:100) {
    row <- ceiling(i/10)
    col <- ifelse(i %% 10 != 0, i %% 10, 10)
    xmin = 2*(col - 1); xmax = 2*col; ymin = 2*(row - 1); ymax = 2*row
    polygons[[i]] <- rbind(c(xmin, ymax), c(xmax,ymax), c(xmax, ymin), c(xmin,ymin))
  }

  polys <- do.call(raster::spPolygons, polygons)
  response_df <- data.frame(area_id = 1:100, response = runif(100, min = 0, max = 10))
  spdf <- sp::SpatialPolygonsDataFrame(polys, response_df)

  r <- raster::raster(ncol=20, nrow=20)
  r <- raster::setExtent(r, raster::extent(spdf))
  r[] <- sapply(1:raster::ncell(r), function(x) rnorm(1, ifelse(x %% 20 != 0, x %% 20, 20), 3))
  r2 <- raster::raster(ncol=20, nrow=20)
  r2 <- raster::setExtent(r2, raster::extent(spdf))
  r2[] <- sapply(1:raster::ncell(r), function(x) rnorm(1, ceiling(x/10), 3))
  cov_rasters <- raster::stack(r, r2)

  cl <- parallel::makeCluster(2)
  doParallel::registerDoParallel(cl)
  result <- parallelExtract(cov_rasters, spdf, fun = NULL, id = 'area_id')
  parallel::stopCluster(cl)
  foreach::registerDoSEQ()
 }

Run the code above in your browser using DataLab