Vehicle Accidents - Weather Related


Sample code for downloading in R



# Load the Libs

suppressMessages(library(dplyr))
library(ggplot2)
library(tidyr)
library(ggmap)
library(readr)
library(lubridate)
library(reshape2)
library(animation)
library(scales)

# Read the data

urlLink=
"https://storage.googleapis.com/montco-stats/tzr.csv"
d=read.csv(url(urlLink),header=TRUE,stringsAsFactors=FALSE)
wd<-function(x)
as.POSIXct(strptime(x, '%Y-%m-%d %H:%M:%S',tz='EST'))


# Functions

epoch<-function(x) strftime(x, format =
"%s", tz = 'EST')
epocht<- function(x)
as.integer(strtoi(x)/600)*600
epoch10<- function(x)
as.POSIXct(strptime(x, '%s',tz='EST'))

wdhr<-function(x)
as.POSIXct(strptime(x, '%Y-%m-%d %H:%M:%S',tz='EST'))
d$mdate=wd(d$timeStamp)

d$epoch=epoch(d$timeStamp)
d$epoch10=epoch10(epocht(epoch(d$timeStamp)))

# Compressing Dates

d$hr=format(d$mdate, format=
"%Y-%m-%d %H:00:00")
d$day=format(d$mdate, format=
"%Y-%m-%d 00:00:00")

#t=d[d$mdate >= '2016-02-10 07:00:00' & d$mdate <= '2016-02-10 09:00:00',]

# Traffic Accidents
t = d
t = filter(d,
grepl(
'VEHICLE',title))
counts <- summarise(group_by(t, title,day), Counts=length(title))
counts <- counts[order(-counts$Counts),]
counts

dx=counts[counts$title %
in% title$title,]

dx$asday =
as.Date(dx$day)
ggplot(data=dx,
aes(x=asday, y=Counts, colour=title)) +
geom_line(aes(group=title)) +
scale_x_date(breaks =
"1 month", minor_breaks = "1 week", labels=date_format("%B"))+
ggtitle(
"Montco PA\nTraffic Events Per day")+
labs(x=
"2016",y="Counts per day", colour = "Category")






Here's the graph


Screenshot 2016-02-11 16.56.42


blog comments powered by Disqus