2016-12-07 71 views
2

我很新,並在使用R. 這是我的問題是初學者:如何比較柵格的單元格值與此柵格的先前單元格的值?二進制[R

我有很多細胞的大柵格。這是一個二進制柵格,所以只有0和1。我必須通過整個光柵並找到0。如果cell [i,j]是0,那麼我需要在它的4個鄰居上進行配對。

我只是想用一個小的7x7矩陣來嘗試這個。

我的想法是利用這樣的循環:

nr3=0 
for (i in 1:7) 
    {for (j in 1:7) 
    {if (m[i,j]==0) 
     {if (m[i-1,j]!=0&&m[i,j-1]!=0) 
      {nr3++} 
     if (m[i-1,j]!=0&&m[i,j+1]!=0) 
      {nr3++} 
     if (m[i,j+1]!=0&&m[i+1,j]!=0) 
      {nr3++} 
     if (m[i+1,j]!=0&&m[i,j-1]!=0) 
      {nr3++} }}} 

所以這就是它必須是。 但出現此錯誤:

Error in if (m[i-1,j]!=0&&m[i,j-1]!=0 {: missing value where TRUE/FALSE needed 

我可以看到問題。在邊界你不能比較所有的鄰居。 這就是爲什麼我試圖與

for (i in 2:6) 
for (j in 2:6) 

它的工作。但問題是有些人不見了。

那麼我該怎麼辦?順便說一句,我希望有另一種可能性來解決這個任務。也許我不需要一個循環?我可以想象這對於一個非常大的光柵來說不是一個很好的解決方案。 有沒有人有想法?

+0

你應該清楚你的意思是什麼「需要在其4個鄰國尋找配對」 ..什麼是你在看他們?你期望輸出什麼?最好用文字說明,而不是讓我們從你的代碼中找出你的意圖。 – jbaums

回答

0

利用raster庫。這應該是比你的循環方法快:

虛擬矩陣

library(raster) 

    #create a dummy raster 
    m <- raster(matrix(c(0,1,1,0,0,1,0,1,0), nrow=3)) 

    > as.matrix(m) 
    [,1] [,2] [,3] 
[1,] 0 0 0 
[2,] 1 0 1 
[3,] 1 1 0 

與4個相鄰

#define the size of your moving window (focal) 
f <- matrix(c(0,1,0,1,1,1,0,1,0), nrow=3) 

使用功能光柵::焦點

聯絡窗口爲成對比較a找到一個<<-分配:

nr3 <- 0 

    focal(m, 
     w = f, 
     pad = T, 
     padValue = 0, 
     fun = function(x){ 
       #x[5] corresponds to the center pixel in the moving window 
       if(x[5]==0){ 

        #x[2],x[4],x[6] and x[8] are the four neighbours 
        if(x[2]!=0 & x[4]!=0){ 
        nr3 <<- nr3 + 1 
        } 
        if(x[8]!=0 & x[4]!=0){ 
        nr3 <<- nr3 + 1 
        } 
        if(x[8]!=0 & x[6]!=0){ 
        nr3 <<- nr3 + 1 
        } 
        if(x[2]!=0 & x[6]!=0){ 
        nr3 <<- nr3 + 1 
        } 
       } 
     } 
    ) 

輸出:

> nr3 
[1] 3 

注: 你要在這裏使用<<-分配到能夠修改的功能環境以外的變量。引述Hadley

The regular assignment arrow, <- , always creates a variable in the current environment. The deep assignment arrow, <<- , never creates a variable in the current environment, but instead modifies an existing variable found by walking up the parent environments.

相關問題