簡體   English   中英

識別R中的網格中的最近鄰居(空間)

[英]Identify nearest neighbor in grid in R (spatial)

我想創建一個正方形網格並標識與一組其他網格單元格相鄰的網格單元格,對於這些網格單元格,二進制變量取1。在下面的示例中,我想生成一個邊界為g13和G24:

require(sp)         
grid <- GridTopology(c(0,0), c(1,1), c(5,5))    
polys <- as(grid, "SpatialPolygons")
centroids <- coordinates(polys)
id <- names(polys)
tr <- ifelse(id == "g13" | id == "g24", 1, 0)       
ex <- SpatialPolygonsDataFrame(polys, data = data.frame(id = id, tr = tr, row.names = row.names(polys)))

plot(ex)
text(coordinates(polys), labels = row.names(polys))

這樣它就為所有匹配的g13(g7,g8,g9,g12,g14,g17,g18,g19)和一個匹配的g24(g18,g19,g20,g23,g24,g25)輸出一個向量。 任何想法都將不勝感激。

rgeos::gTouches非常適合:

library(rgeos)
adj <- gTouches(polys, polys[which(ex$tr==1)], byid=TRUE)
apply(adj, 1, which)

# $g13
#  g7  g8  g9 g12 g14 g17 g18 g19 
#   7   8   9  12  14  17  18  19 
# 
# $g24
# g18 g19 g20 g23 g25 
#  18  19  20  23  25 

而且,由於每個人都喜歡圖片:

plot(ex, col=ifelse(seq_along(ex) %in% c(unlist(adj), which(ex$tr==1)), 'gray', NA))
text(coordinates(polys), labels=row.names(polys))

在此處輸入圖片說明

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM