5
votes

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.

3

3 Answers

7
votes

The raster package defines methods for is.na and sum so you can use them directly:

rNA <- sum(!is.na(stacka))    

The result is a RasterLayer:

> rNA
class       : RasterLayer 
dimensions  : 3, 3, 9  (nrow, ncol, ncell)
resolution  : 0.3333333, 0.3333333  (x, y)
extent      : 0, 1, 0, 1  (xmin, xmax, ymin, ymax)
coord. ref. : NA 
data source : in memory
names       : layer 
values      : 1, 4  (min, max)

> as.matrix(rNA)
     [,1] [,2] [,3]
[1,]    4    4    3
[2,]    4    4    1
[3,]    4    4    2

You should try calc if you need more sophisticated functions.

6
votes

You can use getValues and rowSums:

 rowSums(!is.na(getValues(stacka)))
 4 4 3 4 4 1 4 4 2

And to format it as a matrix

matrix(rowSums(!is.na(getValues(stacka))),ncol=3,byrow=TRUE)
     [,1] [,2] [,3]
[1,]    4    4    3
[2,]    4    4    1
[3,]    4    4    2

FYI ,

getValues(stacka)
      layer.1 layer.2 layer.3 layer.4
 [1,]       1       2       3       4
 [2,]       1       2       3       4
 [3,]       1       2      NA       4
 [4,]       1       2       3       4
 [5,]       1       1       3       4
 [6,]       1      NA      NA      NA
 [7,]       1       2       3       4
 [8,]       1       2       2       4
 [9,]      NA       2      NA       4
3
votes

Here's one way:

apply(as.array(stacka), 1:2, function(x) length(na.omit(x)))
#      [,1] [,2] [,3]
# [1,]    4    4    3
# [2,]    4    4    1
# [3,]    4    4    2