![](/img/trans.png)
[英]Assigning cell values of one raster to the adjacent cells of another using R
[英]How do I compare cell values of a raster with previous cells of this raster? binary r
我是新手,並且是使用R的初學者。這是我的問題:
我的柵格很大,有很多像元。 這是一個二進制柵格,因此只有0和1。 我必須遍歷整個柵格並找到0。 如果單元格[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)
有效。 但是問題是缺少了一些。
那我該怎么辦? 順便說一句,我希望有另一種可能性來解決這個任務。 也許我不需要循環? 我可以想象這對於很大的柵格來說不是一個很好的解決方案。 有人有主意嗎?
利用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)
使用函數raster :: focal
用於成對比較和<<-
分配:
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
注意:您必須在這里使用<<-
賦值,才能在函數環境之外修改變量。 引用哈德利 :
常規賦值箭頭
<-
始終在當前環境中創建一個變量。 深分配箭頭<<-
從不在當前環境中創建變量,而是修改通過遍歷父環境發現的現有變量。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.