I'm trying to create a mask using each layer of my stacked Pixel Reliability QA rasters in R. I'm trying to exclude pixels with values greater than 1. I will use them to mask my vegetation index time-series layers. I tried for one layer and it worked with this code:
rely_ts <- load("Rely/MOD13Q1_MYD13Q1_Rely_1_2019_169_2019_RData.RData")
rely_ts <- get(rely_ts)
test_pix <- raster(rely_ts, layer=4)
test_pix[test_pix>1] <- NA
plot(test_pix, main="Pixel Reliability < 1")
Being new in coding with R, I am still struggling to do loops. I tried this code below but no go:
pix <- load("Rely/MOD13Q1_MYD13Q1_Rely_1_2019_169_2019_RData.RData")
pix <- get(pix)
for (aPix in pix){
aPix[aPix>1] <- NA
plot(aPix)
}
I get this error and I don't know what to do with it:
Error in for (aPix in pix) { : invalid for() loop sequence
RData files are accessible HERE for testing.
UPDATE:
I followed @Spacedman's advise as I understood it. I was able to create and write my masks, however it doesn't follow the filename that I want... the filenames created are "1.tif" to "22.tif". Here's my code:
pix <- load("Rely/MOD13Q1_MYD13Q1_Rely_1_2019_169_2019_RData.RData")
px.mask <- get(pix)
for(i in 1:nlayers(px.mask)){
px.mask[[i]][px.mask[[i]]>1] <- NA
#plot(px.mask[[i]])
fname <- gsub("MYD|MOD|13Q1_Rely_2019_", " ", 1:nlayers(px.mask))
writeRaster(px.mask, file = paste0(fname),
bylayer=TRUE, format="GTiff")
}