<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/why-to-use-wraprlet/"></div></div><div></div></div><div></div></div>
<div>
(This article was first published on <strong><a href="http://www.win-vector.com/blog/2017/05/why-to-use-wraprlet/"> R – Win-Vector Blog</a></strong>, and kindly contributed to <a rel="nofollow" href="https://www.r-bloggers.com/">R-bloggers)</a> </div>
<p>I have written about <a target="_blank" rel="nofollow" href="https://en.wikipedia.org/wiki/Referential_transparency">referential transparency</a> <a target="_blank" rel="nofollow" href="http://www.win-vector.com/blog/2017/04/programming-over-r/">before</a>. In this article I would like to discuss “<a target="_blank" rel="nofollow" href="https://www.joelonsoftware.com/2002/11/11/the-law-of-leaky-abstractions/">leaky abstractions</a>” and why <a target="_blank" rel="nofollow" href="https://cran.r-project.org/package=wrapr"><code>wrapr::let()</code></a> supplies a useful (but leaky) abstraction for <a target="_blank" rel="nofollow" href="https://cran.r-project.org/"><code>R</code></a> programmers.</p>
<p><a target="_blank" rel="nofollow" href="https://cran.r-project.org/package=wrapr"><img title="wraprs.png" alt="Wraprs" src="https://i1.wp.com/www.win-vector.com/blog/wp-content/uploads/2017/05/wraprs.png?resize=118%2C118" border="0" data-recalc-dims="1"></a><span></span></p>
<p>
<h2>Abstractions</h2>
<p>A common definition of an abstraction is (from the <code>OSX</code> dictionary):</p>
<blockquote><p>the process of considering something independently of its associations, attributes, or concrete accompaniments.</p>
</blockquote>
<p>In computer science this is commonly taken to mean “what something can be thought to do independent of caveats and implementation details.” </p>
<h3>The <code>magrittr</code> abstraction</h3>
<p>In <a target="_blank" rel="nofollow" href="https://cran.r-project.org/"><code>R</code></a> one traditionally thinks of the <a target="_blank" rel="nofollow" href="https://cran.r-project.org/package=magrittr%20t"><code>magrittr &quot;%>%&quot;</code> pipe</a> abstractly in the following way:</p>
<pre>
 Once &quot;library(magrittr)&quot; is loaded we can treat the expression:

   <code>7 %>% sqrt()</code>

 as if the programmer had written:

   <code>sqrt(7)</code>
 .
</pre>
<p>That is the abstraction of <code>magrittr</code> into terms one can reason about and plan over. You think of <code>x %>% f()</code> as a synonym for <code>f(x)</code>. This is an abstraction because <code>magrittr</code> is not in fact implemented as a macro source-code re-write, but in in terms of function argument capture and delayed evaluation. And as Joel Spolsky famously wrote:</p>
<blockquote><p>All non-trivial abstractions, to some degree, are leaky.</p>
</blockquote>
<p>The <code>magrittr</code> pipe is non-trivial (in the sense of doing interesting work) because it works as if it were a syntax replacement even though you can use it more places than you could ask for such a syntax replacement. The upside is: <code>magrittr</code> makes two statements behave nearly equivalently. The downside is: we expect this to fail in some corner cases. This is not a criticism; it is as Bjarne Stroustrup wrote:</p>
<blockquote><p>There are only two kinds of languages: the ones people complain about and the ones nobody uses.</p>
</blockquote>
<h3>The <code>tidyeval</code>/<code>rlang</code> abstraction</h3>
<p>The package <code>dplyr 0.6.*</code> brings in a new package called <code>rlang</code> to supply a capability called <code>tidyeval</code>. Among the abstractions it supplies are: operators for quoting and un-quoting variable names. This allows code like the following, where a <code>dplyr::select()</code> takes a variable name from a user supplied variable (instead of the usual explicit take from the text of the <code>dplyr::select()</code> statement).</p>
<pre>
library(&quot;dplyr&quot;)
packageVersion(&quot;dplyr&quot;)
 # [1] ‘0.5.0.9004’
varName = quo(disp)
mtcars %>% select(!!varName) %>% head()
 #                   disp
 # Mazda RX4          160
 # Mazda RX4 Wag      160
 # Datsun 710         108
 # Hornet 4 Drive     258
 # Hornet Sportabout  360
 # Valiant            225
</pre>
<p>Notice in the above example we had to specify the abstract <code>varName</code> by calling <code>quo()</code> on a free variable name (<code>disp</code>) and did not take the value from a string. <code>tidyeval</code> is working hard to supply a parametrizable non-standard interface, and it doesn’t look like a standard interface is the central goal. That is: the following is not intended to work:</p>
<pre>
varName &lt;- quo(colnames(mtcars)[[1]])
mtcars %>% select(!!varName) %>% head()
 # Error: colnames(mtcars)[[1]]: must resolve to integer column positions, not string 
