spatialEco (version 1.3-2)

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

Examples

Run this code
# NOT RUN {
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) )  

# }

Run the code above in your browser using DataCamp Workspace