Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

R: count non-NAs in a raster stack

Tags:

stack

r

raster

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.

like image 222
EDU Avatar asked Jun 25 '13 18:06

EDU


1 Answers

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.

like image 182
Oscar Perpiñán Avatar answered Oct 10 '22 04:10

Oscar Perpiñán