<h1>Current State</h1>
<p>Using databases is unavoidable for those who analyze data as part of their jobs. As R developers, our first instinct may be to approach databases the same way we do regular files. We may attempt to read the data either all at once or as few times as possible. The aim is to reduce the number of times we go back to the data ‘well’, so our queries extract as much data as possible. After that, we spend cycles analyzing the data in memory. Here is what this model looks like:</p>
<p></p>
<p>Because the volume of data is significant with this approach, we usually attempt to come up with strategies to minimize the resources and time it takes to analyze the data. We may try to retrieve all rows of a few columns, or a few rows of several of columns. Another tactic is to save the query results into individual files for later analysis.</p>
<p>An improvement to the current approach would be to use the database’s SQL Engine to perform as much of the data exploration as possible. An enterprise-grade SQL server will have more power, and will be better tuned, to execute transformations of large amounts of data. Our goal would then be to bring into R a more targeted data set that will be used for visualization and modeling.</p>
<p>This improvement comes at a cost: we will need to know how to write SQL queries, and will have to switch between both languages. We may also end up using an external querying tool that is able to provide a list of tables and inline SQL code helpers. Of course, this involves switching between tools. On a personal note, I used to switch from R to Microsoft SQL Management Studio. After I that, I would bring the finalized query back into my code in R.</p>

<div>
<h1>A better way</h1>
<p></p>
<p>The <code>dplyr</code> package simplifies data transformation. It provides a consistent set of functions, called verbs, that can be used in succession and interchangeably to gain understanding of the data iteratively. The first time I re-wrote R code using <code>dplyr</code>, the new script was at least half as long and much easier to understand.</p>
<p>Another nice thing about <code>dplyr</code> is that it can interact with databases directly. It accomplishes this by translating the <code>dplyr</code> verbs into SQL queries. This incredibly convenient feature allows us to ‘speak’ directly with the database from R, thus resolving the issues brought up in the previous section:</p>
<ul><li><p><strong>Run data exploration over all of the data</strong> - Instead of coming up with a plan to decide what data to import, we can focus on analyzing the data inside the database, which in turn should yield faster insights.</p></li>
<li><p><strong>Use the SQL Engine to run the data transformations</strong> - We are, in effect, pushing the computation to the database because <code>dplyr</code> is sending SQL queries to the database.</p></li>
<li><p><strong>Collect a targeted dataset</strong> - After become familiar with the data and choosing the data points that will either be shared or modeled, a final query can then be used to bring back only that data into memory in R.</p></li>
<li><p><strong>All your code is in R!</strong> - Because we are using <code>dplyr</code> to communicate with the database, there is no need to change language, or tools, to perform the data exploration.</p></li>
</ul></div>
<div>
<h1>Example</h1>
<p>There are three things that we will need to get started:</p>
<ul><li><p>A database we can access</p></li>
<li><p>A database driver installed in either our workstation or RStudio Server</p></li>
<li><p>All of the required packages installed in R</p></li>
</ul><p>In this section, we will demonstrate how to access a Microsoft SQL Server database from a workstation that is running on Microsoft Windows.</p>
<div>
<h2>Database Driver</h2>
<p>A <strong>database driver</strong> is a program that allows the workstation and the database to communicate. In Microsoft Windows, the drivers that connect to MS SQL databases are installed by default. We need the <strong>name</strong> of the driver that will be used inside our code in R. The easiest way to do this is to open the ODBC Data Source Administrator. To find it in your, system please refer to this article: <a href="https://docs.microsoft.com/en-us/sql/database-engine/configure-windows/check-the-odbc-sql-server-driver-version-windows">Check the ODBC SQL Server Driver Version (Windows)</a> . Once the administrator program is open, click on the <strong>Drivers</strong> tab. In my laptop, these are the drivers available. I will use <strong>SQL Server</strong> for the Driver argument in my connection in R.</p>
<p></p>
</div>
<div>
<h2>R packages</h2>
<p>Besides <code>dplyr</code>, the following packages are required:</p>
<ul><li><code>odbc</code> - This is the interface between the database driver and R</li>
<li><code>DBI</code> - Standardizes the functions related to database operations</li>
<li><code>dbplyr</code> - Enables <code>dplyr</code> to interact with databases. It also contains the vendor-specific SQL translations.</li>
</ul><p>The database accessibility feature is still being developed, so we will use the development versions of <code>dbplyr</code> and <code>dplyr</code>.</p>
<pre><code>devtools::install_github(&quot;tidyverse/dplyr&quot;)
devtools::install_github(&quot;tidyverse/dbplyr&quot;)
install.packages(&quot;rstats-db/odbc&quot;)
install.packages(&quot;DBI&quot;)</code></pre>
</div>
<div>
<h2>Connect to the database</h2>
<p>We will use the <code>dbConnect()</code> function from the <code>DBI</code> package to connect to the database. The value for the <code>Driver</code> argument is the name we determined in the Database Driver section above.</p>
<pre><code>library(DBI)

