How can I get the the total area of my land cover classes 1,2,3,4,5 given the following example:
library("raster")
r <- raster(nrow=10, ncol=10)
r<-setValues(r,c(rep(1,20),rep(2,20),rep(3,20),rep(4,20),rep(5,20)))
One approach might be to subset the raster based on these values, however somethig like a <- area(r[getValues(r)==1])
did not work neither did a <- area(r[r==1])
.
There is a solution provided on this website, however it requires creating new raster layers for each value to be analyzed. I would prefer rather not to do so since my original raster contains lots of different values and is very large. A similar approach is presented here, however it works only for small regions.
You can use the base function aggregate
on the areas grouped by the values in r and sum them up.
aggregate(getValues(area(r, weights=FALSE)), by=list(getValues(r)), sum)
Group.1 x
1 1 48166136
2 2 126933351
3 3 320336528