rterra

Replace Inf, Inf in a Raster Stack


I can't seem to figure out how to replace all the Inf and -Inf in a raster stack

library(terra)
#> terra 1.7.29

nrows <- 10
ncols <- 10
set.seed(123) 
r1 <- rast(nrows = nrows, ncols = ncols, xmin = 0, xmax = 10, vals = sample(0:8, nrows * ncols, replace = TRUE))
r1 <- c(rep(list(r1), 10))  
values(r1[[4]]) <- NaN  
values(r1[[7]]) <- NaN 
r1 <- rast(r1)
r2 <- classify(r1, cbind(-Inf, 0, NA))

What am I doing wrong?


Solution

  • You can use terra::subst.

    Example data

    library(terra)
    #terra 1.8.0
    x <- rast(ncols=10, nrows=10, nlyr=2, vals=1:200)
    x[1] <- -Inf
    x[2] <- Inf
    

    Solution

    y <- subst(x, c(-Inf, Inf), NA)
    y[1:3]
    #  lyr.1 lyr.2
    #1    NA    NA
    #2    NA    NA
    #3     3   103
    

    You can also use classify (that is a bit less efficient)

    m <- cbind(c(-Inf, Inf), NA)
    z <- classify(x, m)
    z[1:3]
    #  lyr.1 lyr.2
    #1    NA    NA
    #2    NA    NA
    #3     3   103
    

    Or, the least efficient way, use ifel:

    ifel(is.finite(x), x, NA)
    #class       : SpatRaster 
    #dimensions  : 10, 10, 2  (nrow, ncol, nlyr)
    #resolution  : 36, 18  (x, y)
    #extent      : -180, 180, -90, 90  (xmin, xmax, ymin, ymax)
    #coord. ref. : lon/lat WGS 84 (CRS84) (OGC:CRS84) 
    #source(s)   : memory
    #names       : lyr.1, lyr.2 
    #min values  :     3,   103 
    #max values  :   100,   200