con &lt;- dbConnect(odbc::odbc(),
                   Driver    = &quot;SQL Server&quot;, 
                   Server    = &quot;localhost&quot;,
                   Database  = &quot;airontime&quot;,
                   UID       = [My User ID],
                   PWD       = [My Password],
                   Port      = 1433)</code></pre>
<p>A very useful function in <code>DBI</code> is <code>dbListTables()</code>, which retrieves the names of available tables.</p>
<pre><code>dbListTables(con)</code></pre>
<p><code>[1] &quot;airlines&quot; &quot;airport&quot;  &quot;airports&quot; &quot;faithful&quot; &quot;flights&quot;  &quot;iris&quot;</code></p>
<p>Another useful function is the <code>dbListFields</code>, which returns a vector with all of the column names in a table.</p>
<pre><code>dbListFields(con, &quot;flights&quot;)</code></pre>
<p><code>[1] &quot;year&quot;           &quot;month&quot;          &quot;day&quot;            &quot;dep_time&quot;       &quot;sched_dep_time&quot;  [6] &quot;dep_delay&quot;      &quot;arr_time&quot;       &quot;sched_arr_time&quot; &quot;arr_delay&quot;      &quot;carrier&quot;        [11] &quot;flight&quot;         &quot;tailnum&quot;        &quot;origin&quot;         &quot;dest&quot;           &quot;air_time&quot;       [16] &quot;distance&quot;       &quot;hour&quot;           &quot;minute&quot;         &quot;time_hour&quot;</code></p>
</div>
<div>
<h2>Interacting with the data using dplyr</h2>
<p>Using <code>dplyr</code>, we can easily preview a database. The <code>tbl()</code> command creates a reference to the table.</p>
<pre><code>library(dplyr)
tbl(con, &quot;flights&quot;)</code></pre>
<p><br></p>
<pre><code>Source:     table&lt;flights> [?? x 19]
Database:   Microsoft SQL Server 12.00.4422[username@localhost/airontime]

    year month   day dep_time sched_dep_time dep_delay arr_time sched_arr_time arr_delay carrier flight tailnum origin  dest
   &lt;int> &lt;int> &lt;int>    &lt;int>          &lt;int>     &lt;dbl>    &lt;int>          &lt;int>     &lt;dbl>   &lt;chr>  &lt;int>   &lt;chr>  &lt;chr> &lt;chr>
1   2013     1     1      517            515         2      830            819        11      UA   1545  N14228    EWR   IAH
2   2013     1     1      533            529         4      850            830        20      UA   1714  N24211    LGA   IAH
3   2013     1     1      542            540         2      923            850        33      AA   1141  N619AA    JFK   MIA
4   2013     1     1      544            545        -1     1004           1022       -18      B6    725  N804JB    JFK   BQN
5   2013     1     1      554            600        -6      812            837       -25      DL    461  N668DN    LGA   ATL
6   2013     1     1      554            558        -4      740            728        12      UA   1696  N39463    EWR   ORD
7   2013     1     1      555            600        -5      913            854        19      B6    507  N516JB    EWR   FLL
8   2013     1     1      557            600        -3      709            723       -14      EV   5708  N829AS    LGA   IAD
9   2013     1     1      557            600        -3      838            846        -8      B6     79  N593JB    JFK   MCO
10  2013     1     1      558            600        -2      753            745         8      AA    301  N3ALAA    LGA   ORD
# ... with more rows, and 5 more variables: air_time &lt;dbl>, distance &lt;dbl>, hour &lt;dbl>, minute &lt;dbl>, time_hour &lt;dttm>
</code></pre>
<p><br> The <code>tally()</code> verb in <code>dplyr</code> returns the row count.</p>
<pre><code>tally(tbl(con, &quot;flights&quot;))</code></pre>
<p></p>
<pre><code>Source:     lazy query [?? x 1]
Database:   Microsoft SQL Server 12.00.4422[username@localhost/airontime]

       n
   &lt;int>
