Last active
February 1, 2019 00:36
-
-
Save robsalasco/259d58cbffc10c0b6bed43bc4d227339 to your computer and use it in GitHub Desktop.
This file contains hidden or 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
library(geojsonio) | |
library(dplyr) | |
library(purrr) | |
library(stringr) | |
d <- geojsonio::geojson_read("https://raw.githubusercontent.com/robsalasco/precenso_2016_geojson_chile/master/Comunas/R01.geojson", method = "local", what = "sp") | |
regiones_names_list <- c("region_id", "region_name") | |
provincias_names_list <- c("region_id", "provincia_id", | |
"region_name", "provincia_name") | |
comunas_names_list <- c("region_id", "provincia_id", "comuna_id", | |
"region_name", "provincia_name", "comuna_name") | |
manzanas_names_list <- c("region_id", "provincia_id", "comuna_id", | |
"region_name", "provincia_name", "comuna_name", | |
"manzent", "dis_id", "zon_id", "ent_id") | |
name_value <- case_when( | |
length(names(d)) == 2 ~ 1, | |
length(names(d)) == 4 ~ 2, | |
length(names(d)) == 6 ~ 3, | |
length(names(d)) == 10 ~ 4 | |
) | |
column_names <- switch(name_value, | |
regiones_names_list, provincias_names_list, comunas_names_list, manzanas_names_list) | |
names(d) <- column_names | |
id_columns <- column_names[endsWith(column_names, "_id")] | |
vector_sprintf <- c(2,2,5,2,2,2) | |
zeros <- map_chr(vector_sprintf[1:length(id_columns)], function(x) {paste0("%0", x, "d")}) | |
sanitizer <- function(x) { | |
x <- iconv(x, to = "ASCII//TRANSLIT", sub = "") | |
x <- str_replace_all(x, "[^[:alnum:]|[:space:]]", "") | |
x <- str_to_title(x) | |
return(x) | |
} | |
test_with <- function(x) { | |
if(endsWith(x, "_id") == TRUE){ | |
loc <- zeros[match(x, id_columns)] | |
vector_number <- list(sprintf(loc, as.numeric(as.character(d[[x]])))) | |
names(vector_number) <- x | |
return(vector_number) | |
} else { | |
vector_character <- list(x=sanitizer(as.character(d[[x]]))) | |
names(vector_character) <- x | |
return(vector_character) | |
} | |
} | |
d@data <- as.data.frame(map(names(d), test_with)) | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment