2016-11-07 82 views
0

當柵格堆棧中的每個像素的值(x)高於給定閾值(由另一個柵格y定義)時,我需要計算連續三天的連續天數, 。我試着用rle爲宗旨,以calc如下堆疊xy彙集成新的光柵a後:計算閾值之上的三個連續值(光柵堆棧中)的數量

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

不過,我得到的錯誤:

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

重複的樣品:

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) 

有人可以請幫忙。

+0

請給出一個可重現的例子(你需要'輸入()'一些示例數據)。將指針懸停在「r」標籤上以獲取更多信息。 –

+0

@ Hack-R我已經編輯了相應的問題。 – rar

回答

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!

+0

嘿謝謝!這段代碼工作得很好。但是,當我在我的原始數據上使用這個函數時,我只得到1作爲所有像素的值:( – rar

+0

不知道....在測試數據集上我認爲代碼正在做它應該做的事......您的輸入數據中是否有NAs? – lbusett

0

基於洛倫佐的回答,我修改了代碼,這正是我一直在尋找的。

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

但由於我的解決方案是基於你的答案,所以我接受你的答案洛倫佐。謝謝!