Learn R Programming

spatialEco (version 0.1-5)

zonal.stats: zonal.stats

Description

Polygon zonal statistics of a raster

Usage

zonal.stats(x, y, stat, trace = TRUE, plot = TRUE)

Arguments

x
Polygon object of class SpatialPolygonsDataFrame
y
Raster object of class raster
stat
Statistic or function
trace
Should progress counter be displayed
plot
Should subset polygons/rasters be plotted (TRUE/FALSE)

Value

Vector, length of nrow(x), of function results

Examples

Run this code
                                                                      
# 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) {
  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
library(raster)
library(sp)   
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, stat=skew, trace=TRUE, plot=TRUE) 
z.pct <- zonal.stats(x=p, y=r, stat=pct, trace=TRUE, plot=TRUE)
  ( z <- data.frame(ID=as.numeric(as.character(row.names(p@data))), 
                    SKEW=z.skew, PCT=z.pct) )  

Run the code above in your browser using DataLab