计算高于阈值的三个连续值的数量(在光栅堆栈中)

时间:2016-11-07 14:46:57

标签: r stack raster r-raster run-length-encoding

当栅格堆栈(x)中每个像素的值高于给定阈值(由另一个栅格y定义)时,我需要计算连续三天的数量。在将rlecalc堆叠到新的栅格x之后,我尝试将y用于a,如下所示:

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

但是,我收到错误:

  

.calcTest(x [1:5],有趣,na.rm,forcefun,forceapply)出错:
  不能使用此功能

可重复的样本:

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)

有人可以帮忙。

2 个答案:

答案 0 :(得分:0)

你可以试试这个:

 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)

(请注意,我修改了示例数据集以获得一些好的序列)

HTH!

答案 1 :(得分:0)

根据Lorenzo的回答,我修改了代码,这正是我所寻找的。

# 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)

但由于我的解决方案是基于你的答案,所以我接受你的回答洛伦佐。谢谢!