我希望为大约200个邮政编码及其相邻的邮政编码创建一个矩阵。这个矩阵是200*200的,其中两个邮政编码接触的单元格将填充1,当它们不是相邻的邮政编码时填充0。
我应该如何创建或获取这样的矩阵呢?非常感谢。
最好的祝福,
我希望为大约200个邮政编码及其相邻的邮政编码创建一个矩阵。这个矩阵是200*200的,其中两个邮政编码接触的单元格将填充1,当它们不是相邻的邮政编码时填充0。
我应该如何创建或获取这样的矩阵呢?非常感谢。
最好的祝福,
如果您可以访问shapefile文件,那么使用spdep
软件包相对简单。
这是一个使用加利福尼亚州邮政编码数据的独立示例(~3.5MB下载):
# load libraries
library(rgdal)
library(spdep)
# download, unzip and import shapefile
download.file('http://geocommons.com/overlays/305142.zip', {f<-tempfile()})
unzip(f, exdir=tempdir())
shp <- readOGR(tempdir(), 'tigerline_shapefile_2010_2010_state_california_2010_census_5-digit_zip_code_tabulation_area_zcta5_state-based')
# identify neighbours for each poly
nbs <- setNames(poly2nb(shp), shp$ZCTA5CE10)
# convert to a binary neighbour matrix
nbs.mat <- nb2mat(nbs, zero.policy=TRUE, style='B')
# see?rgeos::gTouches for an alternative to the above steps
# assign zip codes as dimension names
dimnames(nbs.mat) <- list(shp$ZCTA5CE10, shp$ZCTA5CE10)
对于我们的数据集,这将返回一个1769 x 1769的矩阵,指示哪些邮政编码是相邻的。前10行和10列如下所示:
nbs.mat[1:10, 1:10]
## 94601 94501 94560 94587 94580 94514 94703 95601 95669 95901
## 94601 0 1 0 0 0 0 0 0 0 0
## 94501 1 0 0 0 0 0 0 0 0 0
## 94560 0 0 0 0 0 0 0 0 0 0
## 94587 0 0 0 0 0 0 0 0 0 0
## 94580 0 0 0 0 0 0 0 0 0 0
## 94514 0 0 0 0 0 0 0 0 0 0
## 94703 0 0 0 0 0 0 0 0 0 0
## 95601 0 0 0 0 0 0 0 0 0 0
## 95669 0 0 0 0 0 0 0 0 0 0
## 95901 0 0 0 0 0 0 0 0 0 0
如果您想要一个两列的矩阵,显示相邻的邮政编码对(即第一列为邮政编码,第二列为相邻邮政编码),则可以使用以下方法。
nbs.list <- sapply(row.names(nbs.mat), function(x) names(which(nbs.mat[x, ] == 1)))
nbs.pairs <- data.frame(zipcode=rep(names(nbs.list), sapply(nbs.list, length)),
neighbour=unlist(nbs.list))
head(nbs.pairs)
## zipcode neighbour
## 946011 94601 94501
## 946012 94601 94602
## 946013 94601 94605
## 946014 94601 94606
## 946015 94601 94621
## 946016 94601 94619