Search code examples
rrasterna

How to automatically remove an empty raster from a rasterstack in r?


For my research I create rasterstack of satellite data of an area with a lot of ice, because of this, a lot of images are completely filled with NA's. These i would like to remove from the stacks automatically.

Suppose I have a rasterstack ,

r <- raster(nrow=10, ncol=10)
s1 <- s2<- list()
for (i in 1:12) {
  s1[i] <- setValues(r, rnorm(ncell(r), i, 3) )
  s2[i] <- setValues(r, rnorm(ncell(r), i, 3) )
}
s1 <- stack(s1)
s3 <- subset(s1,1) 
s3[] <- NA
s2 <- stack(s2)

# regression of values in one brick (or stack) with another
s <- stack(s1,s3, s2)

The middle image, image 13, is completely NA, now I could delete this using the subset function, but how could I get r to remove this layer automatically, so I get the same as;

s_no_na <- stack(s1,s2)

Solution

  • What do you mean by "automatically"? You have to test for it.

    Try testing each raster with something like !any(is.na(values(s))) or all(is.na(values(s))) where s is a raster. Put that in a loop in a function that builds your final stack.

    If you want a one-liner, this uses Filter to select from a list, and then do.call to apply stack to the filtered list:

    sf = do.call(stack, Filter(function(e){!all(is.na(values(e)))},list(s1,s3,s2)))