Last active
August 24, 2021 03:34
-
-
Save uribo/05271588af76a1ea6b06303284094d97 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
# 市区町村別得票数 | |
read_senkyo_s_shikuchouson <- function(path, sheet = 1) { | |
df_raw <- | |
readxl::read_excel(path, | |
sheet = sheet, | |
skip = 3) | |
df_raw <- | |
df_raw %>% | |
dplyr::filter(!is.na(`候補者名`)) | |
x_candidate <- | |
names(df_raw) %>% | |
stringr::str_subset("\\.\\.", negate = TRUE) %>% | |
stringr::str_subset("候補者名|得票数計", negate = TRUE) | |
index_candidate <- | |
x_candidate %>% | |
stringr::str_remove("\\(.+\\)") %>% | |
purrr::map_dbl(~ stringr::str_which(names(df_raw) %>% | |
stringr::str_remove("\\(.+\\)"), | |
.x)) | |
y_candidate <- | |
df_raw %>% | |
dplyr::slice(1L) %>% | |
dplyr::select(all_of(index_candidate)) %>% | |
unlist() | |
kuname <- | |
df_raw %>% | |
dplyr::slice(nrow(.)) %>% | |
dplyr::pull(1) %>% | |
stringr::str_remove("[[:space:]]合計") %>% | |
stringi::stri_trans_nfkc() | |
df_raw %>% | |
dplyr::slice(-1L) %>% | |
dplyr::slice(-nrow(.)) %>% | |
dplyr::select(1, all_of(index_candidate)) %>% | |
dplyr::mutate(dplyr::across(c(all_of(index_candidate)), | |
.fns = ~ as.numeric(.x) %>% | |
round(digits = 3))) %>% | |
tidyr::pivot_longer(cols = -1, | |
names_to = "candidate") %>% | |
readr::type_convert(col_types = "cci") %>% | |
dplyr::mutate(candidate = stringr::str_squish(candidate)) %>% | |
dplyr::left_join(tibble::tibble( | |
candidate = stringr::str_squish(names(y_candidate)), | |
party = y_candidate), | |
by = "candidate") %>% | |
purrr::set_names(c("area", "candidate", "votes", "party")) %>% | |
dplyr::mutate(kuname = kuname) %>% | |
dplyr::select(kuname, area, candidate, party, votes) %>% | |
dplyr::mutate(dplyr::across(where(is.character), | |
.fns = stringi::stri_trans_nfkc)) | |
} |
Author
uribo
commented
Aug 24, 2021
kuname | area | candidate | party | votes |
---|---|---|---|---|
北海道第1区 | 札幌市中央区 | 船橋 利実 | 自由民主党 | 53200 |
北海道第1区 | 札幌市中央区 | 道下 大樹 | 立憲民主党 | 59879 |
北海道第1区 | 札幌市北区(1区) | 船橋 利実 | 自由民主党 | 1577 |
北海道第1区 | 札幌市北区(1区) | 道下 大樹 | 立憲民主党 | 1808 |
北海道第1区 | 札幌市南区 | 船橋 利実 | 自由民主党 | 36229 |
北海道第1区 | 札幌市南区 | 道下 大樹 | 立憲民主党 | 38906 |
北海道第1区 | 札幌市西区(1区) | 船橋 利実 | 自由民主党 | 29981 |
北海道第1区 | 札幌市西区(1区) | 道下 大樹 | 立憲民主党 | 38517 |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment