Last active
July 8, 2019 06:49
-
-
Save uribo/4bdf76e07399ad75e9896763dd24aa60 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
zip_n03_url <- function(year, pref_code) { | |
year <- as.character(year) | |
year <- rlang::arg_match(year, | |
values = as.character(c(1920L, | |
seq.int(1950, 1985, by = 5L), | |
seq.int(1995, 2005, by = 5L), | |
seq.int(2006, 2018, by = 1L)))) | |
year_dir <- | |
dplyr::case_when( | |
year == "1920" ~ "200101", | |
year == "1950" ~ "501001", | |
year == "1955" ~ "551001", | |
year == "1960" ~ "601001", | |
year == "1965" ~ "651001", | |
year == "1970" ~ "701001", | |
year == "1975" ~ "751001", | |
year == "1980" ~ "801001", | |
year == "1985" ~ "851001", | |
year == "1995" ~ "951001", | |
year == "2000" ~ "001001", | |
year == "2005" ~ "05", | |
year == "2006" ~ "06", | |
year == "2007" ~ "071001", | |
year == "2008" ~ "090320", | |
year == "2009" ~ "100329", | |
year == "2010" ~ "110331", | |
year == "2011" ~ "120331", | |
year == "2012" ~ "120401", | |
year == "2013" ~ "130401", | |
year == "2014" ~ "140401", | |
year == "2015" ~ "150101", | |
year == "2016" ~ "160101", | |
year == "2017" ~ "170101", | |
year == "2018" ~ "180101" | |
) | |
paste0( | |
"http://nlftp.mlit.go.jp/ksj/gml/data/N03/N03-", | |
year, | |
"/N03-", | |
year_dir, | |
"_", | |
jpndistrict:::collect_prefcode(code = pref_code), | |
"_GML.zip" | |
) | |
} | |
read_ksj_n03 <- function(path = NULL, year = NULL, pref_code = NULL, download = FALSE) { | |
if (is.null(path)) { | |
dl_zip <- | |
zip_n03_url(year, pref_code) | |
path <- dplyr::if_else(download == TRUE, | |
".", | |
tempdir()) | |
zip_path <- | |
paste0(path, "/", basename(dl_zip)) | |
dl_zip %>% | |
download.file(zip_path) | |
path <- paste0(path, "/", gsub(".zip", "", basename(dl_zip))) | |
dir.create(path) | |
unzip(zipfile = zip_path, | |
exdir = path) | |
} | |
if (grepl(".shp$", basename(path))) { | |
d <- sf::st_read(dsn = path, | |
options = c("ENCODING=CP932"), | |
as_tibble = TRUE, | |
stringsAsFactors = FALSE) | |
} else if (grepl(".geojson$", basename(path))) { | |
d <- sf::st_read(dsn = path, | |
as_tibble = TRUE, | |
stringsAsFactors = FALSE) | |
} | |
xml_info <- | |
list.files(gsub(pattern = "(.+)/.+$", | |
replacement = "\\1", | |
path), | |
pattern = paste0("^N03.+", | |
gsub(basename(path), | |
"..+", ""), | |
".xml$"), | |
full.names = TRUE) | |
if (length(xml_info) == 1) { | |
xml_info <- | |
xml_info %>% | |
xml2::read_xml() %>% | |
xml2::as_list() | |
d <- | |
d %>% | |
purrr::set_names( | |
names(xml_info$Dataset$AdministrativeBoundary)[2:6], | |
attr(d, "sf_column")) | |
} | |
d | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment