2014-11-04 60 views
2

我在柵格堆棧中有四個圖層,並希望在四個圖層中的每個單元格中選取最頻繁的值。如何從柵格堆棧中選取最頻繁的值(模式)

下面是數據集和代碼:

require(raster) 
a <- raster(matrix(c(12,11,11, 
        NA,11,11, 
        11,11,13),nrow=3)) 

b <- raster(matrix(c(12,12,12, 
        NA,12,12, 
        14,12,13),nrow=3)) 

c <- raster(matrix(c(13,9,13, 
        NA,13,13, 
        13,NA,13),nrow=3)) 

d <- raster(matrix(c(10,10,10, 
        NA,10,10, 
        10,10,10),nrow=3)) 

stk <- stack(a,b,c,d) 

我不知道是否有可能與代碼類似辦呢?

which.freqV <- function(x, ...){ 
    ??? 
} 

max <- stackApply(stk,1,which.freqV,na.rm=NULL) 

回答

2

我不得不這樣在我的腳本(計算堆棧的方式),並找到了完美的作品:

Mode <- function(x) { 
    ux <- unique(x) 
    ux=ux[!is.na(ux)] 
    ux[which.max(tabulate(match(x, ux)))] 
    } 
    layers_mode=calc(stack, fun=Mode) 

現在,如果你想要計算每個單元的模式頻率,請使用:

###calculate proportion of layers that have mode value as measure of uncertainty 
    Mode_count <- function(x) { 
    ux <- unique(x)  
    ux=ux[!is.na(ux)] 
    mode=ux[which.max(tabulate(match(x, ux)))] 
    sum(x==mode, na.rm=T) 
    } 
    layers_mode_freq=calc(stack, fun=Mode_count) 
+0

這正是我正在尋找的。它效果很好。非常感謝! – user1617676 2014-11-07 21:35:44

+0

你能告訴我如何獲得模式的計數嗎? – user1617676 2014-11-07 21:49:40

+0

謝謝!這很有幫助。 – user1617676 2014-11-08 17:28:11

0

一些非常基本的

a <- freq(stk, merge=TRUE) 
a$nt <- rowSums(a[, -1], na.rm = T) 
with(a, a[order(nt, decreasing = T), ]) 
+0

這適用於所有單元格,但不適用於堆棧中各層之間的每個單元格。 – user1617676 2014-11-07 21:34:30

+0

好的,我明白了。你想在所有的rasterLayers中使用最大的新圖層? – 2014-11-08 12:06:51

+0

這是正確的。謝謝。 – user1617676 2014-11-08 17:30:42

相關問題