Question

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)
Was it helpful?

Solution 2

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)))

OTHER TIPS

Here is another approach. If all values are NA, the minimum value is also NA. So you can do:

 i <- !is.na(minValue(s))
 s_no_na <- s[[i]]

This could be very fast if the minValue is known (otherwise it needs to be computed).

I prefer this approach, which is a bit short and sweet:

result <- rasters[!sapply(rasters, is.null)]
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top