【问题标题】:Calculating number of three consecutive values above a threshold (in raster stack)计算超过阈值的三个连续值的数量(在光栅堆栈中)
【发布时间】:2017-03-20 23:04:00
【问题描述】:

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

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

但是,我得到了错误:

.calcTest(x[1:5], fun, 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)

有人可以帮忙吗。

【问题讨论】:

  • 请给出一个可重现的例子(你需要dput()一些样本数据)。将指针悬停在 r 标签上以了解更多信息。
  • @Hack-R 我已经相应地编辑了问题。

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


【解决方案1】:

你可以试试这个:

 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 作为所有像素的值:(
  • 不知道......在测试数据集上,我认为代码正在做它应该做的......你的输入数据中是否有 NAs ?跨度>
【解决方案2】:

根据 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)

但是由于我的解决方案是基于您的回答,所以我接受您的回答 Lorenzo。谢谢!

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2014-08-29
    • 2020-10-02
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-12-03
    • 1970-01-01
    • 2019-07-22
    相关资源
    最近更新 更多