Plot filtered patch sizes in R terra

rterra

I would like to plot patch sizes above a threshold in R terra.

f=system.file("ex/elev.tif", package="terra")
r=rast(f)
x=app(r,function(x) ifelse(x< 400,NA,x))
y=patches(x)
z=tapply(cellSize(y,unit="ha")[], y[], sum)
filtered=z[z>100]

The "filtered" variable contains patches larger than 100 ha. How do I plot them in terra?

Best Answer

The filtered variable is a table of patch numbers and areas. The names of the table are the patch numbers.

To plot a map of TRUE/FALSE for those patches, do a boolean (logical) operator to see which values of y are in that set:

plot(y %in% as.numeric(names(filtered)))

enter image description here

or if you want a raster with those patches and their patch values (first I've made a copy so I don't stomp on y), set all that arent in the set to NA:

yf = y
yf[!yf %in% as.numeric(names(filtered))] = NA
plot(yf)

enter image description here