<p><div><div><div><div data-width="100" data-show-faces="false" data-send="true" data-layout="button_count" data-height="21" data-href="https://www.r-bloggers.com/fast-data-lookups-in-r-dplyr-vs-data-table/"></div></div><div></div></div><div></div></div>
<div>
(This article was first published on <strong><a href="http://blog.appsilondatascience.com/rstats/2017/03/02/r-fast-lookup.html"> Appsilon Data Science - R language</a></strong>, and kindly contributed to <a rel="nofollow" href="https://www.r-bloggers.com/">R-bloggers)</a> </div>
<p>R is a vector-oriented language and most of the things you do in R is optimised for that, but what if you need something less typical… What if you need to find a specific element in a dataset? There are a lot of options to do that in R, but when your dataset has a few million rows or more lookups may be extremely slow. This is especially problematic in Shiny apps, where user should get a feedback on his/her action in a fraction of seconds. Otherwise user might get really frustrated when using your app!</p>
<p>In this post I’m going to compare different methods that can be used to improve lookup times in R. In our case, we were able to improve lookup speed 25 times by using data.table indexes.</p>
<p>First, let’s generate a sample dataset with 10 million rows:</p>
<div>
<pre><code data-lang="r"><span>library</span><span>(</span>tibble<span>)</span>

random_string_column <span>&lt;-</span> <span>function</span><span>(</span>n<span>)</span> <span>{</span>
  stringi<span>::</span>stri_rand_strings<span>(</span>n <span>=</span> n<span>,</span> length <span>=</span> <span>8</span><span>)</span>
<span>}</span>

random_data_frame <span>&lt;-</span> <span>function</span><span>(</span>n<span>)</span> tibble<span>(</span>
  col1 <span>=</span> random_string_column<span>(</span>n<span>),</span>
  col2 <span>=</span> random_string_column<span>(</span>n<span>)</span>
<span>)</span>

data <span>&lt;-</span> random_data_frame<span>(</span><span>10</span><span>^</span><span>7</span><span>)</span></code></pre>
</div>
<p>To compare efficiency of different methods, let’s create a simple benchmarking routine:</p>
<div>
<pre><code data-lang="r">time <span>&lt;-</span> <span>function</span><span>(</span><span>...</span><span>)</span> <span>{</span>
  time_measurement <span>&lt;-</span> <span>system.time</span><span>(</span><span>eval</span><span>(</span><span>...</span><span>))</span>
  time_measurement<span>[[</span><span>&quot;user.self&quot;</span><span>]]</span>
<span>}</span>

benchmark <span>&lt;-</span> <span>function</span><span>(</span><span>...</span><span>,</span> n <span>=</span> <span>100</span><span>)</span> <span>{</span>
  times <span>&lt;-</span> <span>replicate</span><span>(</span>n<span>,</span> <span>...</span><span>)</span>
  <span>c</span><span>(</span>min <span>=</span> <span>min</span><span>(</span>times<span>),</span> max <span>=</span> <span>max</span><span>(</span>times<span>),</span> mean <span>=</span> <span>mean</span><span>(</span>times<span>))</span>
<span>}</span></code></pre>
</div>
<p>These routines benchmark a piece of code running it multiple times. In each run, we can have some preparation steps that are not included in the measured execution time – we will only measure execution time of code wrapped with a call to <code>time(...)</code>.</p>
<h2>dplyr::filter and data.table filtering</h2>
<p>At Appsilon, we often use Hadley’s <a target="_blank" rel="nofollow" href="https://github.com/hadley/dplyr">dplyr</a> package for data manipulations. To find a specific element in a data frame (or, more precisely, a tibble) one can use dplyr’s <code>filter</code> function.<br>
Let’s see how long it takes to find an element with a specific key using dplyr.</p>
<div>
<pre><code data-lang="r"><span>library</span><span>(</span>dplyr<span>)</span>

benchmark<span>({</span>
  key_to_lookup <span>&lt;-</span> select_random_key<span>()</span>
  time<span>(</span>data <span>%>%</span> filter<span>(</span>col1 <span>==</span> key_to_lookup<span>))</span>
<span>})</span></code></pre>
</div>
<div>
<pre><code data-lang="r"><span>## min max mean </span>
<span>## 0.0960 0.2440 0.1124</span></code></pre>
</div>
<p>On average, finding a single element using <code>filter</code> takes 112 ms on my machine. This may not seem a lot, but in fact this is very slow – especially if you want to do several such operations at a time.<br>
Why is <code>filter</code> so slow? <em>dplyr</em> does not know anything about our dataset. The only way for it to find matching elements is to look row by row and check if the criteria is matched. When the dataset gets large, this simply must take time.<br>
Filtering using <code>data.table</code> is similarly slow:</p>
<div>
<pre><code data-lang="r"><span>library</span><span>(</span>data.table<span>)</span>

data_table <span>&lt;-</span> data.table<span>(</span>data<span>)</span>

