Skip to content

Instantly share code, notes, and snippets.

@mkearney
Last active November 16, 2019 17:41
Show Gist options
  • Save mkearney/d7a5c40e42521f2551b7faa56dd01631 to your computer and use it in GitHub Desktop.
Save mkearney/d7a5c40e42521f2551b7faa56dd01631 to your computer and use it in GitHub Desktop.
Search tweets example using #txlege tweets
library(rtweet)
## number of iterations
n <- 5
## to do a certain task (e.g., searching for tweets on a topic),
## twitter policy says you should use one token
## so select one token
token <- get_tokens()
if (!"Token" %in% class(token)) {
token <- token[[1]]
}
## initialize vectors
maxid <- NULL
txleg <- vector("list", n)
## check rate limit
rtlimit <- rate_limit(token, "search/tweets")
## loop through to capture all tweets
for (i in seq_len(n)) {
## if rate limit exhausted, wait for reset (cooldown)
if (rtlimit[["remaining"]] == 0) {
Sys.Sleep(rtlimit[["reset"]])
}
## search tweets
txleg[[i]] <- search_tweets(
"txlege", n = 18000, max_id = maxid, token = token)
## update rate limit
rtlimit <- rate_limit(token, "search/tweets")
## break conditions
if (!isTRUE(NROW(txleg[[i]]) > 0)) break
if (identical(maxid, txleg[[i]]$status_id[NROW(txleg[[i]])])) break
## update maxid
maxid <- txleg[[i]]$status_id[NROW(txleg[[i]]
}
txdf <- do.call("rbind", txleg)
ts_plot(txdf, "hours", theme = "nerdy", main = "#txlege tweets")
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment