Become an expert in R — Interactive courses, Cheat Sheets, certificates and more!
Get Started for Free

zonal.stats

zonal.stats


Description

Polygon zonal statistics of a raster

Usage

zonal.stats(x, y, stats = c("min", "mean", "max"))

Arguments

x

Polygon object of class SpatialPolygonsDataFrame

y

rasterLayer object of class raster

stats

Statistic or function

Value

data.frame, nrow(x) and ncol of function results

Note

This function calculates the zonal statistics between a polygon vector object and a raster. This provides the advantage of being able to accept any custom function, passed to the 'stats' argument. Please note that any custom function needs to have a 'na.rm' argument.

Author(s)

Jeffrey S. Evans <jeffrey_evans@tnc.org>

Examples

library(raster)
library(sp)                                                                          

# skewness function
skew <- function(x, na.rm = FALSE) { 
   if (na.rm) 
       x <- x[!is.na(x)]
  sum( (x - mean(x)) ^ 3) / ( length(x) * sd(x) ^ 3 )  
  }   

# percent x >= p function
pct <- function(x, p=0.30, na.rm = FALSE) {
  if ( length(x[x >= p]) < 1 )  return(0) 
    if ( length(x[x >= p]) == length(x) ) return(1) 
     else return( length(x[x >= p]) / length(x) ) 
}

# create some example data
p <- raster(nrow=10, ncol=10)
  p[] <- runif(ncell(p)) * 10
    p <- rasterToPolygons(p, fun=function(x){x > 9})
      r <- raster(nrow=100, ncol=100)
        r[] <- runif(ncell(r)) 
plot(r)
  plot(p, add=TRUE, lwd=4) 

# run zonal statistics using skew and pct functions   
z.skew <- zonal.stats(x = p, y = r, stats = "skew") 
z.pct <- zonal.stats(x=p, y=r, stats = "pct")
  ( z <- data.frame(ID = as.numeric(as.character(row.names(p@data))), 
                    SKEW=z.skew, PCT=z.pct) )

spatialEco

Spatial Analysis and Modelling Utilities

v1.3-6
GPL-3
Authors
Jeffrey S. Evans [aut, cre], Melanie A. Murphy [ctb], Karthik Ram [ctb]
Initial release
2021-03-24

We don't support your browser anymore

Please choose more modern alternatives, such as Google Chrome or Mozilla Firefox.