Skip to content

Instantly share code, notes, and snippets.

@ymattu
Created July 17, 2017 16:34
Show Gist options
  • Save ymattu/1eb9cec5acb7814c9541167784ee1cb2 to your computer and use it in GitHub Desktop.
Save ymattu/1eb9cec5acb7814c9541167784ee1cb2 to your computer and use it in GitHub Desktop.
緯度経度から住所を求める関数
# 住所(市)判定
#' @param sp_polygon object of class sf, sfc or sfg
#' @param lon longitude
#' @param lat latitude
find_city <- function(sp_polygon = df, lon = lon, lat = lat) {
which.row <- sf::st_contains(sp_polygon, sf::st_point(c(lon, lat)), sparse = FALSE) %>%
grep(TRUE, .)
if (identical(which.row, integer(0)) == TRUE) {
message("指定した座標がポリゴンに含まれません")
} else {
geos <- sp_polygon[which.row, ] %>%
dplyr::mutate_if(is.factor, as.character) #%>%
#dplyr::mutate_at(dplyr::vars(N03_001:N03_004), dplyr::funs(dplyr::if_else(condition = is.na(.), true = "", false = .)))
#res <- tibble::data_frame(
# #city_code = geos$N03_007,
# city_name = paste0(geos$N03_001, geos$N03_002, geos$N03_003, geos$N03_004) %>%
# stringr::str_replace_all("NA", "")
#)
city_name = paste0(geos$N03_001, geos$N03_002, geos$N03_003, geos$N03_004) %>%
stringr::str_replace_all("NA", "")
return(city_name)
}
}
# 住所(街レベル)判定
#' @param sp_polygon object of class sf, sfc or sfg
#' @param lon longitude
#' @param lat latitude
find_place <- function(sp_polygon = df, lon = lon, lat = lat) {
which.row <- sf::st_contains(sp_polygon, sf::st_point(c(lon, lat)), sparse = FALSE) %>%
grep(TRUE, .)
if (identical(which.row, integer(0)) == TRUE) {
message("指定した座標がポリゴンに含まれません")
} else {
geos <- sp_polygon[which.row, ] %>%
dplyr::mutate_if(is.factor, as.character) #%>%
#dplyr::mutate_at(dplyr::vars(N03_001:N03_004), dplyr::funs(dplyr::if_else(condition = is.na(.), true = "", false = .)))
place_name = paste0(geos$KEN_NAME, geos$GST_NAME, geos$MOJI) %>%
stringr::str_replace_all("NA", "")
return(place_name)
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment