Hallie Sheikh
Hallie Sheikh

Reputation: 431

Finding percentage land cover classes in a shapefile in R

I have shapefile in R and a tiff file of land cover classes. How can I find the percentage of land cover classes in the shapefile? For instance how much land is present in the study area in that shapefile?

#example data for cover
rat <- levels(raster2 )[[1]]
rat[["landcover"]] <- c("land","ocean/lake", "rivers")
levels(raster2 ) <- rat

#and a raster
raster1 <-  raster(matrix(c(1,1,1,2,3,4,5,6,7),ncol =3))

Upvotes: 0

Views: 1137

Answers (2)

nxlouch
nxlouch

Reputation: 11

I have written an R package to do this.

Package name is SpatialCover and can be found on Github. It requires packages raster and sp.

The Percent.cov function will do what you need. You'll need to ensure that your polygon/shapefile has an ID field. If there are multiple polygons in the shapefile, Percent.cov will calculate the frequency of each cover type within each polygon individually.

  library(SpatialCover)
  library(raster)
  library(sp)
  library(rgdal)

  shapefile<- readOGR(dsn=wd, layer="filename.shp")
  lcraster<- raster("filepathname/rasterfilename.tif")

  FreqTable<- Percent.cov(vectorlayer=shapefile, rasterlayer=lcraster, zoneID=ID)

You should then get a table that looks something like this

zoneID CoverType PercentCover
1 Land 20
1 Ocean/Lake 70
1 Rivers 10

Hopefully this helps. There is also an example with the package.

Upvotes: 1

Robert Hijmans
Robert Hijmans

Reputation: 47071

Here is a minimal, self-contained, reproducible example:

Raster data

library(raster)
r <- raster(ncol=36, nrow=18)
set.seed(111)
values(r) <- sample(3, 18*36, replace=TRUE)

Polygon

cds1 <- rbind(c(-180,-20), c(-160,5), c(-60, 0), c(-160,-60), c(-180,-20))
polys <- spPolygons(cds1)

Solution

x <- extract(r, polys)
table(x)
#x
# 1  2  3 
#16  9 13 

Upvotes: 1

Related Questions