R Extract – How to Find Min and Max Value Locations of Raster’s Centroid Using Terra

extractrterra

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:

r = rast("au.tif")

Get coords of minimum:

xyFromCell(r, where.min(r)[2])

##           x      y
## [1,] 377500 393500

Breaking this down a bit, where.min returns the layer, cell number, and value there:

> where.min(r)
     layer   cell   value
[1,]     1 101114 1265075

If you have a multi-layer raster then you get the second column of the where.min:

Make 3 layers:

> r3 = c(r,r,r)

Splash a zero into each of the first two layers:

> r3[100,100,1]=0
> r3[200,200,2]=0

Then see:

> xyFromCell(r3, where.min(r3)[,2])
          x      y
[1,] 211500 470500
[2,] 311500 370500
[3,] 377500 393500

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:

> r3[200,100,2]=0

Get the where.min matrix and use column 2 to get the coords info and then splat the matrix on it as well using cbind:

> wm = where.min(r3)
> cbind(xyFromCell(r3, wm[,2]), wm)
          x      y layer   cell   value
[1,] 211500 470500     1  56827       0
[2,] 211500 370500     2 114127       0
[3,] 311500 370500     2 114227       0
[4,] 377500 393500     3 101114 1265075