I want to create subsets of raster stacks and write them as new stacks when the difference between the previous layer and the next layer is all NA
. I.e., starting from layer 1, I want to create a subset of raster stacks until there are no-overlapping pixels between the previous and next layers (i.e., the difference between the two layers is all NA
) So I want is; starting from layer 1, retain all the layers that have at least 1 common pixel between the previous and next layer, write them as a 1 stack, and move to the next. Below are a sample data and unsuccessful for-loop. In this example, I want to retain layers 1:8, name and write them and start again from layer 9 and so on.
r <- raster(ncol=5, nrow=5)
set.seed(0)
#create raster layers with some values
s <- stack(lapply(1:8, function(i) setValues(r, runif(ncell(r)))))
s1<-extend(s,c(-500,100,-400,100))
#to recreate the condition I am looking for, create 2 layers with `NA` vlaues
s2 <- stack(lapply(1:2, function(i) setValues(r, runif(ncell(r)))))
s1e<-extend(s2,c(-500,100,-400,100))
s1e[]<-NA
#Stack the layers
r_stk<-stack(s1,s1e)
plot(r_stk)
#here is the sample code showing what i am expecting here but could not get
required_rst_lst<-list() # sample list of raster layers with overlapping pixels I am hoping to create
for ( i in 1: nlayers(r_stk))
# i<-1
lr1<-subset(r_stk,i)
lr1
lr2<-subset(r_stk,i+1)
lr2
diff_lr<-lr1-lr2
plot(diff_lr)
if ((sum(!is.na(getValues(diff_lr)))) ==0)) #??
required_rst_lst[[i]] #?? I want layers 1: 8 in this list
#because the difference in these layers in not NA