Running the Python Package for Search Tweets in R
Tags: twitter, r, python, tutorial
Published: 2020-03-13 20:06:48

---
title: Running the Python Package for Search Tweets in R
published: true
description: Running the search-tweets-python package inside of R
tags: #Twitter #R #Python #tutorial 
cover_image: https://images.unsplash.com/photo-1515879218367-8466d910aaa4?ixlib=rb-1.2.1&ixid=eyJhcHBfaWQiOjEyMDd9&auto=format&fit=crop&w=700&q=60
---
_This tutorial was [originally posted to the Twitter developer blog](https://blog.twitter.com/developer/en_us/topics/tips/2020/running-the-python-package-for-search-tweets-in-r.html)._

[Reticulate](https://rstudio.github.io/reticulate/) is a package for R that allows you to run Python code inside of R. Since both Python and R are very popular for common data science tasks, it makes sense that you would want to use them together. A few times, I’ve been asked if we had an R version of the Python package, [search-tweets-python](https://github.com/twitterdev/search-tweets-python). This package allows you to connect to the [premium](https://developer.twitter.com/en/docs/tweets/search/overview/premium) and [enterprise](https://developer.twitter.com/en/docs/tweets/search/overview/enterprise) search endpoints easily.  With `reticulate`, you can call this Python package inside of R. This tutorial will walk you through how to use the search-tweets-python package inside of R to get a data frame that contains the date, ID and text of Tweets from a Twitter handle of your choosing from the past 30 days.

## What you need to get started with the Twitter API
First, you will need an approved developer account. You can apply for a developer account [here](https://developer.twitter.com/en/apply-for-access). Once your account is approved, you will need to [create a Twitter app](https://developer.twitter.com/en/apps). Then, set up that app for the [Search Tweets: 30-Day environment](https://developer.twitter.com/en/account/environments). You will also need to set a dev environment name – for the purposes of this tutorial mine is named `Testaroo`. After you have completed the initial set up, you’ll need to [locate your keys and tokens](https://developer.twitter.com/en/docs/basics/apps/overview).

## Installing the packages you need
To follow this tutorial, you will need to install the packages `reticulate` and `dplyr`. Reticulate is the package that will allow you to run Python code inside of R and `dplyr` allows you to shape your data to get exactly the results you are looking for.

```r
install.packages('reticulate')
install.packages('dplyr')
```

You will also need to call the packages to start working with them:

```r
library('reticulate')
library('dplyr')
```

## Getting your Python environment to set up inside of R
To work with reticulate you will need to make sure that your python environment is set up in R. You will need to create a variable for your Python path and use the [`use_python`](https://rstudio.github.io/reticulate/reference/use_python.html) module to set this path.

```r
path_to_python <- "/usr/bin/python3.7"
use_python(path_to_python)
```

You will need to install the Python packages `searchtweets` to help you connect to the Twitter API, and [`pandas`](https://pandas.pydata.org/pandas-docs/stable/) to create a data frame. You’ll create a virtual environment that provides an isolated Python environment to install packages into. You also have the option of using [`conda`](https://pandas.pydata.org/pandas-docs/stable/) if you prefer.

The following code creates a virtual environment called `tweetenv`. You’ll use two lines of code to install into this environment. After installing it, you can tell R to use the virtual environment you just created called `tweetenv` by using the function [`use_virtualenv`](https://rstudio.github.io/reticulate/reference/use_python.html).  

```r
virtualenv_install("tweetenv", "searchtweets", ignore_installed = TRUE)
virtualenv_install("tweetenv", "pandas", ignore_installed = TRUE)
use_virtualenv("tweetenv", required = TRUE)
```

You’ll need to import two packages you just installed into your code. You’ll create a variable called `st` that imports the package `searchtweets` and one called `pd` for `pandas`.

```r
st <- import("searchtweets")
pd <- import("pandas")
```

## Storing and accessing your credentials
To store your credentials and endpoint information you can create a file in the same directory you are using called `secret.yaml` that contains the following:

```yaml
search_tweets_api:
  account_type: premium
  endpoint: https://api.twitter.com/1.1/tweets/search/30day/Testaroo.json
  consumer_key: xxxxxxxxxxxxxxxxxxx
  consumer_secret: xxxxxxxxxxxxxxxxxxx
```

The `env_name` in the endpoint is the name of the dev environment you created on developer.twitter.com. You will need to change this to the name of your own dev environment. 

You want to make sure you add this file to your `.gitignore` before you push it to GitHub. For more information about working with a `.gitignore` file [check out this page](https://help.github.com/en/articles/ignoring-files). You also might want to review our [guide on keeping tokens secure](https://developer.twitter.com/en/docs/basics/authentication/guides/securing-keys-and-tokens).

In your R file, you will want to create a variable that uses the `load_credentials` function of the search-tweets-python library to load in your `secret.yaml` file. You may need to type the full path for the file if you run into any issues.

```r
cred <-
  st$load_credentials(filename = "secret.yaml",
                      yaml_key = "search_tweets_api",
                      env_overwrite = FALSE)
```

## Getting key information 
You’ll first need to set up a variable to allow us to type in the Twitter handle you’re looking for. For the purposes of this tutorial, the example being used is @TwitterDev. But you can type in any Twitter handle you wish to after being prompted to do so by the code.

```r
input <- readline('What handle do you want to get Tweets from? ')
```

You’ll need to set up two variables one for today that pulls in the current date and one that gets us the data from 30 days back. 

```r
today <- toString(Sys.Date())
thirty_days <- toString(as.Date(today) - 30)
```

In order for your text to be formatted correctly so that you can construct a valid search query, you’ll need to do some string formatting to create a variable called `pt_format`.

```r
pt_format <- sprintf("from:%s", input)
```

Run a print statement to make sure everything looks good.

```r
print(pt_format)
```

What you get back should look like this:

```
[1] "from:TwitterDev"
```

Now you can pass this information into a rule by passing in the pt_format you just created, thirty_days, today and set the number of results per a call.

```r
rule <-
  st$gen_rule_payload(
    pt_rule = pt_format,
    from_date = thirty_days,
    to_date = today,
    results_per_call = 500
  )
```

Simply print out this rule to see what you have:

```r
print(rule)
```

You should get back something that looks like this with the handle you typed in:

```
[1] "{\"query\": \"from:TwitterDev\", \"toDate\": \"202002070000\", \"fromDate\": \"202001080000\"}"
```

## Getting the Tweets
Next, you’ll need to create a variable called rs which lets us connect to the endpoint, pass in the max results, and pass in your username, endpoint, and bearer token.

```r
rs <-
  st$ResultStream(
    rule_payload = rule,
    max_results = 500,
    username = cred$extra_headers_dict,
    endpoint = cred$endpoint,
    bearer_token = cred$bearer_token
  )
print(rs)
```

If you print out this variable you’ll get a body of JSON that looks like this:


```
ResultStream: 
	{
    "username": null,
    "endpoint": "https://api.twitter.com/1.1/tweets/search/30day/Testaroo.json",
    "rule_payload": {
        "query": "from:TwitterDev",
        "toDate": "202002070000",
        "fromDate": "202001080000"
    },
    "tweetify": true,
    "max_results": 1000000000000000
}
```

You can pass the stream of the results using the attribute stream() into a variable called tweets.

```r
tweets <- rs$stream()
print(tweets)
```

When you print out the variable of tweets you will get a generator object that looks like this.

```
<generator object ResultStream.stream at 0x11f4a1af0>
```

To be able to access the information in a Python generator object you can use the [iterate](https://rstudio.github.io/reticulate/reference/iterate.html) attribute.

```r
it_tweets <- iterate(tweets)
```

## Creating a data frame
A data frame is a table-like data structure which can be particularly useful for working with datasets. To get a data frame of Tweets you can use the [`DataFrame`](https://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.DataFrame.html?highlight=dataframe#pandas.DataFrame) attribute of `pandas`. A data frame object from pandas is compatible with the data frames in R, so you can use your favorite R packages from this point you can use without doing extra conversions.

```r
tweets_df <- pd$DataFrame(data=it_tweets)
```

If you want to look through the data frame, It’s a bit easier to use `View` than `print`, which will show you a large data frame with many columns.

```r
View(tweets_df)
```

If you want to work with a smaller data frame that contains only a few columns you can [select the specific columns](https://dplyr.tidyverse.org/reference/select.html) using `dyplr`, a package for R that is helpful for reshaping data. The following code will return a data frame that has the date, Tweet ID and the text for all Tweets that fit the query you ran earlier. 

```r
smaller_df <- select(tweets_df, created_at, id, text)
View(smaller_df)
```

## Next steps
It was exciting to explore the interoperability of working with Twitter data with elements of two different languages. Other things you can do to explore this further include [running R inside of a Jupyter Notebook](https://docs.anaconda.com/anaconda/navigator/tutorials/r-lang/), and use a package called [rpy2](https://rpy2.readthedocs.io/en/latest/) to run R code inside of Python. The full version of the code can be found [here](https://github.com/twitterdev/search-tweets-python-in-r). Let us know on the [forums](http://twittercommunity.com) if you run into any troubles along the way or Tweet us at [@TwitterDev](https://twitter.com/TwitterDev) if this inspires you to create anything. 

I used several libraries and tools beyond the Twitter API to make this tutorial, but you may have different needs and requirements and should evaluate whether those tools are right for you.