I have one raster which is split in several patches, which one having a special ID, so each cell will be identified by the ID of the patch they belong. In the example below, I have 1180 patches. I calculated the area of all those patches and I'd like to select only those which are > 100 ha. Here is my code, but the problem is that R gives a vector at the end and not a raster containing only those patches with the criteria.
# list of ID of patches (hors NA)
num_patches <- unique(raster[!is.na(raster[])]) # list length= 1180
area_patches <- c()
# calculate area
for (pixel in num_patches){
area_patches <- c(area_patches ,sum(raster[raster == pixel]) * res(raster)[1]^2)
}
# conversion des m² en ha
area_patches <- area_patches/ha
# identify patches > 100
pos_patches_100ha <- which(area_patches >= 100)
# select only patches > 100 ha
raster <- raster[raster %in% pos_parche_100ha] --> selection doesn't work, the out isn't a raster but a vector
If cell values are the IDs and you know which IDs correspond to patches of 100 ha or less, you can simply set them to NA or whatever is the background value in that case:
r[r %in% ids_to_delete] <- NA
This assumes the raster layer to be called r
and ids_to_delete
to be a vector of IDs to set to NA.