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