【问题标题】:Identify nearest neighbor in grid in R (spatial)识别 R 中网格中的最近邻(空间)
【发布时间】:2015-03-04 18:58:04
【问题描述】:

我想创建一个方形网格并识别与一组其他网格单元相邻的网格单元,其中二进制变量取 1。在下面的示例中,我想生成一个单元格 id 的向量id 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)。任何和所有的想法都非常感谢。

【问题讨论】:

  • 这两个poly 应该是polys(反之亦然)。

标签: r spatial r-grid


【解决方案1】:

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))

【讨论】:

    猜你喜欢
    • 2018-05-19
    • 1970-01-01
    • 2021-10-17
    • 2014-02-23
    • 1970-01-01
    • 2019-11-30
    • 2015-07-17
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多