Search code examples
rrasternaterra

How to create a new raster in terra with same NA cells?


I need to create some new rasters by assigning values using z <- rast(x, vals = y). I would like the new raster (z) to have NA values at the same location as the old raster (x), but with the newly assigned value(s) (y) in the non-NA cells.

What is the most efficient way to create a new raster with a matching NA pixels but with new values assigned to the non-NA pixels?

I don't see any argument to handle NA values listed in the documentation for rast(), so do I need to do a two step process where the value is first assigned to all cells and then NAs are transfered from the old raster to new?

In the following example I would like s to have the same outline as r but have a uniform value of 10 in the non-NA cells.

f <- system.file("ex/elev.tif", package="terra")
r <- rast(f)
s <- rast(r, vals=10) # This fill all rasters cells, including NAs

Solution

  • Here are four ways to do that:

    library(terra)
    f <- system.file("ex/elev.tif", package="terra")
    r <- rast(f)
    
    s1 <- classify(r, cbind(-Inf, Inf, 10))
    s2 <- init(r, 10) |> mask(r)
    s3 <- ifel(is.na(r), NA, 10)
    s4 <- r * 0 + 10
    

    I would expect approach 1 and 4 to be the most efficient.