---
title: "Using twfy to access TheyWorkForYou"
author: "Will Lowe"
date: "`r Sys.Date()`"
output: rmarkdown::html_vignette
vignette: >
  %\VignetteIndexEntry{twfy}
  %\VignetteEngine{knitr::rmarkdown}
  %\VignetteEncoding{UTF-8}
---


```{r,include=FALSE}
# real API access requires a key so these are prefetched 
# results from June 23, 2017
load('prefetched.rda')
```

In this vignette we use `twfy` to take a look at the MP for Keighley, West Yorkshire.
```{r}
library(twfy)
```
We can get its detailed by name or by any postcode
```{r, eval=FALSE}
keighley <- getConstituency("Keighley")
```

Who is the current MP?  This time we'll use the postcode lookup
```{r, eval=FALSE}
mp <- getMP(postcode="BD21 2DH")
```
Keighley's MP is 
```{r}
mp$full_name
```
He's a member of the Labour Party
```{r}
mp$party
```
and since we're in England he's in the House of Commons, represented as 1.
```{r}
mp$house
```
We can find him with two identifiers, the identifier for his current term in office
```{r}
mp$member_id
```
but more lastingly by his person id
```{r}
mp$person_id
```
With `person_id` we can get the details of all of his spells in the House 
of Commons like this
```{r, eval=FALSE}
mp_per <- getPerson(mp$person_id)
```
Now, what's he been talking about in Parliamentary debates?
```{r, eval=FALSE}
mp_talk <- getDebates(person=mp$person_id)
```
Debate results are fairly structured objects
```{r}
names(mp_talk)
names(mp_talk$info) # what we've got to work with
```
the output is paged, so there are
```{r}
mp_talk$info$total_results
```
entries, of which we are seeing from 
```{r}
mp_talk$info$results_per_page
```
counting from
```{r}
mp_talk$info$first_result
```
to get the second page, we'd call `getDebates` again specifying `page=2`.

Let's take a look at the first recorded entry
```{r}
first_entry <- mp_talk$rows[1,]
first_entry$hdate
```
clarifying an important issue
```{r}
first_entry$body
```
The `speaker` field embeds a data.frame with the speaker's details,
from which we note that he was not representing Keighley at that 
time but rather
```{r}
first_entry$speaker$constituency
```
