Skip to content

Commit

Permalink
Create accidents.R
Browse files Browse the repository at this point in the history
New file to play with accidents data from TfL API and population data from: https://data.london.gov.uk/dataset/office-national-statistics-ons-population-estimates-borough
  • Loading branch information
Jim Leach authored Oct 4, 2016
1 parent a87e88f commit 1e1b26d
Showing 1 changed file with 59 additions and 0 deletions.
59 changes: 59 additions & 0 deletions R/accidents/accidents.R
Original file line number Diff line number Diff line change
@@ -0,0 +1,59 @@
# Step 0 - prep -----------------------------------------------------------
library(tidyverse)
library(forcats)
library(httr)
library(jsonlite)
library(readr)

credentials <- list(app_id = tfl_app_id, app_key = tfl_app_key)

# Step 1 - get data -------------------------------------------------------
# Accidents
url <- "https://api.tfl.gov.uk/AccidentStats/2015"
req <- GET(url, query = credentials)
accidents <- req %>%
content("text") %>%
fromJSON() %>%
as_data_frame()


pop <- read_csv("./api/population-estimates-single-year-age.csv")
colnames(pop) <- colnames(pop) %>% tolower()

# Step 2 - prep data ------------------------------------------------------
accidents <- accidents %>%
mutate(severity = as.factor(severity),
borough = as.factor(borough),
severity = fct_infreq(severity),
borough= fct_infreq(borough)) %>%
select(borough, severity, lat, lon, location, date) %>%
mutate(date_cln = gsub("T", " ", date),
date_cln = gsub("Z", " ", date_cln),
date_cln = lubridate::ymd_hms(date_cln))

pop <- pop %>%
filter(year == 2014) %>%
select(borough, `all persons`) %>%
rename(persons = `all persons`)

joined <- accidents %>%
left_join(pop)

joined %>%
group_by(borough) %>%
summarise(total_incidents = n(),
persons = mean(persons)) %>%
na.omit() %>%
mutate(rate = total_incidents / persons) %>%
ggplot(aes(x = persons, y = total_incidents, colour = total_incidents)) +
geom_point(size = 4) +
geom_smooth()

# Step 3 - plot -----------------------------------------------------------
accidents %>%
ggplot(aes(x = fct_rev(borough))) +
geom_bar(aes(fill = severity), colour = "white") +
scale_fill_brewer(palette = "Dark2") +
coord_flip() +
theme_minimal()

1 comment on commit 1e1b26d

@Jim89
Copy link
Owner

@Jim89 Jim89 commented on 1e1b26d Oct 4, 2016

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Please sign in to comment.