<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/mcht-closures-and-r-environments-making-mchtest-objects-self-contained/"></div></div><div></div></div><div></div></div>
<div>
(This article was first published on <strong><a href="https://ntguardian.wordpress.com/2018/10/15/mcht-closures-r-environments-making-mchtest-objects-self-contained/"> R – Curtis Miller's Personal Website</a></strong>, and kindly contributed to <a rel="nofollow" href="https://www.r-bloggers.com/">R-bloggers)</a> </div>
<h2>Introduction</h2>
<p>Last week I <a rel="nofollow" href="https://wp.me/p27liZ-TD" target="_blank">announced</a> the first release of <a rel="nofollow" href="https://github.com/ntguardian/MCHT" target="_blank"><strong>MCHT</strong></a>, an R package that facilitates bootstrap and Monte Carlo hypothesis testing. In this article, I will elaborate on some important technical details about making <code>MCHTest</code> objects, explaining in the process how closures and R environments work.</p>
<p><span></span></p>
<p>To recap, last week I made a basic <code>MCHTest</code>-class object. These are S3-class objects; really they are just functions with a <code>class</code> attribute. All the work is done in the initial function call creating the object. But there’s more to the story.</p>
<p>We want these objects to be self-contained. Specifically, we don’t want changes in the global namespace to change how a <code>MCHTest</code> object behaves. By default, these objects are <em>not</em> self-contained and a programmer who isn’t careful can accidentally break these objects. Here I explain how to prefent this from happening.</p>
<h2>Closures and Environments</h2>
<p>I highly recommend those who want to learn more about closures and environments read <a rel="nofollow" href="http://adv-r.had.co.nz/" target="_blank">[1]</a>, but I will briefly explain these critical concepts here.</p>
<p>A <a rel="nofollow" href="https://en.wikipedia.org/wiki/Closure_(computer_programming)" target="_blank">closure</a> is a function created by another function. <code>MCHTest</code> objects are closures, functions created by <code>MCHTest()</code> (then given a <code>class</code> attribute). An environment is an R object where other R objects are effectively defined. For example, there is the global environment where most R objects created by users live.</p>
<pre>
environment()
</pre>
<pre>
## </pre>