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

r, raster

Solution

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`)

Problem

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?

Original source