library(sf)
library(raster)
nc <- sf::st_read(system.file("shape/nc.shp", package="sf"))
nc <- sf::st_cast(nc, "POLYGON")
#### multi-band
i=100; j=100
r <- do.call(raster::stack, replicate(20,
raster::raster(matrix(runif(i*j), i, j))))
names(r) <- paste0("time", 1:nlayers(r))
extent(r) <- extent(nc)
proj4string(r) <- st_crs(nc)$proj4string
plot(r[[1]])
plot(st_geometry(nc), add=TRUE)
( e <- polygon_extract(r, nc) )
( e <- polygon_extract(r, nc, ids="CNTY_ID") )
# Column means
lapply(e, function(x) apply(x[,2:ncol(x)], MARGIN=1, FUN=mean) )
#### Single band mean
( e <- polygon_extract(r[[1]], nc, ids="CNTY_ID") )
unlist(lapply(e, function(x) mean(x[,2], na.rm=TRUE) ))
# \donttest{
# Leveraging cell ids, pulls values, calculates
# new value, and assigns to source cell using
# index from cells = TRUE
e <- polygon_extract(r, nc, cells=TRUE)
e <- data.frame(
cells=unlist(lapply(e, function(x) as.numeric(x[,22]))),
means=unlist(lapply(e, function(x) apply(x[,2:22], MARGIN=1, FUN=mean)))
)
# copy raster and assign NA's
r2 <- r[[1]]
r2[] <- rep(NA, ncell(r))
# assign using cell indices
r2[e$cells] <- e$means
plot(r2)
# benchmark against raster extract
system.time({
e <- polygon_extract(r, nc)
})
system.time({
e <- raster::extract(r, nc)
})
# }
Run the code above in your browser using DataLab