简体   繁体   English

识别R中的网格中的最近邻居(空间)

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

I would like to create a square grid and identify the grid cells that border a set of other grid cell for which a binary variable takes a 1. In the following example, I would like to generate a vector of cell ids that border id g13 and g24: 我想创建一个正方形网格并标识与一组其他网格单元格相邻的网格单元格,对于这些网格单元格,二进制变量取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))

Such that it outputs a vector for all matching g13 as (g7, g8, g9, g12, g14, g17, g18, g19) and one matching g24 as (g18, g19, g20, g23, g24, g25). 这样它就为所有匹配的g13(g7,g8,g9,g12,g14,g17,g18,g19)和一个匹配的g24(g18,g19,g20,g23,g24,g25)输出一个向量。 Any and all thoughts greatly appreciated. 任何想法都将不胜感激。

rgeos::gTouches is perfect for this: 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 

And, because everyone loves pictures: 而且,由于每个人都喜欢图片:

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