Created
April 7, 2019 14:46
-
-
Save fozy81/4aa67b997f440999e2d1e0cab0514cf5 to your computer and use it in GitHub Desktop.
brexit vote prediction
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
library(tidyverse) | |
brexit_bill <- data.frame( | |
date = c("2019-01-15", | |
"2019-03-12", | |
"2019-03-29"), | |
votes_lost_by = c(230, | |
149, | |
58) | |
) | |
# Convert text to Date format | |
brexit_bill$date <- as.Date(brexit_bill$date, format = "%Y-%m-%d") | |
# Calculate linear model: Date related to votes | |
model <- lm(date ~ votes_lost_by, data = brexit_bill) | |
# new data to generate predictions line - needs to included start point and end point | |
newdata <- | |
data.frame(votes_lost_by = c( | |
max(brexit_bill$votes_lost_by), # start point | |
0 # end point - zero votes | |
)) | |
# use the model to predict dates for new data | |
predicted_date <- predict(model, newdata) | |
# combine predicted dates and votes | |
predicted_data <- data.frame( | |
pred_date = as.Date(predicted_date, origin = "1970-01-01"), | |
pred_votes_lost_by = newdata$votes_lost_by | |
) | |
# plot observed | |
plot <- ggplot(brexit_bill, aes(date, votes_lost_by)) + | |
geom_point() + | |
ggtitle(paste('...If current trends continue, brexit vote will pass in Commons by', | |
predicted_data$pred_date[2])) + | |
xlab('Date') + | |
ylab('Votes needed') | |
# add predicted to plot | |
plot + | |
geom_line(aes(pred_date, pred_votes_lost_by), | |
# need to remove NAs because line is broken/disappears where NAs present | |
predicted_data, | |
linetype = 2, colour = "blue") + | |
theme_bw() | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment