Get patch size in R terra

rterra

I would like to get the patch sizes in a R terra object, and then filter patches above a threshold.

How do I get patch sizes in terra (and then filter)? The only output I see is patch ID (see plot).

f <- system.file("ex/elev.tif", package="terra")
r <- rast(f)
x=app(r,function(x) ifelse(x< 400,NA,x))
y=patches(x)
plot(y)

enter image description here

Best Answer

It is best to avoid using x[] with SpatRasters as that forces all data into memory. That works fine on these examples, but may fail with your real data. In this case, you can use zonal in stead.

You example data:

library(terra)
f = system.file("ex/elev.tif", package="terra")
r = rast(f)
x = classify(r, cbind(-Inf, 400, NA))
y = patches(x)

To count the number of cells by patch

f = freq(y)
head(f)
#     layer value count
#[1,]     1     1   866
#[2,]     1     2     3
#[3,]     1     3     1
#[4,]     1     4     7
#[5,]     1     5     1
#[6,]     1     6     1

If you want the area covered by these cells, first use cellSize

z = cellSize(y,unit="km") |> zonal(y, sum)
head(z) |> round(2)
#  patches   area
#1       1 479.33
#2       2   1.66
#3       3   0.55
#4       4   3.88
#5       5   0.55
#6       6   0.55