<p><div><div><div><div data-show-faces="false" data-height="21" data-width="100" data-layout="button_count" data-send="true" data-href="https://www.r-bloggers.com/drilling-into-csvs-teaser-trailer/"></div></div><div></div></div><div></div></div>
<div>
(This article was first published on <strong><a href="http://apicdn.viglink.com/api/click?format=go&key=949efb41171ac6ec1bf7f206d57e90b8&loc=https%3A%2F%2Fwww.r-bloggers.com%2Ffeed%2F&out=https%3A%2F%2Frud.is%2Fb%2F2017%2F05%2F31%2Fdrilling-into-csvs-teaser-trailer%2F&ref=http%3A%2F%2Fwww.r-bloggers.com%2Ffeed"> R – rud.is</a></strong>, and kindly contributed to <a rel="nofollow" href="https://www.r-bloggers.com/">R-bloggers)</a> </div>
<p>I used reading a directory of CSVs as the foundational example in my recent post on <a rel="nofollow" href="http://apicdn.viglink.com/api/click?format=go&key=949efb41171ac6ec1bf7f206d57e90b8&loc=https%3A%2F%2Fwww.r-bloggers.com%2Ffeed%2F&out=https%3A%2F%2Frud.is%2Fb%2F2017%2F05%2F23%2Fr%25E2%2581%25B6-idiomatic-for-the-people%2F&ref=http%3A%2F%2Fwww.r-bloggers.com%2Ffeed" target="_blank">idioms</a>.</p>
<p>During my exchange with Matt, Hadley and a few others — in the crazy Twitter thread that spawned said post — I mentioned that I’d personally <em>“just use <a rel="nofollow" href="http://apicdn.viglink.com/api/click?format=go&key=949efb41171ac6ec1bf7f206d57e90b8&loc=https%3A%2F%2Fwww.r-bloggers.com%2Ffeed%2F&out=https%3A%2F%2Fdrill.apache.org%2F&ref=http%3A%2F%2Fwww.r-bloggers.com%2Ffeed" target="_blank">Drill</a>”</em>.</p>
<p>I’ll use this post as a bit of a teaser trailer for the actual post (or, more likely, series of posts) that goes into detail on where to get Apache Drill, basic setup of Drill for standalone workstation use and then organizing data with it. </p>
<p>You can get ahead of those posts by doing two things: </p>
<ol>
<li><a rel="nofollow" href="http://apicdn.viglink.com/api/click?format=go&key=949efb41171ac6ec1bf7f206d57e90b8&loc=https%3A%2F%2Fwww.r-bloggers.com%2Ffeed%2F&out=https%3A%2F%2Fdrill.apache.org%2Fdocs%2Fdrill-in-10-minutes%2F&ref=http%3A%2F%2Fwww.r-bloggers.com%2Ffeed" target="_blank">Download, install and test your Apache Drill setup</a> (it’s literally 10 minutes on any platform)</li>
<li>Review the U.S. EPA <a rel="nofollow" href="http://apicdn.viglink.com/api/click?format=go&key=949efb41171ac6ec1bf7f206d57e90b8&loc=https%3A%2F%2Fwww.r-bloggers.com%2Ffeed%2F&out=https%3A%2F%2Faqsdr1.epa.gov%2Faqsweb%2Faqstmp%2Fairdata%2Fdownload_files.html%23Annual&ref=http%3A%2F%2Fwww.r-bloggers.com%2Ffeed" target="_blank">annual air quality data archive</a> (they have individual, annual CSVs that are perfect for the example)</li>
</ol>
<p>My goals for this post are really to just to pique your interest enough in Drill and parquet files (yes, I’m ultimately trying to socially engineer you into using parquet files) to convince you to read the future post(s) and show that it’s worth your time to do Step #1 above.</p>
<h3>Getting EPA Air Quality Data</h3>
<p>The EPA has air quality data going back to 1990 (so, 27 files as of this post). They’re ~1-4MB ZIP compressed and ~10-30MB uncompressed.</p>
<p>You can use the following code to grab them all with the caveat that the <code>libcurl</code> method of performing simultaneous downloads caused some pretty severe issues — like R crashing — for some of my students who use Windows. There are plenty of examples for doing sequential downloads of a list of URLs out there that folks should be able to get all the files even if this succinct method does not work on your platform.</p>
<pre><code>dir.create(&quot;airq&quot;)

