Created
February 18, 2021 21:18
-
-
Save GuillaumePressiat/3f4c6a4b3b918c9e3da2cab5ea399903 to your computer and use it in GitHub Desktop.
Lire et passer fichier data.gouv ministère intérieur commune > 1000 hab. 1er tour
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
library(readr) | |
library(dplyr) | |
# 1er tour | |
# https://www.data.gouv.fr/fr/datasets/elections-municipales-2020-resultats-1er-tour/#_ | |
u <- read_tsv('~/Downloads/2020-05-18-resultats-communes-de-1000-et-plus.txt', | |
locale = locale(encoding = "latin1"), | |
col_types = cols( | |
.default = col_character(), | |
`Code du département` = col_double(), | |
Inscrits = col_double(), | |
Abstentions = col_double(), | |
`% Abs/Ins` = col_number(), | |
Votants = col_double(), | |
`% Vot/Ins` = col_number(), | |
Blancs = col_double(), | |
Nuls = col_double(), | |
Exprimés = col_double(), | |
`% Exp/Ins` = col_number(), | |
`% Exp/Vot` = col_number(), | |
N.Pan. = col_double(), | |
`Sièges / Elu` = col_double(), | |
`Sièges Secteur` = col_double(), | |
`Sièges CC` = col_double(), | |
Voix = col_double(), | |
`% Voix/Exp` = col_number())) | |
v <- u %>% | |
select(1:4, starts_with('X')) | |
l <- length(names(v)) - 4 | |
ngranu <- names(v)[1:4] | |
champs <- c('N.Pan.' , 'Code Nuance' , 'Sexe' , | |
'Nom' , 'Prénom' , 'Liste' , | |
'Sièges / Elu' , 'Sièges Secteur' , | |
'Sièges CC' , 'Voix' , '% Voix/Ins' , | |
'% Voix/Exp') | |
names(v) <- c(names(v)[1:4], paste0(rep(champs, l/12), " ___ ", rep(1:(l/12) + 1, each = 12))) | |
w <- u %>% | |
rename_at(vars(all_of(champs)), function(x)paste0(x, " ___ 1")) %>% | |
select(-starts_with('X')) %>% | |
left_join(v %>% filter(!is.na(`N.Pan. ___ 2`)), by = ngranu) %>% | |
tidyr::gather(var, val, - `Code du département`, - `Libellé du département`, - `Code de la commune`, | |
- `Libellé de la commune`, - `Inscrits`, - `Abstentions`, - `% Abs/Ins`, - `Votants`, - `% Vot/Ins`, - `Blancs`, | |
- `% Blancs/Ins`, - `% Blancs/Vot`, - `Nuls`, - `% Nuls/Ins`, - `% Nuls/Vot`, - `Exprimés`, - `% Exp/Ins`, - `% Exp/Vot`) %>% | |
filter(!is.na(val)) %>% | |
tidyr::separate(var, c('Variable', 'N° Pan.'), sep = " ___ ") %>% | |
tidyr::spread(Variable, val) | |
# Bugs dans les données ? > à vérifier à la main, pb séparateur \t dans le fichier, etc. | |
w %>% | |
filter(N.Pan. != `N° Pan.`) %>% View | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment