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

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.


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
  fname <- gsub("MYD|MOD|13Q1_Rely_2019_", " ", 1:nlayers(px.mask))
  writeRaster(px.mask, file = paste0(fname), 
              bylayer=TRUE, format="GTiff")
  • please don't make substantive changes to your question when its been answered - make a new question instead.
    – Spacedman
    Commented Jul 19, 2019 at 18:16

2 Answers 2


With regard to the naming issue, I'm not sure what you are trying to do with gsub. You don't use any indexing in "fname" so the name isn't changing between iterations of your loop, which could be why you are getting this naming system. I'd suggest something like:

  fname <- paste0("filename_", i, ".tiff")

You are trying to loop over the single object pix, where pix is:

> pix
class      : RasterStack 
dimensions : 668, 1105, 738140, 22  (nrow, ncol, ncell, nlayers)

but R is a bit fussy about what you can loop over. For example you get the same error if you try and loop over a function:

> for(f in sqrt){f}
Error in for (f in sqrt) { : invalid for() loop sequence

If you want to loop over all layers of a raster stack then loop over the layer indexes:

> s = stack(list(raster(matrix(1:12,3,4)),raster(matrix(1:12,3,4))))
> for(i in 1:nlayers(s)){plot(s[[i]])}
  • I followed your advise and made some modification... my problem now is on the filename.
    – mand3rd
    Commented Jul 19, 2019 at 16:30

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.