简体   繁体   English

计算超过阈值的三个连续值的数量(在栅格堆栈中)

[英]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 ). 当栅格堆栈( x )中每个像素的值都超过给定阈值(由另一个栅格y定义)时,我需要计算连续三天的数量。 I tried using rle for the purpose with calc as follows after stacking x and y together into new raster a : 在将xy一起堆叠到新的栅格a之后,我尝试将rle用于calc ,如下所示:

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) : .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. 有人可以帮忙吗?

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 ! HTH!

Based on Lorenzo's answer I modified the code and this is exactly what I was looking for. 根据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)

But since my solution is based on your answer, so I accept your answer Lorenzo. 但是由于我的解决方案基于您的答案,所以我接受您的答案Lorenzo。 Thanks! 谢谢!

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM