Skip to content

Instantly share code, notes, and snippets.

@glamp
Last active July 24, 2019 04:05
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save glamp/5c3f96fb1ad41c97adfe8e97b1e5b2f1 to your computer and use it in GitHub Desktop.
Save glamp/5c3f96fb1ad41c97adfe8e97b1e5b2f1 to your computer and use it in GitHub Desktop.
library(plyr)
library(XML)
library(uuid)
library(reshape2)
results <- ldply(states, function(state) {
url <- "http://www.electionprojection.com/latest-polls/%s-presidential-polls-trump-vs-clinton-vs-johnson-vs-stein.php"
state.fmt <- gsub(" ", "-", tolower(state))
url.state <- sprintf(url, state.fmt)
print(url.state)
r <- readHTMLTable(url.state, stringsAsFactors=FALSE)[[3]]
r$state <- state
r$id <- 1:nrow(r)
cols <- c("Dates", "Firm", "state", "Clinton", "Trump", "Johnson", "id")
r <- r[2:nrow(r),][,cols]
r <- melt(r, id=c("Dates", "Firm", "state", "id"), variable.name="candidate", value.name="vote")
names(r) <- c("date", "poll", "state", "id", "candidate", "vote")
r$race <- ""
cols <- c("date", "race", "state", "poll", "candidate", "vote", "id")
r <- r[,cols]
r$vote <- as.numeric(r$vote)
r
})
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment