Warning: file_get_contents(/data/phpspider/zhask/data//catemap/4/r/71.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
识别R(空间)中栅格中的最近邻_R_Spatial_R Grid - Fatal编程技术网

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

识别R(空间)中栅格中的最近邻,r,spatial,r-grid,R,Spatial,R Grid,我想创建一个正方形网格,并确定与一组二进制变量取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)

我想创建一个正方形网格,并确定与一组二进制变量取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))
require(sp)

grid
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 

两个
poly
应该是
poly
(反之亦然)。
plot(ex, col=ifelse(seq_along(ex) %in% c(unlist(adj), which(ex$tr==1)), 'gray', NA))
text(coordinates(polys), labels=row.names(polys))