Twitter is a great source of news about R — especially during conferences like useR! and RStudio Conference. And thanks to R and the rtweet package, you can build your own tool to download tweets for easy searching, sorting, and filtering. Let’s take a look, step by step.

First you want to install any of the rtweet project’s packages you don’t already have: rtweet, reactable, glue, stringr, httpuv, and dplyr. Then to start, load rtweet and dplyr.

# If you need to install any of these:
# install.packages("rtweet")
# install.packages("reactable")
# install.packages("glue")
# install.packages("stringr")
# install.packages("httpuv")
# install.packages("dplyr")
# install.packages("purrr")

Authorize the Twitter API

To use rtweet, you need a Twitter account so you can authorize rtweet to use your specific account credentials. That’s because there is a limit to how many tweets you can download in a 15-minute period.

Michael Kearney, who wrote rtweet, gives rtweet users two choices. The easiest way is to simply request some tweets. If there aren’t credentials stored on your system, a browser window should open asking you to authorize the request. After that, an authorization token will be stored in your .Renviron file so you don’t have to re-authorize in the future.

You can go to to see the other method, which involves setting up a Twitter developer account and a new project to generate authorization credentials. If you’re going to use rtweet a lot, you’ll probably want to do that. But to start, the easier way is, well, easier.

Import tweets

To search for tweets with a specific hashtag (or phrase that is not a hashtag), you use the intuitively named search_tweets() function. It takes several arguments, including the query, such as #rstudioconf or #rstats; whether you want to include retweets; and the number of tweets to return. The number defaults to 100.

Source link