1
votes

This question was asked once in the past (from what I could find), but the only response did not provide a solution. Within a RasterStack, I want to generate summary statistics for each raster (min, max, mean, SD), AND the number of cells included in these calculations (i.e., non-NA cell count). You might think the number would be the same for every raster if they are all the same extent and resolution, but these rasters have been masked by their respective QA layers, resulting in a different number of non-NA cells in each raster layer. I've been using cellStats, but that does not provide cell count as output. I could also use zonal stats, but that does not appear to have this functionality (from what I read). Does anyone know how to add this to my output?

Thanks

1

1 Answers

0
votes

I think you are looking for the freq function. This function will give you the frequency of pixels by value. Here is one way you could calculate the number of non-NA pixels with some dummy data.

library(raster)

#Create 2 matrix
m1<-matrix(sample(1:10, 250, replace = T), 
           nrow = 50, 
           ncol = 50)
m2<-matrix(sample(11:20, 250, replace = T), 
           nrow = 50, 
           ncol = 50)

#Transform it to stack
r1 <- stack(raster(m1), raster(m2))

#Set pixel values == 3 and == 12 as NA
r1[r1 ==3 | r1 == 12]<-NA

#Get your cellStats
cellStats(r1, stat = "mean")

#Transform non-NA values to 1
r1[!is.na(r1)]<-1

#Get frequency of pixels by value
#1's will be the number of non-NA pixels
freq(r1)