Multiple ifel statements to eliminate bad quality pixels from a SpatRaster

I am using NASA's Black Marble monthly nighttime light (NTL) product, VNP46A3. The data are in .h5 format and apart from the radiance product, they come with quality assurance (QA) data. I am using the All_Angle_Composite_Snow_Free radiance NTL image for my analysis. Using the below code I extracted the radiance image as well as the QA rasters:

library(terra)

wd <- "path/"

s <- sds(paste0(wd, "VNP46A3.A2018182.h06v05.001.2021125183820.h5"))

# extract single image as spatraster from h5
r <- s[5] # s[] are the radiance and QA rasters

writeRaster(r, paste0(wd, "NTL.tif"))

The next step is the preprocessing of the NTL images, i.e., to eliminate bad quality pixels. I am using the ifel function from the terra package in R to achieve this. There are 2 QA rasters:

  • Quality is a binary raster and the good quality pixels have the value of 0
  • Num is the number of observations being used to create the monthly raster and should have a value greater than 0

I want to create ifel statement(s) such as:

if the Quality = 0 and Num > 0 then keep the NTL raster values else set the NTL raster values to NULL.

I have tried to create 2 separate ifel statements and then combine the results but I am getting an error:

NTL <- rast(paste0(wd, "NTL.tif"))
Num <- rast(paste0(wd, "Num.tif"))
Quality <- rast(paste0(wd, "Quality.tif"))

r <- ifel(Quality = 0, NTL, NULL)
# Error in .local(test, ...) : argument "no" is missing, with no default

r1 <- ifel(Num > 0, NTL, NULL)
# Error in .local(test, ...) : argument "no" is missing, with no default

r <- ifel(Quality == 0 & Num > 0, NTL, NA)

This topic was automatically closed 7 days after the last reply. New replies are no longer allowed.

If you have a query related to it or one of the replies, start a new topic and refer back with a link.