I've created a loop that runs through a vector of Twitter handles, and collects tweets from them using the search_tweets
function from the rtweet
package.
Downloading the latest version of rtweet
## install devtools package if it's not already
if (!requireNamespace("devtools", quietly = TRUE)) {
install.packages("devtools")
}
## install dev version of rtweet from github
devtools::install_github("mkearney/rtweet")
library(rtweet)
Creating token
## autheticate via web browser
token=create_token(
app = "My_app",
consumer_key = "My Consumer Key",
consumer_secret =
"My Secret Code",set_renv = FALSE)
Here are my my Twitter handles, stored in a vector
twitter_handles=c("@realDonaldTrump","@HillaryClinton","@MittRomney")
Then I loop through these handles, and store results of each handle as a unique dataframe
#Loop through the twitter handles & store the results as individual dataframes
for(handle in twitter_handles) {
result <- search_tweets(handle, n = 3500 , include_rts = FALSE,retryonratelimit = TRUE)
if(length(result) != 0){
result$`Twitter Handle` <- handle
result$Source <- "Search"
df_name <- paste(tolower(substring(handle, 2)),"_search")
if(exists(df_name)) {
assign(df_name, unique(rbind(get(df_name), result)))
} else {
assign(df_name, result)
}
}
}
However when I do this, I get an error message
Warning: 32 - Could not authenticate you. Error in vector("list", ntimes) : invalid 'length' argument
However I don't think this is an authentication problem, because when I try with a random keyword/hashtag, I get results
data <- search_tweets("#rstats", n = 10, include_rts = FALSE,token = token)
My loop was working fine, but recently it has started throwing errors. Any ideas on why this is happening, and whether there is a fix?
Your help is highly appreciated!