0

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")
}
  • please don't make substantive changes to your question when its been answered - make a new question instead. – Spacedman Jul 19 at 18:16
0

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)
[etc]

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 Jul 19 at 16:30

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

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