gpt4 book ai didi

r - 如何查找与特定邮政编码相关的其他邮政编码?

转载 作者:行者123 更新时间:2023-12-02 02:32:48 24 4
gpt4 key购买 nike

我想为大约 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

如果您想要一个两列矩阵,给出相邻的邮政编码对(即第 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

关于r - 如何查找与特定邮政编码相关的其他邮政编码?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22652069/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com