<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/promises-and-closures-in-r/"></div></div><div></div></div><div></div></div>
<div>
(This article was first published on <strong><a href="https://www.inwt-statistics.com/read-blog/promises-and-closures-in-r.html"> INWT-Blog-RBloggers</a></strong>, and kindly contributed to <a rel="nofollow" href="https://www.r-bloggers.com/">R-bloggers)</a> </div>
<div>
<p>At the moment I try to improve my knowledge about functional programming in R. Luckily there are some explanations on the topic in the web (<a rel="nofollow" href="http://adv-r.had.co.nz/Functional-programming.html" target="_blank">adv-r</a> and <a rel="nofollow" href="https://cartesianfaith.com/2017/04/14/modeling-data-with-functional-programming-part-i/" target="_blank">Cartesian Faith</a>). Beginning to (re)discover the usefulness of closures, I remember some (at first sight) very strange behaviour. Actually it is consistent within the scoping rules of <a rel="nofollow" href="http://cran.r-project.org/" target="_blank">R</a>, but until I felt to be on the same level of consistency it took a while.</p>
</div>
<div>
<h2>What is a Promise?</h2>
<p>Every argument you pass to a function is a promise until the moment R evaluates it. Consider a function <em>g</em> with arguments <em>x</em> and <em>y.</em> Let’s leave out one argument in the function call:</p>
</div>
<pre><pre><code>g &lt;- function(x, y) x g(1) ## [1] 1 </code></pre></pre>
<div>
<p>R will be forgiving (lazy) until the argument <em>y</em> is actually needed. Until then <em>y</em> exists in the environment of the function call as a ‘name without a value’. Only when R needs to evaluate <em>y</em> a value is searched for. This means that we can pass some non-existent objects as arguments to the function <em>g</em> and R won’t care until the argument is needed in the functions body.</p>
</div>
<pre><pre><code>g(1, nonExistentObject) ## [1] 1 </code></pre></pre>
<div>
<p>Have a look at the figure ‘Environment Path 1’. Your workspace is also called the Global Environment and you can access it explicitly using the internal variable <em>.GlobalEnv</em>. There is one variable in my workspace, the function <em>g(x, y)</em>. When <em>g</em> is called a new environment is created in which it’s body will be evaluated. This is denoted by the solid line. In this new environment of <em>g</em> there exist two variables, <em>x</em> and <em>y</em>. As long as those variables are not needed, no values are bound to those names only a promise that a value can be found at the time of evaluation. Since <em>x</em> is evaluated, the value 1 is bound to <em>x</em> in the environment of the function <em>g</em>. <em>y</em>, however, is not evaluated, so the promised value of <em>y</em> is never searched for and we can promise anything.</p>

<p><img alt="" src="https://i2.wp.com/www.inwt-statistics.com/files/INWT/images_blog/promisesAndClosures/EnvPath1.png?resize=124%2C234&ssl=1" data-recalc-dims="1"></p>
<p><span>Environment Path 1.</span></p>
</div>
<div>
<p>The dashed line indicates the direction in which R will try to find objects. Meaning that if the function <em>g</em> does not find a variable in its own ‘evaluation environment’, it will continue its search in the global environment. The question where this dashed line is pointing to is really important if you try to understand closures. Just to give you a heads up: The parent environment (environment where the dashed line is pointing to) of a ‘functions evaluation environment’ is always the environment in which the function was created – and not the environment from which the function is called. In the case of <em>g</em> that is the global environment. In the case of a function living in a package it is the packages namespace.</p>
</div>
<div>
<h2>What is a closure?</h2>
<p>A closure is a function which has an enclosing environment. As far as my understanding of these things goes, by that definition every function can be considered a closure. This suspicion is supported by R’s constant complaint, that I try to subset closures. Anyway, typically the term closure is used for functions which will have a function as return value:</p>
</div>
<pre><pre><code>fClosure &lt;- function(p) function(x) x^p f1 &lt;- fClosure(1) f2 &lt;- fClosure(2) cbind(f1(1:10), f2(1:10)) </code></pre></pre>
<pre><pre><code>##       [,1] [,2] ##  [1,]    1    1 ##  [2,]    2    4 ##  [3,]    3    9 ##  [4,]    4   16 ##  [5,]    5   25 ##  [6,]    6   36 ##  [7,]    7   49 ##  [8,]    8   64 ##  [9,]    9   81 ## [10,]   10  100 </code></pre></pre>
<div>
<p>Here I created <em>fClosure</em> as a function of <em>p</em> which will return a function of <em>x</em>. Then I assign values to <em>f1</em> and <em>f2</em> which are the functions <em>f(x)=x<sup>1</sup></em> and <em>f(x)=x<sup>2</sup></em>. The reason this works can be answered by looking at the figure ‘Environment Path 2’ with all environments and connections between them.</p>