</pre>
<p>This is unfortunate as the main reason you want to parameterize over variable names is that the names are coming from somewhere else, and likely supplied as strings not as <code>quosure</code>s (which themselves carry details of environment, meaning they are more like bound variables than free variables). I am sure you can convert a string into a column reference in <code>rlang/tidyeval</code> but it doesn’t seem to be the central use case (or is least not held out as such in the help and examples).</p>
<h3>The <code>wrapr::let()</code> abstraction</h3>
<p>Our <code>wrapr</code> package can abstract the recent example (working over strings instead of “<code>quosure</code>” classes) as follows.</p>
<p>The (leaky) abstraction is: </p>
<blockquote><p>
“<code>varName &lt;- 'var'; wrapr::let(VAR=varName, expr(VAR))</code>” is treated as if the user had written <code>expr(var)</code>.
</p>
</blockquote>
<p>This can be also thought of as form of unquoting as you do see one set of quotes disappear.</p>
<p>Let’s try it:</p>
<pre>
library(&quot;wrapr&quot;)
x &lt;- 5
varName &lt;- 'x'
let(c(VAR=varName), VAR)
 # [1] 5
</pre>
<p>Or moving back to our <code>dplyr::select()</code> example:</p>
<pre>
varName &lt;- 'disp'
let(
  c(VARNAME = varName),
  mtcars %>% select(VARNAME) %>% head()
)
 #                    disp
 # Mazda RX4          160
 # Mazda RX4 Wag      160
 # Datsun 710         108
 # Hornet 4 Drive     258
 # Hornet Sportabout  360
 # Valiant            225
</pre>
<p>And <code>wrapr::let()</code> can also conveniently handle the “<code>varName &lt;- colnames(mtcars)[[1]]</code>” case.</p>
<h2>An issue</h2>
<p><a target="_blank" rel="nofollow" href="https://github.com/tidyverse/dplyr/issues/2726"><code>dplyr</code> issue 2726</a> (reproduced below) discusses a very important and interesting issue.</p>
<p><center><br>
<a target="_blank" rel="nofollow" href="https://github.com/tidyverse/dplyr/issues/2726"><img title="2726.png" alt="2726" src="https://i1.wp.com/www.win-vector.com/blog/wp-content/uploads/2017/05/2726.png?w=660" border="0" data-recalc-dims="1"></a><br>
</center></p>
<p>At a cursory glance the two discussed expressions and the work-around may seem alien, artificial, or even silly:</p>
<ol>
<li><code>(function(x) select(mtcars, !!enquo(x)))(disp)</code></li>
<li><font color="red"><code>(function(x) mtcars %>% select(!!enquo(x)))(disp)</code></font></li>
<li><code>(function(x) { x &lt;- enquo(x); mtcars %>% select(!!x)})(disp)<br>
</code></li>
</ol>
<p>However, this is actually a very crisp and incisive example. In fact, if <code>rlang</code>/<code>tidyeval</code> were a system up for public revision (such as a <a target="_blank" rel="nofollow" href="https://en.wikipedia.org/wiki/Request_for_Comments">RFC</a> or some such proposal) you would expect the equivalence of the above to be part of an acceptance suite.</p>
<p>The first expression looks very much like <code>rlang</code>/<code>tidyeval</code> package examples and is the “right way” in <code>rlang</code>/<code>tidyeval</code> to send in a column name parametrically. It is in the style preferred by the new package so by the <em>package</em> standards can not be considered complicated, perverse, or verbose. The second expression differs from the first only by the application of the “<code>magrittr</code> invariant” of “<code>x %>% f()</code> is to be considered equivalent to <code>f(x)</code>“.</p>
<p>The outcome is the first expression currently executes as expected, and the second expression errors-out. This can be considered surprising as this is not something anticipated in the documentation or recipes for building up tidy expressions. This is a leak in the combined abstractions, something we are told to back away from as it doesn’t work.</p>
<p>The proposed work-around (expression 3) is helpful, but itself demonstrates another leak in the mutual abstractions. Think of it this way: suppose we had started with expression 3 as working code. We would by referential transparency expect to be able to refactor the code and replace <code>x</code> with its value and move from this third working example to the second expression (which happens to fail).</p>
<p>To summarize: expressions 1 and 3 are equivalent. They differ by two refactoring steps (introduction/removal of pipes, and introduction/removal of a temporary variable). But we can not demonstrate the equivalence by interpolating in 2 named transformations (going from 1 to 2 to 3, or from 3 to 2 to 1) as the intermediate expression 2 is apparently not valid.</p>
<p>The wrapr::let version of the issue author’s desired expression 2 is:</p>
<pre>
  (function(x) let(c(X = x), mtcars %>% select(X)))('disp')
</pre>
<h2>Conclusion</h2>
<p><code>wrapr::let()</code> is a useful abstraction:</p>
<ul>
<li>It directly takes strings as variable names (the most common source of parametric variable names).</li>
<li>It is a marco-like replacement and easy to teach as a code re-writing abstraction.</li>
<li>It has a small interaction surface, and plays well with delayed evaluation packages such as <code>magrittr</code> and <code>dplyr 0.5.0</code>.</li>
</ul>
<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://www.win-vector.com/blog/2017/05/why-to-use-wraprlet/"> R – Win-Vector Blog</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/FYTwFnnb-m0"></a></div>