I need to count the number of non-NA values in each grid cell in a raster stack. For example:
library(raster)
a1<-c(1,1,1,1,1,1,1,1,NA)
a2<-c(2,2,2,2,1,2,2,NA,2)
a3<-c(3,3,3,3,3,2,NA,NA,NA)
a4<-c(4,4,4,4,4,4,4,NA,4)
matrixa1<-matrix(a1,3,3)
matrixa2<-matrix(a2,3,3)
matrixa3<-matrix(a3,3,3)
matrixa4<-matrix(a4,3,3)
rastera1<-raster(matrixa1)
rastera2<-raster(matrixa2)
rastera3<-raster(matrixa3)
rastera4<-raster(matrixa4)
stacka<-stack(rastera1,rastera2,rastera3,rastera4)
In the end it should come up with a raster with number of valid value (non-NAs) like
4 4 3
4 4 1
4 4 2
Update: yes the final raster should have same extent as original stack.