我想为大约200个拉链码和相邻的拉链码创建一个矩阵,触摸那些拉链码.矩阵将是200*200,两个zipcodes接触的单元格为1,而不是相邻的zipcodes,为0.
我怎么能创建或获得这样的矩阵?非常感谢你.
最好,
jba*_*ums 13
如果您有权访问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)
Run Code Online (Sandbox Code Playgroud)
对于我们的数据集,这将返回一个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
Run Code Online (Sandbox Code Playgroud)
(可选)如果您想要一个双列矩阵给出相邻的邮政编码对(即第1列中的邮政编码和第2栏中的相邻邮政编码),您可以使用以下内容.
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
Run Code Online (Sandbox Code Playgroud)