1 336776</code></pre>
<p><br> When used against a database, the previous function is converted to a SQL query that works with MS SQL Server. The <code>show_query()</code> function displays the translation.</p>
<pre><code>show_query(tbl(con, &quot;flights&quot;))</code></pre>
<p><code>&lt;SQL> SELECT COUNT(*) AS &quot;n&quot; FROM &quot;flights&quot;</code></p>
</div>
<div>
<h2>Bringing it all together</h2>
<p>The last code sample shows how easy it is to find out what the top airlines are by number of flights. Additionally, we wish to see the names of the airlines and not their codes. The steps taken are:</p>
<ul><li><p>Start with the <code>flights</code> table and join it to the <code>carrier</code> table to obtain the airline name</p></li>
<li><p>Group the data by the airline <code>name</code></p></li>
<li><p>Tally the total rows by airline <code>name</code></p></li>
<li><p>Order the data by the resulting tallies in a descending order</p></li>
</ul><p>All of these steps are translated into a SQL statement and processed inside the database. We do not need to import the tables into R memory at any time, we just use <code>dplyr</code> to get the results quickly.</p>
<pre><code>tbl(con, &quot;flights&quot;) %>%
  left_join(tbl(con, &quot;airlines&quot;), by = &quot;carrier&quot;) %>%
  group_by(name) %>%
  tally %>%
  arrange(desc(n))</code></pre>
<p><br></p>
<pre><code>Source:     lazy query [?? x 2]
Database:   Microsoft SQL Server 12.00.4422[username@localhost/airontime]
Ordered by: desc(n)

# S3: tbl_dbi
                       name     n
                      &lt;chr> &lt;int>
 1    United Air Lines Inc. 58665
 2          JetBlue Airways 54635
 3 ExpressJet Airlines Inc. 54173
 4     Delta Air Lines Inc. 48110
 5   American Airlines Inc. 32729
 6                Envoy Air 26397
 7          US Airways Inc. 20536
 8        Endeavor Air Inc. 18460
 9   Southwest Airlines Co. 12275
10           Virgin America  5162
# ... with more rows</code></pre>
</div>
</div>
<div>
<h1>Additional Resources</h1>
<p>Here are links that will provide a deeper look into their respective subjects:</p>
<ul><li><p><a href="http://dplyr.tidyverse.org/">dplyr’s Official Site</a></p></li>
<li><p><a href="https://cran.r-project.org/web/packages/DBI/vignettes/DBI-1.html">Vignette of the DBI package</a></p></li>
<li><p><a href="http://r4ds.had.co.nz/">R for Data Science</a> - An online book that covers how to use <code>dplyr</code> and other like packages that together are called the <code>tidyverse</code>.</p></li>
</ul></div>
<div>
<h1>Conclusion</h1>
<p>When we have only one method available to us, it is sometimes hard to see its inherent flaws. The method does what we need, so we do our best to overcome its shortfalls.</p>
<p>Our hope is that highlighting the issues related to importing large amounts of data into R, and the advantages of using <code>dplyr</code> to interact with databases, will be the encouragement needed to learn more about <code>dplyr</code> and to give it a try.</p>
<p>We plan to continue writing about the subject of databases using R in future posts. We will cover different aspects and techniques to get the most out of working with these two great technologies.</p>
</div>