rterra

How do I check with TRUE/FALSE return if there are NAs in a R SpatRaster?


I'm trying to check for NAs (missing values) in my SpatRaster (is a bioclimatic raster from CHELSA from ex [DOWNLOAD the raster 117MB] https://os.zhdk.cloud.switch.ch/chelsav2/GLOBAL/climatologies/1981-2010/bio/CHELSA_bio10_1981-2010_V.2.1.tif) but I can't find the function that returns TRUE if there are NAs or FALSE if there is no NA in my raster.

I try with anyNA function but it does not return a TRUE or FALSE response

r <- rast("~/Downloads/CHELSA_bio10_1981-2010_V.2.1.tif")
r
class       : SpatRaster 
dimensions  : 20880, 43200, 1  (nrow, ncol, nlyr)
resolution  : 0.008333333, 0.008333333  (x, y)
extent      : -180.0001, 179.9999, -90.00014, 83.99986  (xmin, xmax, ymin, ymax)
coord. ref. : lon/lat WGS 84 (EPSG:4326) 
source      : CHELSA_bio10_1981-2010_V.2.1.tif 
name        : CHELSA_bio10_1981-2010_V.2.1 

anyNA(r)
class       : SpatRaster                  
dimensions  : 20880, 43200, 1  (nrow, ncol, nlyr)
resolution  : 0.008333333, 0.008333333  (x, y)
extent      : -180.0001, 179.9999, -90.00014, 83.99986  (xmin, xmax, ymin, ymax)
coord. ref. : lon/lat WGS 84 (EPSG:4326) 
source      : spat_40430ebe563_1028.tif 
varname     : CHELSA_bio10_1981-2010_V.2.1 
name        : CHELSA_bio10_1981-2010_V.2.1 
min value   :                        FALSE 
max value   :                        FALSE 

Any ideas? Thanks in advance for help,


Solution

  • You already have the information within min and max values of results. Use minmax() function to retrieve it:

    library(terra)
    #> terra 1.8.3
    
    r <- rast(nrows=10, ncols=10, nlyrs=1)
    values(r) <- runif(ncell(r) * nlyr(r))
    anyNA(r) |>
      minmax() |>
      any() |>
      suppressWarnings()
    #> [1] FALSE
    
    set.seed(3)
    v <- values(r)
    v[sample(length(v), 10)] <- NA
    values(r) <- v
    anyNA(r) |>
      minmax() |>
      any() |>
      suppressWarnings()
    #> [1] TRUE
    

    And with your raster:

    r <- terra::rast("~/Downloads/CHELSA_bio10_1981-2010_V.2.1.tif")
    anyNA(r) |>
      minmax() |>
      any() |>
      suppressWarnings()
    #> [1] FALSE
    

    Created on 2024-12-17 with reprex v2.1.1.9000