I have a raster like this one:
https://drive.google.com/drive/u/0/folders/1AEKu4TKpzJg95oXv8dxep24xpXaesr0F
I want to find the locations (can be the centroid or the bounding box of these cells) for the extreme values (minimum and maximum).
Here is a great answer on how to do it using stars
However, I wonder how to do it quickly using terra
There are the where.min
and where.max
, as well as the minmax
functions. Yet they return the cell-index and the value, not the coordinates though.
Best Answer
Read raster using
terra
:Get coords of minimum:
Breaking this down a bit,
where.min
returns the layer, cell number, and value there:If you have a multi-layer raster then you get the second column of the
where.min
:Make 3 layers:
Splash a zero into each of the first two layers:
Then see:
If you have multiple equal minima per layer, then you might want to record the layers alongside the locations...
Stick another zero in layer 2:
Get the
where.min
matrix and use column 2 to get the coords info and then splat the matrix on it as well usingcbind
: