Zonal statistics to get majority pixel value per polygon in R?

♀尐吖头ヾ 提交于 2020-01-15 09:53:50

问题


Actually I try to calculate the major pixel values from a raster with a SpatialPolygonsDataFrame. Here is some code I found which might lead in the right direction:

library(raster)
# Create interger class raster
r <- raster(ncol=36, nrow=18)
r[] <- round(runif(ncell(r),1,10),digits=0)
r[]<-as.integer(r[])
# Create two polygons
cds1 <- rbind(c(-180,-20), c(-160,5), c(-60, 0), c(-160,-60), c(-180,-20))
cds2 <- rbind(c(80,0), c(100,60), c(120,0), c(120,-55), c(80,0))
polys <- SpatialPolygonsDataFrame(SpatialPolygons(list(Polygons(list(Polygon(cds1)), 1), 
Polygons(list(Polygon(cds2)),2))),data.frame(ID=c(1,2)))

# Extract raster values to polygons                             
( v <- extract(r, polys) )

# Get class counts for each polygon
v.counts <-lapply(v,table)

So far everything is fine but I´m really stuck to extract the column name of the column which has the highest counts.

I tried things like:

v.max<- lapply(v.counts,max)

But there the column information gets lost. After:

v.max<- lapply(v.counts, max.col)

I get just "1" as result.

I´d appreciate if somebody can give me a hint what I´m doing wrong. Is there also another way to extract the major pixel values in a polygon?


回答1:


which.max() is your friend. Since you just want the names, use names().

sapply(v.counts, function(x) names(x)[which.max(x)])
# [1] "9" "5"

Note: set.seed(42)



来源:https://stackoverflow.com/questions/59554551/zonal-statistics-to-get-majority-pixel-value-per-polygon-in-r

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!