<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/simpler-sql-with-dplyr/"></div></div><div></div></div><div></div></div>
<div>
(This article was first published on <strong><a href="https://www.johnmackintosh.com/2018-06-01-dplyr-for-the-win/"> HighlandR</a></strong>, and kindly contributed to <a rel="nofollow" href="https://www.r-bloggers.com/">R-bloggers)</a> </div>
<p>	comparing dplyr with SQL nested queries – </p>
<p>Following on from my <a rel="nofollow" href="https://www.johnmackintosh.com/2018-05-13-apha-scotland-it-s-a-thing/" target="_blank">last post</a>, where I demonstrated R to some first time R users, I want to do a wee comparison of dplyr V SQL, so that folks, particularly those in the NHS who might be R curious, can see just what the fuss is about.</p>
<p>To do so I want to recap on the example I showed at the AphA Scotland event.</p>
<p>This,in turn goes back to some work I’ve been doing with Neil Pettinger, where we are looking <a rel="nofollow" href="https://www.johnmackintosh.com/2017-12-21-flow/" target="_blank">at ways to visualise patient flow.</a></p>
<p>This relies on a spreadsheet that Neil originally put together. Part of my demo was to explain how to recreate the visualisation in R, but I also showed some of the data transformation steps carried out using dplyr and some fellow tidyverse helpers.</p>
<p>In <em>this</em> post I want to focus on that a but further, by showing the SQL code I would write to arrive at the same end result.</p>
<p>In order to do this I imported Neil’s spreadsheet (which I’ve uploaded – with Neil’s permission to the repo <a rel="nofollow" href="https://github.com/johnmackintosh/RowOfDots" target="_blank">here</a>) to into a SQL Server table (by using the built in import wizard, for a quick but not reproducible way of ingesting the data).</p>
<p>Here’s how that looks:</p>
<p><img alt="20180531-basic-table.PNG" src="https://i0.wp.com/www.johnmackintosh.com/img/20180531-basic-table.PNG?w=456&ssl=1" data-recalc-dims="1"></p>
<p>NB – ALL patient names are entirely made up.</p>
<p>As a reminder, for this task we need to create a column that mimics Excel’s floor function and reduces the MovementDateTime field to the nearest 15 mins. We also want to get a count of how many patient were either moving IN or OUT during each 15 minute segment of the day.</p>
<p></p>
<p>You’d need to replace the database and table names to suit.<br>
I’m not going to explain the code for flooring the datetime field – just know that it works, but you may want to compare the syntax for the case when statement with the equivalent dplyr code ( see later).</p>
<p>Here is the table output – with the 2 new columns at the end:</p>
<p><img alt="20180531-first-revised-table.PNG" src="https://i1.wp.com/www.johnmackintosh.com/img/20180531-first-revised-table.PNG?w=456&ssl=1" data-recalc-dims="1"></p>
<p>Now things get more complicated.</p>
<p>I have a counter field, but I want to get a cumulative count by each 15 minute segment, staging post and whether this was a movement in or out.</p>
<p>One way to do this is to wrap the original query inside another query, so that our newly created counter column can be utilised. This is a similar idea to the the method of mutating a column in dplyr, and having it available within the next pipe.</p>
<p>We have to make use of SQL’s windowing functionality to create virtual groupings and orders within the data ( SQL is a set based language, and there is no concept of row order within a set. Therefore to get a cumulative count, we need to make SQL think in terms of rows by partitioning the data by the desired grouping columns and providing columns to order by):</p>
<p></p>
<p>Understanding windowing techniques is a great SQL skill to have. Don’t forget where you first saw this ;)!</p>
<p>A couple of things to note here are that when we wrap or “nest” the original query, I gave it the alias ‘x’. You do need to provide an alias for this inner query, or the outer query won’t work.<br>
Although not strictly necessary, I also prefixed the column names in the outer query so it’s clear that I am selecting the columns from the “virtual” table defined by the inner query.</p>
<p>Here’s the output with our new Row number (or RNumber) field.</p>
<p><img alt="20180531-row-number.PNG" src="https://i1.wp.com/www.johnmackintosh.com/img/20180531-row-number.PNG?w=456&ssl=1" data-recalc-dims="1"></p>
<p>Almost done, but this is still not in the right format – I need to get an accurate cumulative count.<br>
Once more, <em>I take the previous query, and nest that inside a new query</em> – so you can see this is similar to lots of base R style manipulation where the code starts from the middle, or an end, and works back.</p>
<p></p>
<p>To recap – our first query floored the movement time to 15 minute intervals and gave us a counter field, we then used that counter field to generate a row number field.<br>
Now, even if I’d ordered the result of the second query by MovementDateTime, it still wouldn’t suffice because the rownumbers are all positive, and I want them to be negative when the movement was a movement OUT.</p>
<p>We can’t manipulate the row number field within the same query that it is created, so we nest the whole lot once more, this time arranging in the correct time order and multiplying the counter field by our row number field.</p>
<p>You’ll notice the second query has been aliased (with a ‘y’) and the columns prefixed so that is is clear exactly where the query is obtaining the data from.</p>
<p>This gives us our final output:</p>
<p><img alt="20180531-seq-number.PNG" src="https://i1.wp.com/www.johnmackintosh.com/img/20180531-seq-number.PNG?w=456&ssl=1" data-recalc-dims="1"></p>
<p>A reminder of the dplyr code I used:</p>
<p></p>
<p>And here is the output – compare with above..</p>
<p><img alt="20180531-dplyr.PNG" src="https://i2.wp.com/www.johnmackintosh.com/img/20180531-dplyr.PNG?w=456&ssl=1" data-recalc-dims="1"></p>
<p>A lot more elegant? Definitely.</p>
<p>Another approach to writing the code in SQL would be to use a Common Table Expression, which is a more straightforward of writing and reading it. It’s a similar idea in that you create virtual tables with queries that then run top to bottom until you get your final output.<br>
However that is a post for another day <img alt="🙂" src="https://s.w.org/images/core/emoji/2.4/72x72/1f642.png" class="wp-smiley"></p>
<p><strong>What I hope you get from this post is that dplyr and other packages (lubridate for example) really do make life easier for data manipulation.</strong></p>
<p>Look at the SQL for flooring the date, compared to the lubridate call.<br>
Look at the elegance of mutating new columns and having them available within the next chain, compared to horrendous multi-layered nested queries (this one was pretty tame – imagine a few more levels on top of that).<br>
You can see how traditional SQL can get unwieldy.</p>
<p>Dplyr is a fantastic asset to the R community, and I hope it might prove to be a great hook to get R further established within the analytical departments of the NHS.</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="https://www.johnmackintosh.com/2018-06-01-dplyr-for-the-win/"> HighlandR</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 rel="nofollow" href="https://www.r-project.org/" 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="https://www.r-users.com/" 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/TC4lIcyIREE" height="1"></a></div>