Skip to content

Commit

Permalink
version 1.0.0
Browse files Browse the repository at this point in the history
  • Loading branch information
hmeleiro authored and cran-robot committed Mar 12, 2024
0 parents commit dcbbcb6
Show file tree
Hide file tree
Showing 71 changed files with 3,561 additions and 0 deletions.
25 changes: 25 additions & 0 deletions DESCRIPTION
Original file line number Diff line number Diff line change
@@ -0,0 +1,25 @@
Package: infoelectoral
Type: Package
Title: Download Spanish Election Results
Version: 1.0.0
Authors@R:
person("Héctor", "Meleiro",
email = "hmeleiros@gmail.com",
role = c("aut", "cre"))
Maintainer: Héctor Meleiro <hmeleiros@gmail.com>
Description: Download official election results for Spain at polling station, municipality and province level from the Ministry of Interior (<https://infoelectoral.interior.gob.es/es/elecciones-celebradas/area-de-descargas/>), format them and import them to the R environment.
Depends: R (>= 3.5.0)
License: GPL-2
URL: https://github.com/rOpenSpain/infoelectoral
Encoding: UTF-8
LazyData: true
Imports: dplyr (>= 1.0.0), stringr (>= 1.0.0)
Suggests: mapSpain, tmap, tidyr, preferably, knitr, testthat (>= 3.0.0)
RoxygenNote: 7.2.3
VignetteBuilder: knitr
Config/testthat/edition: 3
NeedsCompilation: no
Packaged: 2024-03-11 08:39:33 UTC; hmele
Author: Héctor Meleiro [aut, cre]
Repository: CRAN
Date/Publication: 2024-03-11 19:10:02 UTC
70 changes: 70 additions & 0 deletions MD5
Original file line number Diff line number Diff line change
@@ -0,0 +1,70 @@
7c18b8b1a3fb38d2cbd3b409e7f34720 *DESCRIPTION
501b05b5cc10978d36ca836c39f2be35 *NAMESPACE
b6bd45c31c243b4a704b5ccb35f6f9b1 *R/candidatos.R
cc0aac5b2a6a6368af0253a4b9850448 *R/candidatos_nosenado.R
e2968c9983bb480215d1a5bd95e3b244 *R/candidatos_senado.R
de270f91db452aa41b8bee9e9f6e0bf3 *R/data.R
34ed821b9747385105882152301a3156 *R/examples/candidatos.R
8b7e816b926b2c875c104e41a425c98e *R/examples/mesas.R
a48cf5465aafcb43e378192a865a74e8 *R/examples/municipios.R
bbe56614dfaec3b6379e80182d8fbf04 *R/examples/provincias.R
8d83a906db5c3dce5d94a51be2389786 *R/mesas.R
81da605e56a7d33fe01ab5d3ea7fe6c4 *R/muni.R
f2952095308f34151de8095b394972da *R/provincias.R
631d95dd4104a23ac4df46f4f420437b *R/read03.R
55be0b859fecae7a8a7842bc4771d8d8 *R/read04.R
99ff8285271e3d3a6ffb931caf3a54d0 *R/read05.R
ea351056af5a2b0f15b3170591692473 *R/read06.R
4b8c152ba2b794acc1061edc713b274b *R/read07.R
7c36fc28e0286f1ee2d60f406f287ecb *R/read08.R
0fff51e57d14f611571ced9cd5890707 *R/read09.R
474daccc33c7fbc7caaa0dfa735b1ee9 *R/read10.R
2b10fc4e934207fdbbca35a55edaa8eb *R/read11.R
7c22990c6d24a5b44695556db4db86ca *R/read12.R
1a0f46f193cb0b7804a63ea122e88372 *R/senado_mesas.R
8795283039ff43404d8b8c6902fd6a0f *R/senado_municipios.R
1cadc91c838f21e037a884e94df92a27 *README.md
941bccdef2d2c23536464d8c1c7c7f30 *build/vignette.rds
14b5909f88064ed801f988e2cc41afac *data/codigos_ccaa.RData
60dc9c3563985000a1854c9ea596f31a *data/codigos_municipios.RData
08b8149b67dfdeb6746c90caf9a0250e *data/codigos_partidos.RData
cd867e338d05907a696281a5251f4aee *data/codigos_provincias.RData
0bd0b2b064b9388cf2f12142656278d0 *data/fechas_elecciones.RData
7da1f5bec203b469e7e73b54ffb9950f *data/renta_secciones.RData
0992adf620468cfc9f1dda129d4ecc37 *inst/doc/infoelectoral.R
df27a3f97f92be6607d7cb1dcc70f017 *inst/doc/infoelectoral.Rmd
322b1df472718f0d2cb9ec32c659f328 *inst/doc/infoelectoral.html
1d5351463536ce6d6ce0320ac181c5ab *inst/doc/municipios.R
5eb3c79796807afb58f9ce62b9251207 *inst/doc/municipios.Rmd
b857b2b9ed4e3b3136b9b0c463ed01b1 *inst/doc/municipios.html
5cf706f4d2853aa301b31d70ad2b2dd7 *man/candidatos.Rd
6d9a78ea69dbd19caa9944859f470502 *man/candidatos_nosenado.Rd
9c6eaef5b18fe4dfa054adf031a2f238 *man/candidatos_senado.Rd
d5008755c782ea733230157481257e85 *man/codigos_ccaa.Rd
28032fd0fac363da20a5f58a55529d0d *man/codigos_municipios.Rd
6df7d913f04e32ad864124fa3f8597fe *man/codigos_partidos.Rd
afb2a15e99420b5381a481f62fe2f45d *man/codigos_provincias.Rd
6ea2024f5eece03086cd5add4ec669e2 *man/fechas_elecciones.Rd
0fb76bf0cbbc88278e1f0263a4fea686 *man/mesas.Rd
55015737a681be338679087ae94456fc *man/municipios.Rd
7c48d336f930f374d857e182ae9eba84 *man/provincias.Rd
6c59b63f94ae71fb51217605e82db103 *man/read03.Rd
d0afb2db44adc923aa70018d4fb52e58 *man/read04.Rd
9603f6e42cd114dfbe41e08021161616 *man/read05.Rd
c34d3915911cac38e215bd2c87c3285a *man/read06.Rd
05c0d941cd52868aacf795c1494316bc *man/read07.Rd
a2e0967b924e45306fe530d236f5181b *man/read08.Rd
e1fa7a9c0ec90ad62d1e498276234882 *man/read09.Rd
9b82b26adf80e3a7d47be12d170b8820 *man/read10.Rd
f4a94354d04485660dc5f3066a9eee26 *man/read11.Rd
65d71ac402298c897353cd6560bef035 *man/read12.Rd
0f768b75bc71d6edbaad1962f4c86560 *man/renta.Rd
0f0b4d572d2d1234f9dfd896f35d7b1f *man/senado_mesas.Rd
b4f63c0be70438349e477ced0c0fecb1 *man/senado_municipios.Rd
b2a1c57c3aafbf6ea8fcbb7bc20085f2 *tests/testthat.R
f67195ca1ffbe6aaa524415f21fa73aa *tests/testthat/test-candidatos.R
9abe7b2a45cdfc60d0a7cdd1bd807da7 *tests/testthat/test-mesas.R
94f097a5a058393daf1db0310d64282e *tests/testthat/test-municipios.R
c00469b7a3584e100e153d89d6445e6f *tests/testthat/test-provincias.R
df27a3f97f92be6607d7cb1dcc70f017 *vignettes/infoelectoral.Rmd
5eb3c79796807afb58f9ce62b9251207 *vignettes/municipios.Rmd
20 changes: 20 additions & 0 deletions NAMESPACE
Original file line number Diff line number Diff line change
@@ -0,0 +1,20 @@
# Generated by roxygen2: do not edit by hand

export(candidatos)
export(mesas)
export(municipios)
export(provincias)
importFrom(dplyr,"%>%")
importFrom(dplyr,arrange)
importFrom(dplyr,bind_rows)
importFrom(dplyr,desc)
importFrom(dplyr,full_join)
importFrom(dplyr,left_join)
importFrom(dplyr,mutate)
importFrom(dplyr,mutate_if)
importFrom(dplyr,relocate)
importFrom(dplyr,select)
importFrom(stringr,str_remove_all)
importFrom(stringr,str_trim)
importFrom(utils,download.file)
importFrom(utils,unzip)
47 changes: 47 additions & 0 deletions R/candidatos.R
Original file line number Diff line number Diff line change
@@ -0,0 +1,47 @@
#' @title Download candidate data
#'
#' @description `candidatos()` downloads, formats and imports to the environment the data of the candidates from the electoral lists of the selected elections.
#'
#' @param tipo_eleccion The type of choice you want to download. The accepted values are "congreso", "senado", "europeas" o "municipales".
#' @param anno The year of the election in YYYY format.
#' @param mes The month of the election in MM format.
#' @param nivel The administrative level for which the data is wanted ("mesa" for polling stations or "municipio" for municipalities). Only necessary when tipo_eleccion = "senado"
#'
#' @example R/examples/candidatos.R
#'
#' @return data.frame with the candidates data. If tipo_eleccion = "senado" a column called `votos` is included with the votes recieved by each candidate. If other type of election is selected this column is not included since the votes are not received by the specific candidates but by the closed list of the party.
#'
#' @importFrom stringr str_trim
#' @importFrom stringr str_remove_all
#' @importFrom dplyr mutate
#' @importFrom dplyr mutate_if
#' @importFrom dplyr select
#' @importFrom dplyr arrange
#' @importFrom dplyr %>%
#'
#' @export
#'
candidatos <- function(tipo_eleccion, anno, mes, nivel) {

### Construyo la url al zip de la elecciones
if (tipo_eleccion == "municipales") {
tipo <- "04"
df <- candidatos_nosenado(tipo, anno, mes)
} else if (tipo_eleccion == "congreso") {
tipo <- "02"
df <- candidatos_nosenado(tipo, anno, mes)
} else if (tipo_eleccion == "europeas") {
tipo <- "07"
df <- candidatos_nosenado(tipo, anno, mes)
} else if (tipo_eleccion == "cabildos") {
tipo <- "06"
df <- candidatos_nosenado(tipo, anno, mes)
} else if (tipo_eleccion == "senado") {
tipo <- "03"
df <- candidatos_senado(anno, mes, nivel)
} else {
stop('The argument tipo_eleccion must take one of the following values: "congreso", "senado", "municipales", "europeas"')
}

return(df)
}
95 changes: 95 additions & 0 deletions R/candidatos_nosenado.R
Original file line number Diff line number Diff line change
@@ -0,0 +1,95 @@
#' @title candidatos_nosenado
#'
#' @description `candidatos_nosenado()` downloads, formats and imports to the environment the data of the candidates from the electoral lists of the selected elections.
#' @param tipo Code for the type of election.
#' @param anno The year of the election in YYYY format.
#' @param mes The month of the election in MM format.
#'
#' @return data.frame with the data of candidates.
#'
#' @importFrom stringr str_trim
#' @importFrom stringr str_remove_all
#' @importFrom dplyr mutate
#' @importFrom dplyr mutate_if
#' @importFrom dplyr select
#' @importFrom dplyr arrange
#' @importFrom dplyr %>%
#' @importFrom dplyr full_join
#' @importFrom dplyr left_join
#'
#' @keywords internal
#'
candidatos_nosenado <- function(tipo, anno, mes) {

urlbase <- "https://infoelectoral.interior.gob.es/estaticos/docxl/apliextr/"
url <- paste0(urlbase, tipo, anno, mes, "_MUNI", ".zip")
### Descargo el fichero zip en un directorio temporal y lo descomprimo
tempd <- tempdir(check = FALSE)
temp <- tempfile(tmpdir = tempd, fileext = ".zip")
download.file(url, temp, mode = "wb")
unzip(temp, overwrite = TRUE, exdir = tempd)

### Construyo las rutas a los ficheros DAT necesarios
codigo_eleccion <- paste0(substr(anno, nchar(anno)-1, nchar(anno)), mes)
todos <- list.files(tempd, recursive = TRUE)
x <- todos[grepl(paste0("04", tipo, codigo_eleccion, ".DAT"), todos)]
xbasicos <- todos[grepl(paste0("05", tipo, codigo_eleccion, ".DAT"), todos)]
xcandidaturas <- todos[grepl(paste0("03", tipo, codigo_eleccion, ".DAT"), todos)]


### Leo los ficheros DAT necesarios
dfcandidaturas <- read03(xcandidaturas, tempd)
dfcandidatos <- read04(x, tempd)
dfcandidatos$codigo_distrito[dfcandidatos$codigo_distrito == "9"] <- "99"
colnames(dfcandidatos)[colnames(dfcandidatos) == "codigo_senador"] <- "codigo_municipio"
dfbasicos <- read05(xbasicos, tempd)
dfbasicos <- dfbasicos[dfbasicos$codigo_distrito == "99",]

### Limpio el directorio temporal (IMPORTANTE: Si no lo hace, puede haber problemas al descargar más de una elección)
borrar <- list.files(tempd, full.names = TRUE, recursive = TRUE)
try(file.remove(borrar), silent = TRUE)

### Junto los datos de los tres ficheros
df <- full_join(dfbasicos, dfcandidatos, by = c("tipo_eleccion", "vuelta", "anno", "mes", "codigo_provincia", "codigo_municipio", "codigo_distrito"))
df <- left_join(df, dfcandidaturas, by = c("tipo_eleccion", "anno", "mes", "codigo_partido"))

### Limpieza: Quito los espacios en blanco a los lados de estas variables
df$siglas <- str_trim(df$siglas)
df$denominacion <- str_trim(df$denominacion)

df <- df %>%
mutate_if(is.character, str_trim) %>%
mutate(denominacion = str_remove_all("denominacion", '"')) %>%
select(
"tipo_eleccion",
"anno",
"mes",
"vuelta",
"codigo_provincia",
"codigo_municipio",
"codigo_distrito",
"orden_candidato",
"tipo_candidato",
"nombre",
"apellido_1",
"apellido_2",
"sexo",
"nacimiento",
"dni" ,
"electo",
"codigo_partido_nacional",
"codigo_partido_autonomia",
"codigo_partido_provincia",
"codigo_partido",
"denominacion",
"siglas"
) %>%
arrange("codigo_provincia", "siglas", "orden_candidato")

df <- df[!is.na(df$orden_candidato),]

df$nacimiento <- NA
df$dni <- NA

return(df)
}
23 changes: 23 additions & 0 deletions R/candidatos_senado.R
Original file line number Diff line number Diff line change
@@ -0,0 +1,23 @@
#' @title candidatos_senado
#'
#' @description `candidatos_senado()` downloads, formats and imports to the environment the data of the Senate candidates of the selected elections.
#'
#' @param anno The year of the election in YYYY format.
#' @param mes The month of the election in MM format.
#' @param nivel The administrative level for which the data is wanted ("mesa" for polling stations or "municipio" for municipalities).
#'
#' @return data.frame with the data for the Senate candidates.
#'
#' @keywords internal
#'
candidatos_senado <- function(anno, mes, nivel) {
if(nivel == "mesa") {
df <- senado_mesas(anno, mes)
} else if(nivel == "municipio") {
df <- senado_municipios(anno, mes)
} else {
stop('The argumento nivel must take one of the following values: "mesa", "municipio".')
}

return(df)
}
79 changes: 79 additions & 0 deletions R/data.R
Original file line number Diff line number Diff line change
@@ -0,0 +1,79 @@
#' Administrative codes for spanish provinces.
#'
#' This dataset contains the National Institute of Statistics administrative codes for spanish provinces with their official names.
#'
#' @format A dataset with 52 rows and 5 columns:
#' \describe{
#' \item{codigo_ccaa}{Code given to the autonomous communities by the Ministry of Interior (not the same as the National Institute of Statistics codes)}
#' \item{codigo_ccaa_ine}{Code given to the autonomous communities by the National Institute of Statistics}
#' \item{ccaa}{Official name of the autonomous communities}
#' \item{codigo_provincia}{Code given to the provinces by the National Institute of Statistics}
#' \item{provincia}{Official name of the provinces}
#' }
#' @source \url{https://www.ine.es/daco/daco42/codmun/cod_provincia.htm}
"codigos_provincias"

#' Administrative codes for spanish autonomous communities.
#'
#' This dataset contains the codes given to the autonomus communities by the Ministry of Interior and the ones given by the National Institute of Statistics with their official names.
#'
#' @format A dataset with 19 rows and 3 columns:
#' \describe{
#' \item{codigo_ccaa}{Code given to the autonomous communities by the Ministry of Interior (not the same as the National Institute of Statistics codes)}
#' \item{codigo_ccaa_ine}{Code given to the autonomous communities by the National Institute of Statistics}
#' \item{provincia}{Official name of the provinces}
#' }
#' @source \url{https://infoelectoral.interior.gob.es/opencms/es/elecciones-celebradas/area-de-descargas/}
"codigos_ccaa"

#' Administrative codes for spanish municipalities.
#'
#'This dataset contains the INE codes of the municipalities of Spain with their most recent names (eg: Cabrera d'Igualada appears as Cabrera d'Anoia). For the municipalities that have been merged at some point, their codes are kept separately along with that of the new municipality created (eg: it contains the municipality Oza-Cesuras but also that of Cesuras and Oza dos Ríos separately).
#'
#' @format A dataset with more than 8.000 rows and 3 columns:
#' \describe{
#' \item{codigo_provincia}{Code given to the provinces by the National Institute of Statistics}
#' \item{codigo_municipio}{Code given to the municipalities by the National Institute of Statistics}
#' \item{municipio}{Most recent official name of the municipality}
#' }
#' @source \url{https://www.ine.es/dyngs/INEbase/es/operacion.htm?c=Estadistica_C&cid=1254736177031&menu=ultiDatos&idp=1254734710990}
"codigos_municipios"

#' Recoded party names
#'
#' This dataset contains a list of recoded electoral party or coalition names with their correspondent national codes. For example: 'PSOE' when the original name is 'PSA-PSOE', 'PSOE-PROGR.' or 'PSOE-A'. This recodification helps the longitudinal analysis of the electoral results, avoiding the many variations in the party and coalition names.
#'
#' @format A dataset with the names of the electoral party or coalition
#' \describe{
#' \item{anno}{Year of the election}
#' \item{mes}{Month of the election}
#' \item{codigo_partido_nacional}{The national accumulation code for the electoral party or coalition}
#' \item{partido}{The recoded name for the electoral party or coalition.}
#' }
"codigos_partidos"

#' Election dates
#'
#' This dataset contains the dates of the local, general and european elections in Spain from 1977 to 2023.
#'
#' @format A dataset with the dates of the elections
#' \describe{
#' \item{tipo_eleccion}{Election level (local, general or european parliament)}
#' \item{anno}{Year of the election}
#' \item{mes}{Month of the election}
#' \item{day}{Day of the election}
#' }
#' @source \url{https://www.juntaelectoralcentral.es/cs/jec/elecciones}
"fechas_elecciones"

#' Mean income at the census section level (INE)
#'
#' This dataset contains the mean income of each census section
#'
#' @format A dataset with more than 34.000 rows and 2 columns:
#' \describe{
#' \item{codigo_seccion}{Code given to the census section made by the combination of the codes of the province, the municipality, the district and the section.}
#' \item{renta}{Mean income of the census section in euros}
#' }
#' @source \url{https://www.ine.es/dyngs/INEbase/es/operacion.htm?c=Estadistica_C&cid=1254736177088&menu=ultiDatos&idp=1254735976608}
"renta"
4 changes: 4 additions & 0 deletions R/examples/candidatos.R
Original file line number Diff line number Diff line change
@@ -0,0 +1,4 @@
data <- candidatos(tipo_eleccion = "senado", anno = "2004",
mes = "03", nivel = "municipio")
str(data)

4 changes: 4 additions & 0 deletions R/examples/mesas.R
Original file line number Diff line number Diff line change
@@ -0,0 +1,4 @@
\donttest{
data <- mesas(tipo_eleccion = "congreso", anno = "2023", mes = "07")
str(data)
}
3 changes: 3 additions & 0 deletions R/examples/municipios.R
Original file line number Diff line number Diff line change
@@ -0,0 +1,3 @@
data <- municipios(tipo_eleccion = "congreso", anno = "2019", mes = "11")
str(data)

3 changes: 3 additions & 0 deletions R/examples/provincias.R
Original file line number Diff line number Diff line change
@@ -0,0 +1,3 @@
data <- provincias(tipo_eleccion = "congreso", anno = "1982", mes = "10")
str(data)

0 comments on commit dcbbcb6

Please sign in to comment.