Skip to content

Instantly share code, notes, and snippets.

@uribo
Last active September 28, 2022 04:32
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save uribo/93ca243eb8b2e58b02bd5ac47ac2f02a to your computer and use it in GitHub Desktop.
Save uribo/93ca243eb8b2e58b02bd5ac47ac2f02a to your computer and use it in GitHub Desktop.
郵便番号から該当する都道府県・市区町村・町域名、jis codeを検索
read_zipcode_oogaki <-
memoise::memoise(
function(.path) {
dplyr::select(zipangu::read_zipcode(.path,
type = "oogaki"),
jis_code, zip_code, prefecture, city, street)
}
)
zip_to_administration <- function(x, value = "jis_code", .path = NULL) {
if (is.null(.path)) {
.path <-
"https://www.post.japanpost.jp/zipcode/dl/oogaki/zip/ken_all.zip"
}
unique(
dplyr::pull(
dplyr::filter(
read_zipcode_oogaki(.path),
zip_code == {{ x }}),
{{ value }})
)
}
to_jis_code <- function(x) {
df <-
dplyr::select(zipangu::jpnprefs, jis_code, prefecture = prefecture_kanji)
purrr::map_chr(
x,
function(x) {
if (stringr::str_detect(x, "[0-9]{2}|[0-9]{5}")) {
dplyr::pull(
dplyr::filter(df,
jis_code == stringr::str_sub({{ x }}, 1, 2)),
jis_code)
} else {
dplyr::pull(
dplyr::filter(df,
prefecture == {{ x }}),
jis_code)
}
}
)
}
@uribo
Copy link
Author

uribo commented Sep 28, 2022

# 郵便番号から該当する都道府県・市区町村・町域名、jis codeを返却
zip_to_administration("2430307", value = "prefecture")
#> [1] "神奈川県"
zip_to_administration("1550033", "city")
#> [1] "世田谷区"
zip_to_administration("1550033", "jis_code")
#> [1] "13112"

# 都道府県名・5桁のjis codeから2桁の都道府県コードに変換するには2段階
zip_to_administration("2430307", value = "prefecture") |> 
  to_jis_code()
#> [1] "14"
zip_to_administration("1550033", "jis_code") |> 
  to_jis_code()
#> [1] "13"

# 一つの郵便番号に対して複数の都道府県・市区町村がある場合はマッチするすべてを返却
zip_to_administration("8710000", value = "prefecture")
#> [1] "福岡県" "大分県"
zip_to_administration("6180000", "city")
#> [1] "乙訓郡大山崎町" "三島郡島本町"
zip_to_administration("4980000")
#> [1] "23235" "24303"
zip_to_administration("8710000", "prefecture") |> 
  to_jis_code()
#> [1] "40" "44"

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment