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?

有帮助吗?

解决方案

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)

其他提示

I do not understand why you would coerce to a matrix? Perhaps I do not understand your question but, if I get you correctly, you could just query the raster values and then coerce to points to get the geographic position(s).

require(raster)
r <- raster(ncols=100, nrows=100)
  r[] <- runif(ncell(r), 0,1)

# Coerce < max to NA and coerce result to points 
rMax <- r
m = maxValue(r) 
rMax[rMax != m] <- NA 
( r.pts <- rasterToPoints (rMax) )  

# You could also use the raster specific Which or which.max functions. 
i <- which.max(r)
  xy.max <- xyFromCell(r, i)
    plot(r)
      points(xy.max, pch=19, col="black")

# Or for a more general application of Which
i <- Which(r >= 0.85, cells=TRUE)
  xy.max <- xyFromCell(r, i)
    plot(r)
      points(xy.max, pch=19, col="black")

# If you prefer a raster object set cells=FALSE
i <- Which(r >= 0.85, cells=FALSE)
  plot(i)

There are multiple raster functions that will allow you to pass custom or base functions to them. You may want to take a look at "focal" which is a local operator or "calc" . You may want to also read through the help related to raster.

To extend Jeffrey's answer, you can select the last instance of the lowest raster value with the following:

r <- raster(ncols=12, nrows=12)
set.seed(0)
r[] <- round(runif(ncell(r))*0.7 )
rc <- clump(r)
rc[12,8]<-1
plot(rc)

xy.min<-data.frame(xyFromCell(rc,max(which.min(rc))))
xy.min$dat<-1
coordinates(xy.min)<-~x+y
points(xy.min,lwd=2)
许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top