8 Commits
13 changed files with 258 additions and 54 deletions
+26
View File
@@ -0,0 +1,26 @@
Package: hateimparlament
Title: Protocolanalysis of German Bundestag
Version: 0.0.0.9000
Authors@R:
person(given = "First",
family = "Last",
role = c("aut", "cre"),
email = "first.last@example.com",
comment = c(ORCID = "YOUR-ORCID-ID"))
Description: Downloads, parses and analyses protocols of the current German parliament (Bundestag).
License: `use_mit_license()`, `use_gpl3_license()` or friends to pick a
license
Encoding: UTF-8
LazyData: true
Roxygen: list(markdown = TRUE)
RoxygenNote: 7.1.1
Imports:
dplyr,
pbapply,
rvest,
stringr,
xml2
Suggests:
rmarkdown,
knitr
VignetteBuilder: knitr
+7
View File
@@ -0,0 +1,7 @@
# Generated by roxygen2: do not edit by hand
import(dplyr)
import(pbapply)
import(stringr)
import(tibble)
import(xml2)
+46
View File
@@ -0,0 +1,46 @@
mk_absolute_url <- function(path) paste0("https://www.bundestag.de", path)
mk_url <- function(offset) {
mk_absolute_url %$% sprintf("/ajax/filterlist/de/services/opendata/543410-543410?offset=%d",
offset)
}
download_protocol <- function(path, name, download_dir) {
fp <- paste0(download_dir, name)
try %$% download.file(mk_absolute_url(path), fp, quiet=T)
progress <<- progress + 1
setTimerProgressBar(pb, progress)
}
fetch_batch <- function(offset, download_dir) {
stopifnot("Offset must be numeric" = is.numeric(offset))
mk_url(offset) %>%
rvest::read_html() %>%
as.character() %>%
str_match_all("/resource/blob/.*?/([0-9]*-data\\.xml)") %>%
`[[`(1) ->
paths
mapply(download_protocol,
paths[,1],
paths[,2],
MoreArgs=list(download_dir = download_dir))
return(length(paths) > 0)
}
# TODO: error handling
# - what if: page not reachable
# - wrong format, etc.
fetch_all <- function(download_dir="records/") {
cat("Fetching all available records from bundestag.de. This may take a while ...\n")
# create progress bar
pb <<- timerProgressBar(min=0, max=250, width=40, char="+")
progress <<- 0
# close progress bar on exit (also on error)
on.exit({close(pb); cat("Done.\n")})
# fetch batch by batch
offset <- 0
while(fetch_batch(offset, download_dir)) offset <- offset + 10
# if successful, set progressbar to 100%
setTimerProgressBar(pb, 250)
}
+15
View File
@@ -0,0 +1,15 @@
#' @details
#' hateimparlament ist ein großartiges Paket!
#' @import tibble
#' @import dplyr
#' @import pbapply
#' @import stringr
#' @import xml2
#' @keywords internal
"_PACKAGE"
# The following block is used by usethis to automatically manage
# roxygen namespace tags. Modify with care!
## usethis namespace: start
## usethis namespace: end
NULL
+2
View File
@@ -1,2 +1,4 @@
`%$%` <- function(f, x) f(x) `%$%` <- function(f, x) f(x)
`%.%` <- function(f, g) function(...) f(g(...)) `%.%` <- function(f, g) function(...) f(g(...))
clear_na <- function(xs) xs[!is.na(xs)]
+35 -14
View File
@@ -1,14 +1,33 @@
source("config.R")
source("../utils/helpers.R")
library("xml2")
library(tibble)
library(magrittr)
# for usage see the example at the end # for usage see the example at the end
read_all <- function(path="records/") {
cat("Reading all records from", path, "\n")
available_protocols <- list.files(path)
res <- pblapply(available_protocols, read_one, path=path)
lapply(res, `[[`, "redner") %>%
bind_rows() %>%
distinct() ->
redner
lapply(res, `[[`, "reden") %>%
bind_rows() %>%
distinct() ->
reden
lapply(res, `[[`, "talks") %>%
bind_rows() %>%
distinct() ->
talks
list(redner = redner, reden = reden, talks = talks)
}
# this reads all currently parseable data from one xml # this reads all currently parseable data from one xml
read_one <- function(name) { read_one <- function(name, path) {
x <- read_xml(paste0(DOWNLOAD_DIR, name)) x <- tryCatch(read_xml(paste0(path, name)),
error = function(c) NULL)
if (is.null(x)) return(NULL)
cs <- xml_children(x) cs <- xml_children(x)
verlauf <- xml_find_first(x, "sitzungsverlauf") verlauf <- xml_find_first(x, "sitzungsverlauf")
@@ -22,6 +41,7 @@ read_one <- function(name) {
xml_find_all("rede") %>% xml_find_all("rede") %>%
parse_redenliste() -> parse_redenliste() ->
res res
list(redner = redner, reden = res$reden, talks = res$talks) list(redner = redner, reden = res$reden, talks = res$talks)
} }
@@ -60,7 +80,8 @@ parse_rede <- function(rede_xml) {
reden <- list() reden <- list()
for (node in cs) { for (node in cs) {
if (xml_name(node) == "p") { if (xml_name(node) == "p") {
if (xml_attr(node, "klasse") == "redner") { klasse <- xml_attr(node, "klasse")
if (!is.na(klasse) && klasse == "redner") {
if (!is.na(cur_redner)) { if (!is.na(cur_redner)) {
rede <- c(rede_id = rede_id, rede <- c(rede_id = rede_id,
redner = cur_redner, redner = cur_redner,
@@ -111,10 +132,10 @@ parse_rednerliste <- function(rednerliste_xml) {
# EXAMPLE USE # EXAMPLE USE
# make sure data ist downloaded via fetch.R # make sure data ist downloaded via fetch.R
res <- read_one("19038-data.xml") # res <- read_one("19126-data.xml")
#
res$redner # res$redner
res$reden # res$reden
res$talks # res$talks
# ------------------------------- # -------------------------------
+49
View File
@@ -0,0 +1,49 @@
fraktionen <- c("AFD" = "AfD",
"BÜNDNIS90/" = "BÜNDNIS 90 / DIE GRÜNEN",
"BÜNDNIS90/DIEGRÜNEN" = "BÜNDNIS 90 / DIE GRÜNEN",
"FRAKTIONSLOS" = "Fraktionslos",
"DIELINKE" = "DIE LINKE",
"SPD" = "SPD",
"CDU/CSU" = "CDU/CSU",
"FDP" = "FDP")
repair_fraktion <- function(fraktion) {
cleaned <- str_to_upper %$% str_replace_all(fraktion, "\\s", "")
fraktionen[cleaned]
}
# takes vector of titel and keeps longest
longest_titel <- function(titel) {
if (all(is.na(titel))) NA_character_
else titel[which.max %$% str_length(titel)]
}
# takes character vector, removes duplicates and collapses
collect_unique <- function(xs) xs %>% clear_na() %>% unique() %>% str_c(collapse="&") %>% na_if("")
# expects a tibble of redner and repairs
repair_redner <- function(redner) {
redner %>% mutate(fraktion = Vectorize(repair_fraktion)(fraktion)) %>% # fix fraktion
group_by(id, vorname, nachname) %>%
summarize(fraktion = collect_unique(fraktion),
titel = longest_titel(titel),
rolle_kurz = collect_unique(str_squish(rolle_kurz)),
rolle_lang = collect_unique(str_squish(rolle_lang)))
}
repair_reden <- function(reden) {
# TODO: fill with content
reden
}
repair_talks <- function(talks) {
# TODO: fill with content
talks
}
# repairs all tables
repair <- function(parse_output) {
list(redner = repair_redner(parse_output$redner),
reden = repair_reden(parse_output$reden),
talks = repair_talks(parse_output$talks))
}
+22 -2
View File
@@ -1,6 +1,26 @@
#Test # How to develop
Hallo ich teste das gerade Wie kann man entwickeln?
```r
# alles geht mit devtools (laedt auch noch ein paar andere pakete)
library(devtools)
# neu laden aller paket funktionen
load_all()
```
Wir verwenden NIEMALS source, etc.! Außerdem NIEMALD library(...) verwenden, sondern
um neue pakete hinzuzufuegen (als dependency), verwende:
```r
use_package("my-good-old-package")
```
Um paket imports verfuegbar zu machen, muss man diese in `R/hateimparlament-package.R`
als `@import <package>` hinzufuegen.
Um dokumentationen neu zu laden / zu erstellen (ruft roxgen auf)
```r
document()
```
# Herunterladen # Herunterladen
+18
View File
@@ -0,0 +1,18 @@
% Generated by roxygen2: do not edit by hand
% Please edit documentation in R/hateimparlament-package.R
\docType{package}
\name{hateimparlament-package}
\alias{hateimparlament}
\alias{hateimparlament-package}
\title{hateimparlament: Protocolanalysis of German Bundestag}
\description{
Downloads, parses and analyses protocols of the current German parliament (Bundestag).
}
\details{
hateimparlament ist ein großartiges Paket!
}
\author{
\strong{Maintainer}: First Last \email{first.last@example.com} (\href{https://orcid.org/YOUR-ORCID-ID}{ORCID})
}
\keyword{internal}
-2
View File
@@ -1,2 +0,0 @@
DOWNLOAD_DIR = "../data/" # warning: this is not created (should maybe)
-36
View File
@@ -1,36 +0,0 @@
source("../utils/helpers.R")
source("config.R")
library(rvest)
library(stringr)
mk_absolute_url <- function(path) paste0("https://www.bundestag.de", path)
mk_url <- function(offset) {
mk_absolute_url %$% sprintf("/ajax/filterlist/de/services/opendata/543410-543410?offset=%d",
offset)
}
download_protocol <- function(path, name) {
fp <- paste0(DOWNLOAD_DIR, name)
try %$% download.file(mk_absolute_url(path), fp, quiet=T)
}
fetch_batch <- function(offset) {
stopifnot("Offset must be numeric" = is.numeric(offset))
mk_url(offset) %>%
read_html() %>%
as.character() %>%
str_match_all("/resource/blob/.*?/([0-9]*-data\\.xml)") %>%
`[[`(1) ->
paths
mapply(download_protocol, paths[,1], paths[,2])
return(length(paths) > 0)
}
# TODO: error handling
# - what if: page not reachable
# - wrong format, etc.
fetch_all <- function() {
offset <- 0
while(fetch_batch(offset)) offset <- offset + 10
}
+2
View File
@@ -0,0 +1,2 @@
*.html
*.R
+36
View File
@@ -0,0 +1,36 @@
---
title: "funwithdata"
output: rmarkdown::html_vignette
vignette: >
%\VignetteIndexEntry{funwithdata}
%\VignetteEngine{knitr::rmarkdown}
%\VignetteEncoding{UTF-8}
---
```{r, include = FALSE}
knitr::opts_chunk$set(
collapse = TRUE,
comment = "#>"
)
```
```r
read_all() %>% repair() -> res
reden <- res$reden
redner <- res$redner
talks <- res$talks
# first tries
left_join(reden, redner, by=c("redner" = "id")) %>%
group_by(fraktion) %>%
summarize(n = n()) %>%
ggplot(aes(x = fraktion, y = n)) +
geom_bar(stat = "identity")
```
```{r setup}
library(hateimparlament)
```