benchmark<span>({</span>
  key_to_lookup <span>&lt;-</span> select_random_key<span>()</span>
  time<span>(</span>data_table<span>[</span>col1 <span>==</span> key_to_lookup<span>])</span>
<span>})</span></code></pre>
</div>
<div>
<pre><code data-lang="r"><span>## min max mean </span>
<span>## 0.00100 5.99400 0.06194</span></code></pre>
</div>
<p>In the worst case it took almost 6 seconds to find an element!</p>
<h2>Builtin operators</h2>
<p>You might be thinking: maybe it’s just <em>dplyr</em> and <em>data.table</em>? Maybe filtering the old-school way with builtin operators and filtering is faster?</p>
<div>
<pre><code data-lang="r">benchmark<span>({</span>
  key_to_lookup <span>&lt;-</span> select_random_key<span>()</span>
  time<span>(</span>data<span>[</span>data<span>$</span>col1 <span>==</span> key_to_lookup<span>,])</span>
<span>})</span></code></pre>
</div>
<div>
<pre><code data-lang="r"><span>## min max mean </span>
<span>## 0.09800 0.22300 0.11424</span></code></pre>
</div>
<p>No dice. How about using <code>which</code> for selecting rows?</p>
<div>
<pre><code data-lang="r">benchmark<span>({</span>
  key_to_lookup <span>&lt;-</span> select_random_key<span>()</span>
  time<span>(</span>data<span>[</span><span>which</span><span>(</span>data<span>$</span>col1 <span>==</span> key_to_lookup<span>),])</span>
<span>})</span></code></pre>
</div>
<div>
<pre><code data-lang="r"><span>## min max mean </span>
<span>## 0.09200 0.15800 0.10471</span></code></pre>
</div>
<p>Still the same. Dataframe filtering and <code>which</code> also use linear search, so as we could have expected they can’t be noticeably faster than <code>dplyr::filter</code>.</p>
<h2>Hash tables to the rescue?</h2>
<p>The problem of efficient lookups obviously is not R-specific. One of approaches is to use a <strong>hash table</strong>. In short, hash table is a very efficient data structure with constant lookup time. It is implemented in most of modern programming languages and widely used in many areas. If you’d like to read more about how hash tables work, there are lots of good articles about <a target="_blank" rel="nofollow" href="http://algs4.cs.princeton.edu/34hash/">that</a>.</p>
<p>R-bloggers has a great series of articles about hash tables in R: <a target="_blank" rel="nofollow" href="https://www.r-bloggers.com/hash-table-performance-in-r-part-i/">part 1</a>, <a target="_blank" rel="nofollow" href="https://www.r-bloggers.com/hash-table-performance-in-r-part-iiin-part-i-of-this-series-i-explained-how-r-hashed/">part 2</a>, <a target="_blank" rel="nofollow" href="https://www.r-bloggers.com/hash-table-performance-in-r-part-iiiin-part-iof-this-series-i-explained-how-r-hashed/">part 3</a>.<br>
The main conclusion of those articles is that if you need a hash table in R, you can use a data structure that is built into R: <strong><code>environments</code></strong>. <code>Environments</code> are used to keep binding of variables to values. Internally, they are implemented as a hash table. There is even a CRAN package <code>hash</code>, which wraps <code>environments</code> for general-purpose usage.<br>
<strong>However</strong>, these articles analyse performance of hash table with only 30 thousand elements… which is very small. Before we can use a hash.table, we need to create it. Building an environment with 10^7 elements is <em>extremely</em> slow: it takes more than an hour. For 10^6 elements it takes about 30 seconds.</p>
<div>
<pre><code data-lang="r"><span># Try it yourself:</span>

