rar
rar

Reputation: 924

Calculating number of three consecutive values above a threshold (in raster stack)

I need to compute number of three consecutive days when value of each pixel in a raster stack (x) is above a given threshold (defined by another raster y). I tried using rle for the purpose with calc as follows after stacking x and y together into new raster a:

library(raster)    
fn<-function(a) with(rle(a), sum(lengths>=3 & values>a[[nlayers(a)]]))
calc(b,fn)

However, I am getting the error:

Error in .calcTest(x[1:5], fun, na.rm, forcefun, forceapply) :
cannot use this function

Reproducible sample:

x1 <- raster(nrows=10, ncols=10)
 x2=x3=x4=x5=x6=x1
 x1[]= runif(ncell(x1))
 x2[]= runif(ncell(x1))
 x3[]= runif(ncell(x1))
 x4[]= runif(ncell(x1))
 x5[]= runif(ncell(x1))
 x6[]= runif(ncell(x1))
 x=stack(x1,x2,x3,x4,x5,x6)
 y=x1
 y[]= runif(ncell(x1))
 a<-stack(x,y)

Can someone please help.

Upvotes: 0

Views: 863

Answers (2)

rar
rar

Reputation: 924

Based on Lorenzo's answer I modified the code and this is exactly what I was looking for.

# create data
x1 <- raster(nrows=2, ncols=2)
x2=x3=x4=x5=x6=x1
x1[]= runif(ncell(x1))
x2[]= runif(ncell(x1))
x3[]= runif(ncell(x1))
x4[]= runif(ncell(x1))
x5[]= runif(ncell(x1))
x6[]= runif(ncell(x1))
x=stack(x1,x2,x3,x4,x5,x6)*4
y=x1
y[]= runif(ncell(x1))*2

#Overlay to get greater than values raster (in form of TRUE and FALSE)
a<-overlay(x,y,fun=function(x,y){x>y})
# function for finding total number of 3 consecutive days when condition is TRUE     
fn<-function(a) {
      seq <- rle(a)
      n=sum(seq$lengths[seq$lengths>=3 & seq$values==TRUE])
      return(n)
    }
    calc(a,fn)

But since my solution is based on your answer, so I accept your answer Lorenzo. Thanks!

Upvotes: 0

lbusett
lbusett

Reputation: 5932

You could try this:

 x1 <- raster(nrows=10, ncols=10)
 x2=x3=x4=x5=x6=x1
 x1[]= runif(ncell(x1))
 x2[]= runif(ncell(x1))
 x3[]= runif(ncell(x1))
 x4[]= runif(ncell(x1))
 x5[]= runif(ncell(x1))
 x6[]= runif(ncell(x1))
 x=stack(x1,x2,x3,x4,x5,x6)*4
 y=x1
 y[]= runif(ncell(x1))*2
 a<-stack(x,y)


 library(raster)

fn<-function(x) {
  seq <- rle(as.numeric(x)>as.numeric(x)[[nlayers(a)]])
  n = length(seq$lengths > 3 & seq$values == TRUE)
  return(n)
}
calc(a,fn)

class       : RasterLayer 
dimensions  : 10, 10, 100  (nrow, ncol, ncell)
resolution  : 36, 18  (x, y)
extent      : -180, 180, -90, 90  (xmin, xmax, ymin, ymax)
coord. ref. : +proj=longlat +datum=WGS84 +ellps=WGS84 +towgs84=0,0,0 
data source : in memory
names       : layer 
values      : 1, 7  (min, max)

(note that I modified the example dataset to get some good sequences)

HTH !

Upvotes: 0

Related Questions