<p><img alt="" src="https://i0.wp.com/www.inwt-statistics.com/files/INWT/images_blog/promisesAndClosures/EnvPath2.png?resize=317%2C216&ssl=1" data-recalc-dims="1"><span>Environment Path 2.</span></p>
</div>
<div>
<p>The solid line indicates that <em>f1</em> is called from the <em>.GlobalEnv</em>; the dashed line the direction in which R will search for values (an exception is the promise, <em>x</em>, which will reference to the <em>.GlobalEnv</em>). The enclosing environment of <em>f1</em> is the environment in which it was created, which was the environment of the call to <em>fClosure</em>. So <em>f1</em> has an own environment which can be seen when you print the function to the console.</p>
</div>
<pre><pre><code>f1 </code></pre></pre>
<pre><pre><code>## function(x) x^p ## &lt;environment: 0x24488e8> </code></pre></pre>
<div>
<p>This environment can even be accessed, to check what is going on inside.</p>
</div>
<pre><pre><code>ls(environment(f1)) </code></pre></pre>
<pre><pre><code>## [1] &quot;p&quot; </code></pre></pre>
<pre><pre><code>get(&quot;p&quot;, envir = environment(f1)) </code></pre></pre>
<pre><pre><code>## [1] 1 </code></pre></pre>
<div>
<p>So in the enclosing environment of <em>f1</em> lives a variable <em>p</em> with value 1. Whenever R searches for a variable which is not part of the argument list, it will first check the environment created when called, then the enclosing environment and then the <em>.GlobalEnv</em> followed by the search path.</p>
</div>
<div>
<h2>Why are those two related?</h2>
<p>When I read about the scoping rules in R I never really understood the implications of the word lazy. It needed a couple of hours of utter confusion and experiments with closures that I got it. Consider the case where I want to construct an arbitrary number of functions like in the above example. Copy-pasting <em>fClosure</em> will quickly reach limits and is more frustrating than coding.</p>
</div>
<pre><pre><code># Creating f1-f5 and store them in a list # This will actually work using lapply in the most recent R version (3.4) # I enforce it by using a for-loop instead of lapply... # funList &lt;- lapply(1:5, fClosure) funList &lt;- list() for (i in 1:5) funList[[i]] &lt;- fClosure(i) # Call f1-f5 with the argument x = 1:10 resultList &lt;- lapply(funList, do.call, args = list(x = 1:10)) # Cbind the results do.call(cbind, resultList) </code></pre></pre>
<pre><pre><code>##         [,1]   [,2]   [,3]   [,4]   [,5] ##  [1,]      1      1      1      1      1 ##  [2,]     32     32     32     32     32 ##  [3,]    243    243    243    243    243 ##  [4,]   1024   1024   1024   1024   1024 ##  [5,]   3125   3125   3125   3125   3125 ##  [6,]   7776   7776   7776   7776   7776 ##  [7,]  16807  16807  16807  16807  16807 ##  [8,]  32768  32768  32768  32768  32768 ##  [9,]  59049  59049  59049  59049  59049 ## [10,] 100000 100000 100000 100000 100000 </code></pre></pre>
<div>
<p>Ups, what happened? The resulting matrix looks like every column was created using the same function! Just to be clear, the above code works just fine. It does exactly as intended. In this case I was tricked by the promises in the enclosing environments, and that in those enclosing environments there live variables <em>p</em> with values 1 to 5. This is not so. Remember, the arguments of a function are evaluated when they are first needed. Until then they are promises. The concept of a promise was surprising because it’s one of the very few objects which have reference semantics in base-R. So a promise is just a pointer to a variable name in an environment (the environment from which the function is called) – they are not pointing to values! If the value of the variable pointed to changes before the promise is evaluated inside the function, the behaviour of the function will change too. This leads to the question: what is the value of <em>p</em> inside this list of functions?</p>
</div>
<pre><pre><code>sapply(funList, function(fun) get(&quot;p&quot;, envir = environment(fun))) </code></pre></pre>
<pre><pre><code>## [1] 5 5 5 5 5 </code></pre></pre>
<div>
<p>Okay, fine, so in the loop where I created the functions <em>f1</em> to <em>f5</em>, I did pass the numbers 1 to 5 to the closure, however, they do not get evaluated but point to the iterator which is 5 at the moment the promises are evaluated. How do we fix this? Evaluate <em>p</em> in the enclosing environment at the moment of assignment. Actually we could just write <em>p</em> in the functions body (not the function which is returned, it needs to be evaluated in the enclosing environment), but that may be considered bad style because in two weeks time you will see it as a redundant and useless line of code. Actually there is a function for this. <em>force</em> forces the evaluation of arguments in the enclosing environment. This means that the variable <em>p</em> will be bound to a value at the moment the closure is called.</p>
</div>
<pre><pre><code># Fix fClosure &lt;- function(p) {   force(p)   function(x) x^p } # And again, with a new definition of fClosure: for(i in 1:5) funList[[i]] &lt;- fClosure(i) resultList &lt;- lapply(funList, do.call, args = list(x = 1:10)) do.call(cbind, resultList) </code></pre></pre>
<pre><pre><code>##       [,1] [,2] [,3]  [,4]   [,5] ##  [1,]    1    1    1     1      1 ##  [2,]    2    4    8    16     32 ##  [3,]    3    9   27    81    243 ##  [4,]    4   16   64   256   1024 ##  [5,]    5   25  125   625   3125 ##  [6,]    6   36  216  1296   7776 ##  [7,]    7   49  343  2401  16807 ##  [8,]    8   64  512  4096  32768 ##  [9,]    9   81  729  6561  59049 ## [10,]   10  100 1000 10000 100000 </code></pre></pre>
<div>
<p>And that made all the difference.</p>
</div>
	<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.inwt-statistics.com/read-blog/promises-and-closures-in-r.html"> INWT-Blog-RBloggers</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/XdtoWtNfjJY" height="1"></a></div>