Search code examples
rterra

Finding cell loaction that satisfies a condition in SpatRaster


I have a multi-layer SpatRaster and would like to extract x, y, layer, and value information for cells that are greater than 200. I thought about using as.array or as.data.frame, but it will affect performance since it is a large SpatRaster.

Here is a reproducible example:

library(terra)
f <- system.file("ex/logo.tif", package="terra")
r <- rast(f, f) * * seq(1,2, by = 0.2)

Solution

  • To reduce memory needs you can first set the cells you do not want to NA, here using terra::clamp.

    x <- clamp(r, 200, values=FALSE)
    
    d <- as.data.frame(x, xy=TRUE)
    head(d)
    #    x    y lyr1 lyr2 lyr3 lyr4 lyr5 lyr6
    #1 0.5 76.5  255  306  357  408  459  510
    #2 1.5 76.5  255  306  357  408  459  510
    #3 2.5 76.5  255  306  357  408  459  510
    #4 3.5 76.5  255  306  357  408  459  510
    #5 4.5 76.5  255  306  357  408  459  510
    #6 5.5 76.5  255  306  357  408  459  510