问题
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