urls &lt;- sprintf(&quot;https://aqsdr1.epa.gov/aqsweb/aqstmp/airdata/annual_all_%d.zip&quot;, 1990L:2016L)
fils &lt;- sprintf(&quot;airq/%s&quot;, basename(urls))

download.file(urls, fils, method = &quot;libcurl&quot;)</code></pre>
<p>I normally shy away from this particular method since it really hammers the remote server, but this is a beefy U.S. government server, the files are relatively small in number and size and I’ve got a super-fast internet connection (no long-lived sockets) so it should be fine.</p>
<p>Putting all those files under the “control” of Drill is what the next post is for. For now, i’m going to show the basic code and benchmarks for reading in all those files and performing a basic query for all the distinct years. Yes, we know that information already, but it’s a nice, compact task that’s easy to walk through and illustrates the file reading and querying in all three idioms: Drill, tidyverse and data.table.</p>
<h3>Data Setup</h3>
<p>I’ve converted the EPA annual ZIP files into <code>bzip2</code> format. ZIP is fine for storage and downloads but it’s not a great format for data analysis tasks. <code>gzip</code> would be slightly faster but it’s not <a rel="nofollow" href="http://apicdn.viglink.com/api/click?format=go&key=949efb41171ac6ec1bf7f206d57e90b8&loc=https%3A%2F%2Fwww.r-bloggers.com%2Ffeed%2F&out=http%3A%2F%2Fcomphadoop.weebly.com%2F&ref=http%3A%2F%2Fwww.r-bloggers.com%2Ffeed" target="_blank">easily splittable</a> and — even though I’m not using the data in a Hadoop context — I think it’s wiser to not have to re-process data later on if I ever had to move raw CSV or JSON data into Hadoop. Uncompressed CSVs are the most portable, but there’s no need to waste space.</p>
<p>All the following files are in a regular filesystem directory accessible to both Drill and R:</p>
<pre><code>> (epa_annual_fils &lt;- dir(&quot;~/Data/csv/epa/annual&quot;, &quot;*.csv.bz2&quot;))
 [1] &quot;annual_all_1990.csv.bz2&quot; &quot;annual_all_1991.csv.bz2&quot; &quot;annual_all_1992.csv.bz2&quot;
 [4] &quot;annual_all_1993.csv.bz2&quot; &quot;annual_all_1994.csv.bz2&quot; &quot;annual_all_1995.csv.bz2&quot;
 [7] &quot;annual_all_1996.csv.bz2&quot; &quot;annual_all_1997.csv.bz2&quot; &quot;annual_all_1998.csv.bz2&quot;
[10] &quot;annual_all_1999.csv.bz2&quot; &quot;annual_all_2000.csv.bz2&quot; &quot;annual_all_2001.csv.bz2&quot;
[13] &quot;annual_all_2002.csv.bz2&quot; &quot;annual_all_2003.csv.bz2&quot; &quot;annual_all_2004.csv.bz2&quot;
[16] &quot;annual_all_2005.csv.bz2&quot; &quot;annual_all_2006.csv.bz2&quot; &quot;annual_all_2007.csv.bz2&quot;
[19] &quot;annual_all_2008.csv.bz2&quot; &quot;annual_all_2009.csv.bz2&quot; &quot;annual_all_2010.csv.bz2&quot;
[22] &quot;annual_all_2011.csv.bz2&quot; &quot;annual_all_2012.csv.bz2&quot; &quot;annual_all_2013.csv.bz2&quot;
[25] &quot;annual_all_2014.csv.bz2&quot; &quot;annual_all_2015.csv.bz2&quot; &quot;annual_all_2016.csv.bz2&quot;</code></pre>
<p>Drill can directly read plain or compressed JSON, CSV and Apache web server log files plus can treat a directory tree of them as a single data source. It can also read parquet &amp; avro files (both are used frequently in distributed “big data” setups) and access MySQL, MongoDB and other JDBC resources as well as query data stored in Amazon S3 and HDFS (I’ve already mentioned it works fine in plain ‘ol filesystems, too).</p>
<p>I’ve tweaked my Drill configuration to support reading column header info from <code>.csv</code> files (which I’ll show in the next post). In environments like Drill or even Spark, CSV columns are usually queried with some type of column index (e.g. <code>COLUMN[0]</code>) so having named columns makes for less verbose query code.</p>
<p>I turned those individual <code>bzip2</code> files into parquet format with one Drill query:</p>
<pre><code>CREATE TABLE dfs.pq.`/epa/annual.parquet` AS 
  SELECT * FROM dfs.csv.`/epa/annual/*.csv.bz2`</code></pre>
<p>Future posts will explain the <code>dfs...</code> component but they are likely familiar path specifications for folks used to Spark and are pretty straightforward. The first bit (up to the back-tick) is an internal Drill shortcut to the actual storage path (which is a plain directory in this test) followed by the tail end path spec to the subdirectories and/or target files. That one statement said ‘take all the CSV files in that directory and make one big table out of them”.</p>
<p>The nice thing about parquet files is that they work much like R data frames in that they can be processed on the column level. We’ll see how that speeds up things in a bit.</p>
<h3>Benchmark Setup</h3>
<p>The tests were performed on a maxed out 2016 13″ MacBook Pro.</p>
<p>There are 55 columns of data in the EPA annual summary files.</p>
<p>To give both <code>read_csv</code> and <code>fread</code> some benchmark boosts, we’ll define the columns up-front and pass those in to each function on data ingestion and I’ll leave them out of this post for brevity (they’re just a <code>cols()</code> specification and <code>colClasses</code> vector). Drill gets no similar help for this at least when it comes to CSV processing.</p>
<p>I’m also disabling progress &amp; verbose reporting in both <code>fread</code> and <code>read_csv</code> despite not stopping Drill from writing out log messages. </p>
<p>Now, we need some setup code to connect to drill and read in the list of files, plus we’ll setup the five benchmark functions to read in all the files and get the list of distinct years from each.</p>
<pre><code>library(sergeant)
library(data.table)
library(tidyverse)

(epa_annual_fils &lt;- dir(&quot;~/Data/csv/epa/annual&quot;, &quot;*.csv.bz2&quot;, full.names = TRUE))

db &lt;- src_drill(&quot;localhost&quot;)

# Remember, defining ct &amp; ct_dt - the column types specifications - have been left out for brevity

mb_drill_csv &lt;- function() {
  epa_annual &lt;- tbl(db, &quot;dfs.csv.`/epa/annual/*.csv.bz2`&quot;)
  select(epa_annual, Year) %>% 
    distinct(Year) %>% 
    collect()
}

mb_drill_parquet &lt;- function() {
  epa_annual_pq &lt;- tbl(db, &quot;dfs.pq.`/epa/annual.parquet`&quot;)
  select(epa_annual_pq, Year) %>% 
    distinct(Year) %>% 
    collect()
}

mb_tidyverse &lt;- function() {
  map_df(epa_annual_fils, read_csv, col_types = ct, progress = FALSE) -> tmp
  unique(tmp$Year)
}

mb_datatable &lt;- function() {
  rbindlist(
    lapply(
      epa_annual_fils, function(x) { 
        fread(sprintf(&quot;bzip2 -c -d %s&quot;, x), 
              colClasses = ct_dt, showProgress = FALSE, 
              verbose = FALSE) })) -> tmp
  unique(tmp$Year)
}

mb_rda &lt;- function() {
  read_rds(&quot;~/Data/rds/epa/annual.rds&quot;) -> tmp
  unique(tmp$Year)
}

microbenchmark(
  csv = { mb_drill_csv()     },
   pq = { mb_drill_parquet() },
   df = { mb_tidyverse()     },
   dt = { mb_datatable()     },
  rda = { mb_rda()           },
  times = 5
) -> mb</code></pre>
<p>Yep, it’s really as simple as:</p>
<pre><code>tbl(db, &quot;dfs.csv.`/epa/annual/*.csv.bz2`&quot;)</code></pre>
<p>to have Drill treat a directory tree as a single table. It’s also not necessary for all the columns to be in all the files (i.e. you get the <code>bind_rows/map_df/rbindlist</code> behaviour for “free”).</p>
<p>I’m only doing 5 evaluations here since I don’t want to make you wait if you’re going to try this at home now or after the Drill series. I’ve run it with a more robust benchmark configuration and the results are aligned with this one.</p>
<pre><code>Unit: milliseconds
 expr        min         lq       mean     median         uq        max neval
  csv 15473.5576 16851.0985 18445.3905 19586.1893 20087.1620 20228.9450     5
   pq   493.7779   513.3704   616.2634   550.5374   732.6553   790.9759     5
   df 41666.1929 42361.1423 42701.2682 42661.9521 43110.3041 43706.7498     5
   dt 37500.9351 40286.2837 41509.0078 42600.9916 43105.3040 44051.5247     5
  rda  9466.6506  9551.7312 10012.8560  9562.9114  9881.8351 11601.1517     5</code></pre>
<p>The R data route, which is the closest to the parquet route, is definitely better than slurping up CSVs all the time. Both parquet and R data files require pre-processing, so they’re not as flexible as having individual CSVs (that may get added hourly or daily to a directory).</p>
<p>Drill’s CSV slurping handily beats the other R methods even with some handicaps the others did not have.</p>
<p>This particular example is gamed a bit, which helped parquet to ultimately “win”. Since Drill can target the singular column (<code>Year</code>) that was asked for, it doesn’t need to read all the extra columns just to compute the final product (the distinct list of years).</p>
<p>IMO both the Drill CSV ingestion and Drill parquet access provide compelling enough use-cases to use them over the other three methods, especially since they are easily transferrable to remote Drill servers or clusters with virtually no code changes. A single node Drillbit (like R) is constrained by the memory on that individual system, so it’s not going to get you out of a memory jam, but it may make it easier to organize and streamline your core data operations before other analysis and visualization tasks.</p>
<h3>FIN</h3>
<p>I’m sure some member of some other tribe will come up with an example that proves superiority of their particular tribal computations. I’m hoping one of those tribes is the R/Spark tribe so that can get added into the mix (using Spark standalone is much like using Drill, but with more stats/ML functions directly available). </p>
<p>I’m hopeful that this post has showcased enough of Drill’s utility to general R users that you’ll give it a go and consider adding it to your R data analysis toolbox. It can be beneficial having both a precision tools as well as a Swiss Army knife — which is what Drill really is — handy.</p>
<p>You can find the <code>sergeant</code> package <a rel="nofollow" href="http://apicdn.viglink.com/api/click?format=go&key=949efb41171ac6ec1bf7f206d57e90b8&loc=https%3A%2F%2Fwww.r-bloggers.com%2Ffeed%2F&out=https%3A%2F%2Fgithub.com%2Fhrbrmstr%2Fsergeant&ref=http%3A%2F%2Fwww.r-bloggers.com%2Ffeed" target="_blank">on GitHub</a>.</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://apicdn.viglink.com/api/click?format=go&key=949efb41171ac6ec1bf7f206d57e90b8&loc=https%3A%2F%2Fwww.r-bloggers.com%2Ffeed%2F&out=https%3A%2F%2Frud.is%2Fb%2F2017%2F05%2F31%2Fdrilling-into-csvs-teaser-trailer%2F&ref=http%3A%2F%2Fwww.r-bloggers.com%2Ffeed"> R – rud.is</a></strong>.</div>
<hr>
<a rel="nofollow" href="https://www.r-bloggers.com/">R-bloggers.com</a> offers <strong><a rel="nofollow" href="http://apicdn.viglink.com/api/click?format=go&key=949efb41171ac6ec1bf7f206d57e90b8&loc=https%3A%2F%2Fwww.r-bloggers.com%2Ffeed%2F&out=https%3A%2F%2Ffeedburner.google.com%2Ffb%2Fa%2Fmailverify%3Furi%3DRBloggers&ref=http%3A%2F%2Fwww.r-bloggers.com%2Ffeed">daily e-mail updates</a></strong> about <a rel="nofollow" href="http://apicdn.viglink.com/api/click?format=go&key=949efb41171ac6ec1bf7f206d57e90b8&loc=https%3A%2F%2Fwww.r-bloggers.com%2Ffeed%2F&out=https%3A%2F%2Fwww.r-project.org%2F&ref=http%3A%2F%2Fwww.r-bloggers.com%2Ffeed" title="The R Project for Statistical Computing">R</a> news and <a rel="nofollow" href="https://www.r-bloggers.com/search/tutorial" title="R tutorials">tutorials</a> on topics such as: <a rel="nofollow" href="https://www.r-bloggers.com/search/data%20science" title="Data science">Data science</a>, <a rel="nofollow" href="https://www.r-bloggers.com/search/Big%20Data" title="Big Data">Big Data, <a rel="nofollow" href="http://apicdn.viglink.com/api/click?format=go&key=949efb41171ac6ec1bf7f206d57e90b8&loc=https%3A%2F%2Fwww.r-bloggers.com%2Ffeed%2F&out=https%3A%2F%2Fwww.r-users.com%2F&ref=http%3A%2F%2Fwww.r-bloggers.com%2Ffeed" title="R jobs">R jobs</a>, visualization (<a rel="nofollow" href="https://www.r-bloggers.com/search/ggplot2" title="ggplot and ggplot2 tutorials">ggplot2</a>, <a rel="nofollow" href="https://www.r-bloggers.com/search/boxplot" title="Boxplots using lattice and ggplot2 tutorials">Boxplots</a>, <a rel="nofollow" href="https://www.r-bloggers.com/search/map" title="Maps and gis">maps</a>, <a rel="nofollow" href="https://www.r-bloggers.com/search/animation" title="Animation in R">animation</a>), programming (<a rel="nofollow" href="https://www.r-bloggers.com/search/RStudio" title="RStudio IDE for R">RStudio</a>, <a rel="nofollow" href="https://www.r-bloggers.com/search/sweave" title="Sweave and literate programming">Sweave</a>, <a rel="nofollow" href="https://www.r-bloggers.com/search/LaTeX" title="LaTeX in R">LaTeX</a>, <a rel="nofollow" href="https://www.r-bloggers.com/search/SQL" title="SQL and databases">SQL</a>, <a rel="nofollow" href="https://www.r-bloggers.com/search/eclipse" title="Eclipse IDE for R">Eclipse</a>, <a rel="nofollow" href="https://www.r-bloggers.com/search/git" title="git and github, Version Control System">git</a>, <a rel="nofollow" href="https://www.r-bloggers.com/search/hadoop" title="Large data in R using Hadoop">hadoop</a>, <a rel="nofollow" href="https://www.r-bloggers.com/search/Web+Scraping" title="Web Scraping of google, facebook, yahoo, twitter and more using R">Web Scraping</a>) statistics (<a rel="nofollow" href="https://www.r-bloggers.com/search/regression" title="Regressions and ANOVA analysis tutorials">regression</a>, <a rel="nofollow" href="https://www.r-bloggers.com/search/PCA" title="principal component analysis tutorial">PCA</a>, <a rel="nofollow" href="https://www.r-bloggers.com/search/time+series" title="Time series">time series</a>, <a rel="nofollow" href="https://www.r-bloggers.com/search/trading" title="finance trading">trading</a>) and more...
<img width="1" alt="" src="http://feeds.feedburner.com/~r/RBloggers/~4/QbNGxb7TcVc" height="1"></a></div>