Search code examples
rnatiffterra

How to check the NAflag value in `terra`


I need to know how NA values are coded in tif files because I am working with a program that cannot use tifs that have NAs coded as 0.

However, when using the NAflag() function in terra, I always get NaN as the output, even if I set NAflag() myself

Here's an example:

# Create a raster
test <- rast(x=matrix(c(1,1,1,1,1,0,0,0,0), nrow=3))

plot(test) # plotting shows 1s and 0s

# No NAflag set yet, returns NaN
NAflag(test)

# Set NAflag to 0
NAflag(test) <- 0

plot(test) # plotting shows 0s are now NA

# NAflag still returns NaN
NAflag(test)

Maybe I am misunderstanding how NAflag works. Is there another way to learn what value is being used as the NA value in a tif?


Solution

  • You can find that with terra::describe (a.k.a. GDALinfo)

    library(terra)
    f <- system.file("ex/elev.tif", package="terra")
    v <- grep("NoData Value", describe(f), value=TRUE)
    v
    #[1] "  NoData Value=-32768"
    
    strsplit(v, "=")[[1]][2] |> as.numeric()
    #[1] -32768
    

    NAflag is used to set this value prior to reading values from a file. For a SpatRaster with cell values in memory, it is always NaN.

    r <- rast(f)
    NAflag(r) <- 255
    NAflag(r) 
    #[1] 255
    

    You are correct that it does not read the original NAflag (NoData Value).