1
votes

I would like to obtain the extent of raster layer conditional on certain cell values. Consider the following example:

raster1 is a large raster object, filled with values between 1 and 1000. However, I only want to obtain the extent for pixels with value 100. Since this subset of cells should crowd in a small region, the extent should be rather narrow. Once I know the coordinates of that box, I can crop this minor area.

My approach so far is to replace all values != 100 with NA - as suggested in related questions. Considering the raster object's overall size, this step takes an enormous amount of time and invests a lot of computational capacity in regions that I would like to crop anyways.

Does anyone know how to obtain the extent conditional on a certain pixel value which does not require to reclassify the entire object beforehand?

1

1 Answers

1
votes

Here is an alternative way to do that

Example data:

library(raster)
r <- raster(ncol=18,nrow=18)
values(r) <- 1
r[39:45] <- 100
r[113:115] <- 100
r[200] <- 100

"Standard" way:

x <- r == 100
s <- trim(x, values=FALSE) 

Alternate route by creating an extent:

xy <- rasterToPoints(r, function(x){ x ==100 })  
e <- extent(xy[,1:2])
e <- alignExtent(e, r, snap='out')
v <- crop(r, e)

Either way, all cells need to be looked at, but at least you do not need to create another large raster.