I've a RasterStack with several thousand layers. However, some of the layers have a lot of NAs so I would to exclude those layers by setting a threshold. I did it correctly using a for loop, but this is very slow. I was trying to do it with calc, but my function failed. Here are my trials and I would appreciate any hint in order to make the processing faster.
library(raster)
lst<-stack(r1,r2,r3,r4) #
lst_new<-stack()
for (i in 1: nlayers(lst)){
# total number of cells without NA
no_NA<-length(lst[[i]][!is.na(lst[[i]])]) #
if(no_NA >= 14652){ # 97%
l<-lst[[i]]
lst_new<-stack(lst_new,l)
}
}
#This code works OK but slow for big rasterstack. So I tried the
# following using calc function
remove.badL<-function(x){
no_NA<-length(x[is.na(x)])
if(no_NA >= 14652){
return(x)
}
}
lst_new<-calc(lst,fun=remove.badL)
# this is the error I got
Error in (function (classes, fdef, mtable) : unable to find an inherited method for function ‘writeValues’ for signature ‘"RasterBrick", "NULL"’
I would appreciate any suggestions. Thanks