environment_source <span>&lt;-</span> setNames<span>(</span><span>as.list</span><span>(</span>data<span>$</span>col2<span>),</span> data<span>$</span>col1<span>)</span>
time<span>(</span><span>as.environment</span><span>(</span>environment_source<span>))</span></code></pre>
</div>
<p>This makes using environments as hash tables virtually impossible if your dataset has million or more elements. For example, if you’d like to build a hash table when at Shiny app startup, you would have to wait ages before the app actually starts. Such startup time is not acceptable in commercial solutions. Apparently, environments were never intended for storing that many elements. Indeed, their basic role is to store variables that your R code execution creates. There are not many situations where you would need to create that many variables in your R code.<br>
A workaround could be to build the environment once and load it from file, but (quite surprisingly) this turns out to be even slower.</p>
<p>I couldn’t find a good hash tables package for R that was not using environments underneath – please let me know if you know one! I can imagine that an efficient hash table R package will be created in the future, but till then we need to use other solutions.</p>
<h2>Data.table indexes</h2>
<p>It’s unfortunate that we can’t use hash tables for large datasets. However, when the column you are searching by is a number or a string, there is another option. You may use <strong>ordered indexes</strong> from <code>data.table</code> package.</p>
<p>Index keeps a sorted version of our column, which leads to much faster lookups. Finding an element in a sorted set with binary search has a logarithmic execution time – complexity of O(log n). In practice index can be implemented in different ways, but usually the time needed to build up an index is O(n*log n), which in practice is often fast enough.</p>
<p>Let’s measure the time needed to build the index for out dataset: </p>
<div>
<pre><code data-lang="r">time<span>(</span>setkey<span>(</span>data_table<span>,</span> col1<span>))</span></code></pre>
</div>
<div>
<pre><code data-lang="r"><span>5.645</span></code></pre>
</div>
<p>6 seconds – this is not negligible, but this is something we can live with. Let’s check the lookup times:</p>
<div>
<pre><code data-lang="r">benchmark<span>({</span>
  key_to_lookup <span>&lt;-</span> select_random_key<span>()</span>
  time<span>(</span>data_table<span>[</span><span>.</span><span>(</span>key_to_lookup<span>),</span> nomatch <span>=</span> <span>0L</span><span>])</span>
<span>})</span></code></pre>
</div>
<div>
<pre><code data-lang="r"><span>## min max mean </span>
<span>## 0.00200 0.01200 0.00455</span></code></pre>
</div>
<p>This is exactly what we wanted – a mean lookup time of 5 milliseconds! Finally, we’ve managed to get efficient lookups in our dataset.</p>
<h2>Summary</h2>
<p>Dplyr with its <code>filter</code> method will be slow if you want just to find a single element in a dataset.<br>
The same goes for classic data frame filtering with builtin R operators and for regular filtering using <code>data.table</code>.<br>
Using <code>environment</code> as a hash table gives you fast lookups, but building it for a large dataset takes ages.</p>
<p>If you need efficient lookups in a large dataset in R, check out data.table’s ordered indexes – this seems to be the best option out there!</p>
<p>
<div>
<div>To <strong>leave a comment</strong> for the author, please follow the link and comment on their blog: <strong><a href="http://blog.appsilondatascience.com/rstats/2017/03/02/r-fast-lookup.html"> Appsilon Data Science - R language</a></strong>.</div>
<hr>
<a rel="nofollow" href="https://www.r-bloggers.com/">R-bloggers.com</a> offers <strong><a rel="nofollow" href="https://feedburner.google.com/fb/a/mailverify?uri=RBloggers">daily e-mail updates</a></strong> about <a title="The R Project for Statistical Computing" rel="nofollow" href="https://www.r-project.org/">R</a> news and <a title="R tutorials" rel="nofollow" href="https://www.r-bloggers.com/search/tutorial">tutorials</a> on topics such as: <a title="Data science" rel="nofollow" href="https://www.r-bloggers.com/search/data%20science">Data science</a>, <a title="Big Data" rel="nofollow" href="https://www.r-bloggers.com/search/Big%20Data">Big Data, <a title="R jobs" rel="nofollow" href="https://www.r-users.com/">R jobs</a>, visualization (<a title="ggplot and ggplot2 tutorials" rel="nofollow" href="https://www.r-bloggers.com/search/ggplot2">ggplot2</a>, <a title="Boxplots using lattice and ggplot2 tutorials" rel="nofollow" href="https://www.r-bloggers.com/search/boxplot">Boxplots</a>, <a title="Maps and gis" rel="nofollow" href="https://www.r-bloggers.com/search/map">maps</a>, <a title="Animation in R" rel="nofollow" href="https://www.r-bloggers.com/search/animation">animation</a>), programming (<a title="RStudio IDE for R" rel="nofollow" href="https://www.r-bloggers.com/search/RStudio">RStudio</a>, <a title="Sweave and literate programming" rel="nofollow" href="https://www.r-bloggers.com/search/sweave">Sweave</a>, <a title="LaTeX in R" rel="nofollow" href="https://www.r-bloggers.com/search/LaTeX">LaTeX</a>, <a title="SQL and databases" rel="nofollow" href="https://www.r-bloggers.com/search/SQL">SQL</a>, <a title="Eclipse IDE for R" rel="nofollow" href="https://www.r-bloggers.com/search/eclipse">Eclipse</a>, <a title="git and github, Version Control System" rel="nofollow" href="https://www.r-bloggers.com/search/git">git</a>, <a title="Large data in R using Hadoop" rel="nofollow" href="https://www.r-bloggers.com/search/hadoop">hadoop</a>, <a title="Web Scraping of google, facebook, yahoo, twitter and more using R" rel="nofollow" href="https://www.r-bloggers.com/search/Web+Scraping">Web Scraping</a>) statistics (<a title="Regressions and ANOVA analysis tutorials" rel="nofollow" href="https://www.r-bloggers.com/search/regression">regression</a>, <a title="principal component analysis tutorial" rel="nofollow" href="https://www.r-bloggers.com/search/PCA">PCA</a>, <a title="Time series" rel="nofollow" href="https://www.r-bloggers.com/search/time+series">time series</a>, <a title="finance trading" rel="nofollow" href="https://www.r-bloggers.com/search/trading">trading</a>) and more...
<img height="1" alt="" width="1" src="http://feeds.feedburner.com/~r/RBloggers/~4/_SBLqBepbQU"></a></div>