Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Raster grid position/coordinates of pixel(s) matching a value in R

Tags:

r

raster

Is there a way to extract the grid position or (preferably for rasters with an explicit extent) point/centroid coordinates of the pixels that match a particular value? I nearly have a pretty inefficient workflow converting to matrix and using which(mtrx == max(mtrx), arr.ind = TRUE) to get the matrix position(s), but this (a) loses geospatial information and (b) causes data to rotate 90 degrees in the matrix conversion process, both of which requiring extra code to make it work and slow the computations significantly. Is there an equivalent raster workflow anyone is aware of?

like image 870
geotheory Avatar asked Dec 05 '25 16:12

geotheory


1 Answers

Example data:

library(raster)
set.seed(0)
r <- raster(ncols=10, nrows=10)
r[] <- sample(50, 100, replace=T)

Now do:

p <- rasterToPoints(r, function(x) x == 11)

To get

       x   y layer
[1,]   18  81    11
[2,] -126  63    11
[3,]  -90  45    11
[4,]   54 -63    11

If you want the cell(s) with the maximum value

vmax = maxValue(r)
p <- rasterToPoints(r, function(x) all.equal(x, vmax)

(do not use @data@max)

like image 89
Robert Hijmans Avatar answered Dec 07 '25 05:12

Robert Hijmans



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!