UNPKG

skimr

Version:

CLI EDA for CSVs

815 lines (786 loc) 123 kB
<!DOCTYPE html> <html> <head> <meta charset="utf-8" /> <meta name="generator" content="pandoc" /> <meta http-equiv="X-UA-Compatible" content="IE=EDGE" /> <meta name="viewport" content="width=device-width, initial-scale=1" /> <title>Get started with cpp11</title> <script>// Pandoc 2.9 adds attributes on both header and div. We remove the former (to // be compatible with the behavior of Pandoc < 2.8). document.addEventListener('DOMContentLoaded', function(e) { var hs = document.querySelectorAll("div.section[class*='level'] > :first-child"); var i, h, a; for (i = 0; i < hs.length; i++) { h = hs[i]; if (!/^h[1-6]$/i.test(h.tagName)) continue; // it should be a header h1-h6 a = h.attributes; while (a.length > 0) h.removeAttribute(a[0].name); } }); </script> <style type="text/css"> code{white-space: pre-wrap;} span.smallcaps{font-variant: small-caps;} span.underline{text-decoration: underline;} div.column{display: inline-block; vertical-align: top; width: 50%;} div.hanging-indent{margin-left: 1.5em; text-indent: -1.5em;} ul.task-list{list-style: none;} </style> <style type="text/css"> code { white-space: pre; } .sourceCode { overflow: visible; } </style> <style type="text/css" data-origin="pandoc"> pre > code.sourceCode { white-space: pre; position: relative; } pre > code.sourceCode > span { display: inline-block; line-height: 1.25; } pre > code.sourceCode > span:empty { height: 1.2em; } .sourceCode { overflow: visible; } code.sourceCode > span { color: inherit; text-decoration: inherit; } div.sourceCode { margin: 1em 0; } pre.sourceCode { margin: 0; } @media screen { div.sourceCode { overflow: auto; } } @media print { pre > code.sourceCode { white-space: pre-wrap; } pre > code.sourceCode > span { text-indent: -5em; padding-left: 5em; } } pre.numberSource code { counter-reset: source-line 0; } pre.numberSource code > span { position: relative; left: -4em; counter-increment: source-line; } pre.numberSource code > span > a:first-child::before { content: counter(source-line); position: relative; left: -1em; text-align: right; vertical-align: baseline; border: none; display: inline-block; -webkit-touch-callout: none; -webkit-user-select: none; -khtml-user-select: none; -moz-user-select: none; -ms-user-select: none; user-select: none; padding: 0 4px; width: 4em; color: #aaaaaa; } pre.numberSource { margin-left: 3em; border-left: 1px solid #aaaaaa; padding-left: 4px; } div.sourceCode { } @media screen { pre > code.sourceCode > span > a:first-child::before { text-decoration: underline; } } code span.al { color: #ff0000; font-weight: bold; } code span.an { color: #60a0b0; font-weight: bold; font-style: italic; } code span.at { color: #7d9029; } code span.bn { color: #40a070; } code span.bu { color: #008000; } code span.cf { color: #007020; font-weight: bold; } code span.ch { color: #4070a0; } code span.cn { color: #880000; } code span.co { color: #60a0b0; font-style: italic; } code span.cv { color: #60a0b0; font-weight: bold; font-style: italic; } code span.do { color: #ba2121; font-style: italic; } code span.dt { color: #902000; } code span.dv { color: #40a070; } code span.er { color: #ff0000; font-weight: bold; } code span.ex { } code span.fl { color: #40a070; } code span.fu { color: #06287e; } code span.im { color: #008000; font-weight: bold; } code span.in { color: #60a0b0; font-weight: bold; font-style: italic; } code span.kw { color: #007020; font-weight: bold; } code span.op { color: #666666; } code span.ot { color: #007020; } code span.pp { color: #bc7a00; } code span.sc { color: #4070a0; } code span.ss { color: #bb6688; } code span.st { color: #4070a0; } code span.va { color: #19177c; } code span.vs { color: #4070a0; } code span.wa { color: #60a0b0; font-weight: bold; font-style: italic; } </style> <script> // apply pandoc div.sourceCode style to pre.sourceCode instead (function() { var sheets = document.styleSheets; for (var i = 0; i < sheets.length; i++) { if (sheets[i].ownerNode.dataset["origin"] !== "pandoc") continue; try { var rules = sheets[i].cssRules; } catch (e) { continue; } var j = 0; while (j < rules.length) { var rule = rules[j]; // check if there is a div.sourceCode rule if (rule.type !== rule.STYLE_RULE || rule.selectorText !== "div.sourceCode") { j++; continue; } var style = rule.style.cssText; // check if color or background-color is set if (rule.style.color === '' && rule.style.backgroundColor === '') { j++; continue; } // replace div.sourceCode by a pre.sourceCode rule sheets[i].deleteRule(j); sheets[i].insertRule('pre.sourceCode{' + style + '}', j); } } })(); </script> <style type="text/css">body { background-color: #fff; margin: 1em auto; max-width: 700px; overflow: visible; padding-left: 2em; padding-right: 2em; font-family: "Open Sans", "Helvetica Neue", Helvetica, Arial, sans-serif; font-size: 14px; line-height: 1.35; } #TOC { clear: both; margin: 0 0 10px 10px; padding: 4px; width: 400px; border: 1px solid #CCCCCC; border-radius: 5px; background-color: #f6f6f6; font-size: 13px; line-height: 1.3; } #TOC .toctitle { font-weight: bold; font-size: 15px; margin-left: 5px; } #TOC ul { padding-left: 40px; margin-left: -1.5em; margin-top: 5px; margin-bottom: 5px; } #TOC ul ul { margin-left: -2em; } #TOC li { line-height: 16px; } table { margin: 1em auto; border-width: 1px; border-color: #DDDDDD; border-style: outset; border-collapse: collapse; } table th { border-width: 2px; padding: 5px; border-style: inset; } table td { border-width: 1px; border-style: inset; line-height: 18px; padding: 5px 5px; } table, table th, table td { border-left-style: none; border-right-style: none; } table thead, table tr.even { background-color: #f7f7f7; } p { margin: 0.5em 0; } blockquote { background-color: #f6f6f6; padding: 0.25em 0.75em; } hr { border-style: solid; border: none; border-top: 1px solid #777; margin: 28px 0; } dl { margin-left: 0; } dl dd { margin-bottom: 13px; margin-left: 13px; } dl dt { font-weight: bold; } ul { margin-top: 0; } ul li { list-style: circle outside; } ul ul { margin-bottom: 0; } pre, code { background-color: #f7f7f7; border-radius: 3px; color: #333; white-space: pre-wrap; } pre { border-radius: 3px; margin: 5px 0px 10px 0px; padding: 10px; } pre:not([class]) { background-color: #f7f7f7; } code { font-family: Consolas, Monaco, 'Courier New', monospace; font-size: 85%; } p > code, li > code { padding: 2px 0px; } div.figure { text-align: center; } img { background-color: #FFFFFF; padding: 2px; border: 1px solid #DDDDDD; border-radius: 3px; border: 1px solid #CCCCCC; margin: 0 5px; } h1 { margin-top: 0; font-size: 35px; line-height: 40px; } h2 { border-bottom: 4px solid #f7f7f7; padding-top: 10px; padding-bottom: 2px; font-size: 145%; } h3 { border-bottom: 2px solid #f7f7f7; padding-top: 10px; font-size: 120%; } h4 { border-bottom: 1px solid #f7f7f7; margin-left: 8px; font-size: 105%; } h5, h6 { border-bottom: 1px solid #ccc; font-size: 105%; } a { color: #0033dd; text-decoration: none; } a:hover { color: #6666ff; } a:visited { color: #800080; } a:visited:hover { color: #BB00BB; } a[href^="http:"] { text-decoration: underline; } a[href^="https:"] { text-decoration: underline; } code > span.kw { color: #555; font-weight: bold; } code > span.dt { color: #902000; } code > span.dv { color: #40a070; } code > span.bn { color: #d14; } code > span.fl { color: #d14; } code > span.ch { color: #d14; } code > span.st { color: #d14; } code > span.co { color: #888888; font-style: italic; } code > span.ot { color: #007020; } code > span.al { color: #ff0000; font-weight: bold; } code > span.fu { color: #900; font-weight: bold; } code > span.er { color: #a61717; background-color: #e3d2d2; } </style> </head> <body> <h1 class="title toc-ignore">Get started with cpp11</h1> <p><em>This content is adapted (with permission) from the <a href="https://adv-r.hadley.nz/rcpp.html">Rcpp chapter</a> of Hadley Wickham’s book Advanced R.</em></p> <div id="introduction" class="section level2"> <h2>Introduction</h2> <p>Sometimes R code just isn’t fast enough. You’ve used profiling to figure out where your bottlenecks are, and you’ve done everything you can in R, but your code still isn’t fast enough. In this vignette you’ll learn how to improve performance by rewriting key functions in C++. This magic comes by way of the <a href="https://github.com/r-lib/cpp11">cpp11</a> package.</p> <p>cpp11 makes it very simple to connect C++ to R. While it is <em>possible</em> to write C or Fortran code for use in R, it will be painful by comparison. cpp11 provides a clean, approachable API that lets you write high-performance code, insulated from R’s more complex C API.</p> <p>Typical bottlenecks that C++ can address include:</p> <ul> <li><p>Loops that can’t be easily vectorised because subsequent iterations depend on previous ones.</p></li> <li><p>Recursive functions, or problems which involve calling functions millions of times. The overhead of calling a function in C++ is much lower than in R.</p></li> <li><p>Problems that require advanced data structures and algorithms that R doesn’t provide. Through the standard template library (STL), C++ has efficient implementations of many important data structures, from ordered maps to double-ended queues.</p></li> </ul> <p>The aim of this vignette is to discuss only those aspects of C++ and cpp11 that are absolutely necessary to help you eliminate bottlenecks in your code. We won’t spend much time on advanced features like object-oriented programming or templates because the focus is on writing small, self-contained functions, not big programs. A working knowledge of C++ is helpful, but not essential. Many good tutorials and references are freely available, including <a href="https://www.learncpp.com/" class="uri">https://www.learncpp.com/</a> and <a href="https://en.cppreference.com/w/cpp" class="uri">https://en.cppreference.com/w/cpp</a>. For more advanced topics, the <em>Effective C++</em> series by Scott Meyers is a popular choice.</p> <div id="outline" class="section level3"> <h3>Outline</h3> <ul> <li><p>Section <a href="#intro">intro</a> teaches you how to write C++ by converting simple R functions to their C++ equivalents. You’ll learn how C++ differs from R, and what the key scalar, vector, and matrix classes are called.</p></li> <li><p>Section <a href="#cpp-source">cpp_source</a> shows you how to use <code>cpp11::cpp_source()</code> to load a C++ file from disk in the same way you use <code>source()</code> to load a file of R code.</p></li> <li><p>Section <a href="#classes">classes</a> discusses how to modify attributes from cpp11, and mentions some of the other important classes.</p></li> <li><p>Section <a href="#na">na</a> teaches you how to work with R’s missing values in C++.</p></li> <li><p>Section <a href="#stl">stl</a> shows you how to use some of the most important data structures and algorithms from the standard template library, or STL, built-in to C++.</p></li> <li><p>Section <a href="#case-studies">case-studies</a> shows two real case studies where cpp11 was used to get considerable performance improvements.</p></li> <li><p>Section <a href="#package">package</a> teaches you how to add C++ code to an R package.</p></li> <li><p>Section <a href="#more">more</a> concludes the vignette with pointers to more resources to help you learn cpp11 and C++.</p></li> </ul> </div> <div id="prerequisites" class="section level3"> <h3>Prerequisites</h3> <p>We’ll use <a href="https://github.com/r-lib/cpp11">cpp11</a> to call C++ from R:</p> <div class="sourceCode" id="cb1"><pre class="sourceCode r"><code class="sourceCode r"><span id="cb1-1"><a href="#cb1-1" tabindex="-1"></a><span class="fu">library</span>(cpp11)</span></code></pre></div> <p>You’ll also need a working C++ compiler. To get it:</p> <ul> <li>On Windows, install <a href="https://cran.r-project.org/bin/windows/Rtools/">Rtools</a>.</li> <li>On Mac, install Xcode from the app store.</li> <li>On Linux, <code>sudo apt-get install r-base-dev</code> or similar.</li> </ul> </div> </div> <div id="intro" class="section level2"> <h2>Getting started with C++</h2> <p><code>cpp_function()</code> allows you to write C++ functions in R:</p> <div class="sourceCode" id="cb2"><pre class="sourceCode r"><code class="sourceCode r"><span id="cb2-1"><a href="#cb2-1" tabindex="-1"></a><span class="fu">cpp_function</span>(<span class="st">&#39;int add(int x, int y, int z) {</span></span> <span id="cb2-2"><a href="#cb2-2" tabindex="-1"></a><span class="st"> int sum = x + y + z;</span></span> <span id="cb2-3"><a href="#cb2-3" tabindex="-1"></a><span class="st"> return sum;</span></span> <span id="cb2-4"><a href="#cb2-4" tabindex="-1"></a><span class="st">}&#39;</span>)</span> <span id="cb2-5"><a href="#cb2-5" tabindex="-1"></a><span class="co"># add works like a regular R function</span></span> <span id="cb2-6"><a href="#cb2-6" tabindex="-1"></a>add</span> <span id="cb2-7"><a href="#cb2-7" tabindex="-1"></a><span class="co">#&gt; function (x, y, z) </span></span> <span id="cb2-8"><a href="#cb2-8" tabindex="-1"></a><span class="co">#&gt; {</span></span> <span id="cb2-9"><a href="#cb2-9" tabindex="-1"></a><span class="co">#&gt; .Call(&quot;_code_4b3136e975da_add&quot;, x, y, z, PACKAGE = &quot;code_4b3136e975da&quot;)</span></span> <span id="cb2-10"><a href="#cb2-10" tabindex="-1"></a><span class="co">#&gt; }</span></span> <span id="cb2-11"><a href="#cb2-11" tabindex="-1"></a><span class="fu">add</span>(<span class="dv">1</span>, <span class="dv">2</span>, <span class="dv">3</span>)</span> <span id="cb2-12"><a href="#cb2-12" tabindex="-1"></a><span class="co">#&gt; [1] 6</span></span></code></pre></div> <p>When you run the above code, cpp11 will compile the C++ code and construct an R function that connects to the compiled C++ function. There’s a lot going on underneath the hood but cpp11 takes care of all the details so you don’t need to worry about them.</p> <p>The following sections will teach you the basics by translating simple R functions to their C++ equivalents. We’ll start simple with a function that has no inputs and a scalar output, and then make it progressively more complicated:</p> <ul> <li>Scalar input and scalar output</li> <li>Vector input and scalar output</li> <li>Vector input and vector output</li> <li>Matrix input and vector output</li> </ul> <div id="no-inputs-scalar-output" class="section level3"> <h3>No inputs, scalar output</h3> <p>Let’s start with a very simple function. It has no arguments and always returns the integer 1:</p> <div class="sourceCode" id="cb3"><pre class="sourceCode r"><code class="sourceCode r"><span id="cb3-1"><a href="#cb3-1" tabindex="-1"></a>one <span class="ot">&lt;-</span> <span class="cf">function</span>() <span class="dv">1</span><span class="dt">L</span></span></code></pre></div> <p>The equivalent C++ function is:</p> <div class="sourceCode" id="cb4"><pre class="sourceCode cpp"><code class="sourceCode cpp"><span id="cb4-1"><a href="#cb4-1" tabindex="-1"></a><span class="dt">int</span> one<span class="op">()</span> <span class="op">{</span></span> <span id="cb4-2"><a href="#cb4-2" tabindex="-1"></a> <span class="cf">return</span> <span class="dv">1</span><span class="op">;</span></span> <span id="cb4-3"><a href="#cb4-3" tabindex="-1"></a><span class="op">}</span></span></code></pre></div> <p>We can compile and use this from R with <code>cpp_function()</code></p> <div class="sourceCode" id="cb5"><pre class="sourceCode r"><code class="sourceCode r"><span id="cb5-1"><a href="#cb5-1" tabindex="-1"></a><span class="fu">cpp_function</span>(<span class="st">&#39;int one() {</span></span> <span id="cb5-2"><a href="#cb5-2" tabindex="-1"></a><span class="st"> return 1;</span></span> <span id="cb5-3"><a href="#cb5-3" tabindex="-1"></a><span class="st">}&#39;</span>)</span></code></pre></div> <p>This small function illustrates a number of important differences between R and C++:</p> <ul> <li><p>The syntax to create a function looks like the syntax to call a function; you don’t use assignment to create functions as you do in R.</p></li> <li><p>You must declare the type of output the function returns. This function returns an <code>int</code> (a scalar integer). The classes for the most common types of R vectors are: <code>doubles</code>, <code>integers</code>, <code>strings</code>, and <code>logicals</code>.</p></li> <li><p>Scalars and vectors are different. The scalar equivalents of numeric, integer, character, and logical vectors are: <code>double</code>, <code>int</code>, <code>String</code>, and <code>bool</code>.</p></li> <li><p>You must use an explicit <code>return</code> statement to return a value from a function.</p></li> <li><p>Every statement is terminated by a <code>;</code>.</p></li> </ul> </div> <div id="scalar-input-scalar-output" class="section level3"> <h3>Scalar input, scalar output</h3> <p>The next example function implements a scalar version of the <code>sign()</code> function which returns 1 if the input is positive, and -1 if it’s negative:</p> <div class="sourceCode" id="cb6"><pre class="sourceCode r"><code class="sourceCode r"><span id="cb6-1"><a href="#cb6-1" tabindex="-1"></a>sign_r <span class="ot">&lt;-</span> <span class="cf">function</span>(x) {</span> <span id="cb6-2"><a href="#cb6-2" tabindex="-1"></a> <span class="cf">if</span> (x <span class="sc">&gt;</span> <span class="dv">0</span>) {</span> <span id="cb6-3"><a href="#cb6-3" tabindex="-1"></a> <span class="dv">1</span></span> <span id="cb6-4"><a href="#cb6-4" tabindex="-1"></a> } <span class="cf">else</span> <span class="cf">if</span> (x <span class="sc">==</span> <span class="dv">0</span>) {</span> <span id="cb6-5"><a href="#cb6-5" tabindex="-1"></a> <span class="dv">0</span></span> <span id="cb6-6"><a href="#cb6-6" tabindex="-1"></a> } <span class="cf">else</span> {</span> <span id="cb6-7"><a href="#cb6-7" tabindex="-1"></a> <span class="sc">-</span><span class="dv">1</span></span> <span id="cb6-8"><a href="#cb6-8" tabindex="-1"></a> }</span> <span id="cb6-9"><a href="#cb6-9" tabindex="-1"></a>}</span> <span id="cb6-10"><a href="#cb6-10" tabindex="-1"></a><span class="fu">cpp_function</span>(<span class="st">&#39;int sign_cpp(int x) {</span></span> <span id="cb6-11"><a href="#cb6-11" tabindex="-1"></a><span class="st"> if (x &gt; 0) {</span></span> <span id="cb6-12"><a href="#cb6-12" tabindex="-1"></a><span class="st"> return 1;</span></span> <span id="cb6-13"><a href="#cb6-13" tabindex="-1"></a><span class="st"> } else if (x == 0) {</span></span> <span id="cb6-14"><a href="#cb6-14" tabindex="-1"></a><span class="st"> return 0;</span></span> <span id="cb6-15"><a href="#cb6-15" tabindex="-1"></a><span class="st"> } else {</span></span> <span id="cb6-16"><a href="#cb6-16" tabindex="-1"></a><span class="st"> return -1;</span></span> <span id="cb6-17"><a href="#cb6-17" tabindex="-1"></a><span class="st"> }</span></span> <span id="cb6-18"><a href="#cb6-18" tabindex="-1"></a><span class="st">}&#39;</span>)</span></code></pre></div> <p>In the C++ version:</p> <ul> <li><p>We declare the type of each input in the same way we declare the type of the output. While this makes the code a little more verbose, it also makes clear the type of input the function needs.</p></li> <li><p>The <code>if</code> syntax is identical — while there are some big differences between R and C++, there are also lots of similarities! C++ also has a <code>while</code> statement that works the same way as R’s. As in R you can use <code>break</code> to exit the loop, but to skip one iteration you need to use <code>continue</code> instead of <code>next</code>.</p></li> </ul> </div> <div id="vector-input-scalar-output" class="section level3"> <h3>Vector input, scalar output</h3> <p>One big difference between R and C++ is that the cost of loops is much lower in C++. For example, we could implement the <code>sum</code> function in R using a loop. If you’ve been programming in R a while, you’ll probably have a visceral reaction to this function!</p> <div class="sourceCode" id="cb7"><pre class="sourceCode r"><code class="sourceCode r"><span id="cb7-1"><a href="#cb7-1" tabindex="-1"></a>sum_r <span class="ot">&lt;-</span> <span class="cf">function</span>(x) {</span> <span id="cb7-2"><a href="#cb7-2" tabindex="-1"></a> total <span class="ot">&lt;-</span> <span class="dv">0</span></span> <span id="cb7-3"><a href="#cb7-3" tabindex="-1"></a> <span class="cf">for</span> (i <span class="cf">in</span> <span class="fu">seq_along</span>(x)) {</span> <span id="cb7-4"><a href="#cb7-4" tabindex="-1"></a> total <span class="ot">&lt;-</span> total <span class="sc">+</span> x[i]</span> <span id="cb7-5"><a href="#cb7-5" tabindex="-1"></a> }</span> <span id="cb7-6"><a href="#cb7-6" tabindex="-1"></a> total</span> <span id="cb7-7"><a href="#cb7-7" tabindex="-1"></a>}</span></code></pre></div> <p>In C++, loops have very little overhead, so it’s fine to use them. In Section <a href="#stl">stl</a>, you’ll see alternatives to <code>for</code> loops that more clearly express your intent; they’re not faster, but they can make your code easier to understand.</p> <div class="sourceCode" id="cb8"><pre class="sourceCode r"><code class="sourceCode r"><span id="cb8-1"><a href="#cb8-1" tabindex="-1"></a><span class="fu">cpp_function</span>(<span class="st">&#39;double sum_cpp(doubles x) {</span></span> <span id="cb8-2"><a href="#cb8-2" tabindex="-1"></a><span class="st"> int n = x.size();</span></span> <span id="cb8-3"><a href="#cb8-3" tabindex="-1"></a><span class="st"> double total = 0;</span></span> <span id="cb8-4"><a href="#cb8-4" tabindex="-1"></a><span class="st"> for(int i = 0; i &lt; n; ++i) {</span></span> <span id="cb8-5"><a href="#cb8-5" tabindex="-1"></a><span class="st"> total += x[i];</span></span> <span id="cb8-6"><a href="#cb8-6" tabindex="-1"></a><span class="st"> }</span></span> <span id="cb8-7"><a href="#cb8-7" tabindex="-1"></a><span class="st"> return total;</span></span> <span id="cb8-8"><a href="#cb8-8" tabindex="-1"></a><span class="st">}&#39;</span>)</span></code></pre></div> <p>The C++ version is similar, but:</p> <ul> <li><p>To find the length of the vector, we use the <code>.size()</code> method, which returns an integer. C++ methods are called with <code>.</code> (i.e., a full stop).</p></li> <li><p>The <code>for</code> statement has a different syntax: <code>for(init; check; increment)</code>. This loop is initialised by creating a new variable called <code>i</code> with value 0. Before each iteration we check that <code>i &lt; n</code>, and terminate the loop if it’s not. After each iteration, we increment the value of <code>i</code> by one, using the special prefix operator <code>++</code> which increases the value of <code>i</code> by 1.</p></li> <li><p>In C++, vector indices start at 0, which means that the last element is at position <code>n - 1</code>. I’ll say this again because it’s so important: <strong>IN C++, VECTOR INDICES START AT 0</strong>! This is a very common source of bugs when converting R functions to C++.</p></li> <li><p>Use <code>=</code> for assignment, not <code>&lt;-</code>.</p></li> <li><p>C++ provides operators that modify in-place: <code>total += x[i]</code> is equivalent to <code>total = total + x[i]</code>. Similar in-place operators are <code>-=</code>, <code>*=</code>, and <code>/=</code>.</p></li> </ul> <p>This is a good example of where C++ is much more efficient than R. As shown by the following microbenchmark, <code>sum_cpp()</code> is competitive with the built-in (and highly optimised) <code>sum()</code>, while <code>sum_r()</code> is several orders of magnitude slower.</p> <div class="sourceCode" id="cb9"><pre class="sourceCode r"><code class="sourceCode r"><span id="cb9-1"><a href="#cb9-1" tabindex="-1"></a>x <span class="ot">&lt;-</span> <span class="fu">runif</span>(<span class="fl">1e3</span>)</span> <span id="cb9-2"><a href="#cb9-2" tabindex="-1"></a>bench<span class="sc">::</span><span class="fu">mark</span>(</span> <span id="cb9-3"><a href="#cb9-3" tabindex="-1"></a> <span class="fu">sum</span>(x),</span> <span id="cb9-4"><a href="#cb9-4" tabindex="-1"></a> <span class="fu">sum_cpp</span>(x),</span> <span id="cb9-5"><a href="#cb9-5" tabindex="-1"></a> <span class="fu">sum_r</span>(x)</span> <span id="cb9-6"><a href="#cb9-6" tabindex="-1"></a>)[<span class="dv">1</span><span class="sc">:</span><span class="dv">6</span>]</span> <span id="cb9-7"><a href="#cb9-7" tabindex="-1"></a><span class="co">#&gt; # A tibble: 3 × 6</span></span> <span id="cb9-8"><a href="#cb9-8" tabindex="-1"></a><span class="co">#&gt; expression min median `itr/sec` mem_alloc `gc/sec`</span></span> <span id="cb9-9"><a href="#cb9-9" tabindex="-1"></a><span class="co">#&gt; &lt;bch:expr&gt; &lt;bch:tm&gt; &lt;bch:tm&gt; &lt;dbl&gt; &lt;bch:byt&gt; &lt;dbl&gt;</span></span> <span id="cb9-10"><a href="#cb9-10" tabindex="-1"></a><span class="co">#&gt; 1 sum(x) 1.52µs 1.72µs 547073. 0B 0</span></span> <span id="cb9-11"><a href="#cb9-11" tabindex="-1"></a><span class="co">#&gt; 2 sum_cpp(x) 1.39µs 1.56µs 571050. 0B 0</span></span> <span id="cb9-12"><a href="#cb9-12" tabindex="-1"></a><span class="co">#&gt; 3 sum_r(x) 12.79µs 12.91µs 74068. 19.2KB 0</span></span></code></pre></div> </div> <div id="vector-input-vector-output" class="section level3"> <h3>Vector input, vector output</h3> <!-- FIXME: come up with better example. Also fix in two other places it occurs --> <p>Next we’ll create a function that computes the Euclidean distance between a value and a vector of values:</p> <div class="sourceCode" id="cb10"><pre class="sourceCode r"><code class="sourceCode r"><span id="cb10-1"><a href="#cb10-1" tabindex="-1"></a>pdist_r <span class="ot">&lt;-</span> <span class="cf">function</span>(x, ys) {</span> <span id="cb10-2"><a href="#cb10-2" tabindex="-1"></a> <span class="fu">sqrt</span>((x <span class="sc">-</span> ys) <span class="sc">^</span> <span class="dv">2</span>)</span> <span id="cb10-3"><a href="#cb10-3" tabindex="-1"></a>}</span></code></pre></div> <p>In R, it’s not obvious that we want <code>x</code> to be a scalar from the function definition, and we’d need to make that clear in the documentation. That’s not a problem in the C++ version because we have to be explicit about types:</p> <div class="sourceCode" id="cb11"><pre class="sourceCode r"><code class="sourceCode r"><span id="cb11-1"><a href="#cb11-1" tabindex="-1"></a><span class="fu">cpp_function</span>(<span class="st">&#39;doubles pdist_cpp(double x, doubles ys) {</span></span> <span id="cb11-2"><a href="#cb11-2" tabindex="-1"></a><span class="st"> int n = ys.size();</span></span> <span id="cb11-3"><a href="#cb11-3" tabindex="-1"></a><span class="st"> writable::doubles out(n);</span></span> <span id="cb11-4"><a href="#cb11-4" tabindex="-1"></a><span class="st"> for(int i = 0; i &lt; n; ++i) {</span></span> <span id="cb11-5"><a href="#cb11-5" tabindex="-1"></a><span class="st"> out[i] = sqrt(pow(ys[i] - x, 2.0));</span></span> <span id="cb11-6"><a href="#cb11-6" tabindex="-1"></a><span class="st"> }</span></span> <span id="cb11-7"><a href="#cb11-7" tabindex="-1"></a><span class="st"> return out;</span></span> <span id="cb11-8"><a href="#cb11-8" tabindex="-1"></a><span class="st">}&#39;</span>)</span></code></pre></div> <p>This function introduces a few new concepts:</p> <ul> <li><p>Because we are creating a new vector we need to use <code>writable::doubles</code> rather than the read-only <code>doubles</code>.</p></li> <li><p>We create a new numeric vector of length <code>n</code> with a constructor: <code>cpp11::writable::doubles out(n)</code>. Another useful way of making a vector is to copy an existing one: <code>cpp11::doubles zs(ys)</code>.</p></li> <li><p>C++ uses <code>pow()</code>, not <code>^</code>, for exponentiation.</p></li> </ul> <p>Note that because the R version is fully vectorised, it’s already going to be fast.</p> <div class="sourceCode" id="cb12"><pre class="sourceCode r"><code class="sourceCode r"><span id="cb12-1"><a href="#cb12-1" tabindex="-1"></a>y <span class="ot">&lt;-</span> <span class="fu">runif</span>(<span class="fl">1e6</span>)</span> <span id="cb12-2"><a href="#cb12-2" tabindex="-1"></a>bench<span class="sc">::</span><span class="fu">mark</span>(</span> <span id="cb12-3"><a href="#cb12-3" tabindex="-1"></a> <span class="fu">pdist_r</span>(<span class="fl">0.5</span>, y),</span> <span id="cb12-4"><a href="#cb12-4" tabindex="-1"></a> <span class="fu">pdist_cpp</span>(<span class="fl">0.5</span>, y)</span> <span id="cb12-5"><a href="#cb12-5" tabindex="-1"></a>)[<span class="dv">1</span><span class="sc">:</span><span class="dv">6</span>]</span> <span id="cb12-6"><a href="#cb12-6" tabindex="-1"></a><span class="co">#&gt; # A tibble: 2 × 6</span></span> <span id="cb12-7"><a href="#cb12-7" tabindex="-1"></a><span class="co">#&gt; expression min median `itr/sec` mem_alloc `gc/sec`</span></span> <span id="cb12-8"><a href="#cb12-8" tabindex="-1"></a><span class="co">#&gt; &lt;bch:expr&gt; &lt;bch:tm&gt; &lt;bch:tm&gt; &lt;dbl&gt; &lt;bch:byt&gt; &lt;dbl&gt;</span></span> <span id="cb12-9"><a href="#cb12-9" tabindex="-1"></a><span class="co">#&gt; 1 pdist_r(0.5, y) 1.99ms 2.07ms 479. 7.63MB 92.5</span></span> <span id="cb12-10"><a href="#cb12-10" tabindex="-1"></a><span class="co">#&gt; 2 pdist_cpp(0.5, y) 880.8µs 966.7µs 996. 7.63MB 168.</span></span></code></pre></div> <p>On my computer, it takes around 5 ms with a 1 million element <code>y</code> vector. The C++ function is about 2.5 times faster, ~2 ms, but assuming it took you 10 minutes to write the C++ function, you’d need to run it ~200,000 times to make rewriting worthwhile. The reason why the C++ function is faster is subtle, and relates to memory management. The R version needs to create an intermediate vector the same length as y (<code>x - ys</code>), and allocating memory is an expensive operation. The C++ function avoids this overhead because it uses an intermediate scalar.</p> </div> <div id="cpp-source" class="section level3"> <h3>Using cpp_source</h3> <p>So far, we’ve used inline C++ with <code>cpp_function()</code>. This makes presentation simpler, but for real problems, it’s usually easier to use stand-alone C++ files and then source them into R using <code>cpp_source()</code>. This lets you take advantage of text editor support for C++ files (e.g., syntax highlighting) as well as making it easier to identify the line numbers in compilation errors.</p> <p>Your stand-alone C++ file should have extension <code>.cpp</code>, and needs to start with:</p> <div class="sourceCode" id="cb13"><pre class="sourceCode cpp"><code class="sourceCode cpp"><span id="cb13-1"><a href="#cb13-1" tabindex="-1"></a><span class="pp">#include </span><span class="im">&quot;cpp11.hpp&quot;</span></span> <span id="cb13-2"><a href="#cb13-2" tabindex="-1"></a><span class="kw">using</span> <span class="kw">namespace</span> cpp11<span class="op">;</span></span></code></pre></div> <p>And for each function that you want available within R, you need to prefix it with:</p> <div class="sourceCode" id="cb14"><pre class="sourceCode cpp"><code class="sourceCode cpp"><span id="cb14-1"><a href="#cb14-1" tabindex="-1"></a><span class="op">[[</span><span class="at">cpp11</span><span class="op">::</span><span class="at">register</span><span class="op">]]</span></span></code></pre></div> <p>If you’re familiar with roxygen2, you might wonder how this relates to <code>@export</code>. <code>cpp11::register</code> registers a C++ function to be called from R. <code>@export</code> controls whether a function is exported from a package and made available to the user.</p> <p>To compile the C++ code, use <code>cpp_source(&quot;path/to/file.cpp&quot;)</code>. This will create the matching R functions and add them to your current session. Note that these functions can not be saved in a <code>.Rdata</code> file and reloaded in a later session; they must be recreated each time you restart R.</p> <p>This example also illustrates a different kind of a <code>for</code> loop, a for-each loop.</p> <div class="sourceCode" id="cb15"><pre class="sourceCode cpp"><code class="sourceCode cpp"><span id="cb15-1"><a href="#cb15-1" tabindex="-1"></a><span class="pp">#include </span><span class="im">&quot;cpp11/doubles.hpp&quot;</span></span> <span id="cb15-2"><a href="#cb15-2" tabindex="-1"></a><span class="kw">using</span> <span class="kw">namespace</span> cpp11<span class="op">;</span></span> <span id="cb15-3"><a href="#cb15-3" tabindex="-1"></a></span> <span id="cb15-4"><a href="#cb15-4" tabindex="-1"></a><span class="op">[[</span><span class="at">cpp11</span><span class="op">::</span><span class="at">register</span><span class="op">]]</span></span> <span id="cb15-5"><a href="#cb15-5" tabindex="-1"></a><span class="dt">double</span> mean_cpp<span class="op">(</span>doubles x<span class="op">)</span> <span class="op">{</span></span> <span id="cb15-6"><a href="#cb15-6" tabindex="-1"></a> <span class="dt">int</span> n <span class="op">=</span> x<span class="op">.</span>size<span class="op">();</span></span> <span id="cb15-7"><a href="#cb15-7" tabindex="-1"></a> <span class="dt">double</span> total <span class="op">=</span> <span class="dv">0</span><span class="op">;</span></span> <span id="cb15-8"><a href="#cb15-8" tabindex="-1"></a> <span class="cf">for</span><span class="op">(</span><span class="dt">double</span> value <span class="op">:</span> x<span class="op">)</span> <span class="op">{</span></span> <span id="cb15-9"><a href="#cb15-9" tabindex="-1"></a> total <span class="op">+=</span> value<span class="op">;</span></span> <span id="cb15-10"><a href="#cb15-10" tabindex="-1"></a> <span class="op">}</span></span> <span id="cb15-11"><a href="#cb15-11" tabindex="-1"></a> <span class="cf">return</span> total <span class="op">/</span> n<span class="op">;</span></span> <span id="cb15-12"><a href="#cb15-12" tabindex="-1"></a><span class="op">}</span></span></code></pre></div> <p>NB: if you run this code, you’ll notice that <code>mean_cpp()</code> is faster than the built-in <code>mean()</code>. This is because it trades numerical accuracy for speed.</p> <p>For the remainder of this vignette C++ code will be presented stand-alone rather than wrapped in a call to <code>cpp_function</code>. If you want to try compiling and/or modifying the examples you should paste them into a C++ source file that includes the elements described above. This is easy to do in RMarkdown by using <code>{cpp11}</code> instead of <code>{r}</code> at the beginning of your code blocks.</p> </div> <div id="exercises" class="section level3"> <h3>Exercises</h3> <ol style="list-style-type: decimal"> <li>With the basics of C++ in hand, it’s now a great time to practice by reading and writing some simple C++ functions. For each of the following functions, read the code and figure out what the corresponding base R function is. You might not understand every part of the code yet, but you should be able to figure out the basics of what the function does.</li> </ol> <div class="sourceCode" id="cb16"><pre class="sourceCode cpp"><code class="sourceCode cpp"><span id="cb16-1"><a href="#cb16-1" tabindex="-1"></a><span class="pp">#include </span><span class="im">&quot;cpp11.hpp&quot;</span></span> <span id="cb16-2"><a href="#cb16-2" tabindex="-1"></a></span> <span id="cb16-3"><a href="#cb16-3" tabindex="-1"></a><span class="kw">using</span> <span class="kw">namespace</span> cpp11<span class="op">;</span></span> <span id="cb16-4"><a href="#cb16-4" tabindex="-1"></a><span class="kw">namespace</span> writable <span class="op">=</span> cpp11<span class="op">::</span>writable<span class="op">;</span></span> <span id="cb16-5"><a href="#cb16-5" tabindex="-1"></a></span> <span id="cb16-6"><a href="#cb16-6" tabindex="-1"></a><span class="op">[[</span><span class="at">cpp11</span><span class="op">::</span><span class="at">register</span><span class="op">]]</span></span> <span id="cb16-7"><a href="#cb16-7" tabindex="-1"></a><span class="dt">double</span> f1<span class="op">(</span>doubles x<span class="op">)</span> <span class="op">{</span></span> <span id="cb16-8"><a href="#cb16-8" tabindex="-1"></a> <span class="dt">int</span> n <span class="op">=</span> x<span class="op">.</span>size<span class="op">();</span></span> <span id="cb16-9"><a href="#cb16-9" tabindex="-1"></a> <span class="dt">double</span> y <span class="op">=</span> <span class="dv">0</span><span class="op">;</span></span> <span id="cb16-10"><a href="#cb16-10" tabindex="-1"></a></span> <span id="cb16-11"><a href="#cb16-11" tabindex="-1"></a> <span class="cf">for</span><span class="op">(</span><span class="dt">int</span> i <span class="op">=</span> <span class="dv">0</span><span class="op">;</span> i <span class="op">&lt;</span> n<span class="op">;</span> <span class="op">++</span>i<span class="op">)</span> <span class="op">{</span></span> <span id="cb16-12"><a href="#cb16-12" tabindex="-1"></a> y <span class="op">+=</span> x<span class="op">[</span>i<span class="op">]</span> <span class="op">/</span> n<span class="op">;</span></span> <span id="cb16-13"><a href="#cb16-13" tabindex="-1"></a> <span class="op">}</span></span> <span id="cb16-14"><a href="#cb16-14" tabindex="-1"></a> <span class="cf">return</span> y<span class="op">;</span></span> <span id="cb16-15"><a href="#cb16-15" tabindex="-1"></a><span class="op">}</span></span> <span id="cb16-16"><a href="#cb16-16" tabindex="-1"></a></span> <span id="cb16-17"><a href="#cb16-17" tabindex="-1"></a><span class="op">[[</span><span class="at">cpp11</span><span class="op">::</span><span class="at">register</span><span class="op">]]</span></span> <span id="cb16-18"><a href="#cb16-18" tabindex="-1"></a>doubles f2<span class="op">(</span>doubles x<span class="op">)</span> <span class="op">{</span></span> <span id="cb16-19"><a href="#cb16-19" tabindex="-1"></a> <span class="dt">int</span> n <span class="op">=</span> x<span class="op">.</span>size<span class="op">();</span></span> <span id="cb16-20"><a href="#cb16-20" tabindex="-1"></a> writable<span class="op">::</span>doubles out<span class="op">(</span>n<span class="op">);</span></span> <span id="cb16-21"><a href="#cb16-21" tabindex="-1"></a></span> <span id="cb16-22"><a href="#cb16-22" tabindex="-1"></a> out<span class="op">[</span><span class="dv">0</span><span class="op">]</span> <span class="op">=</span> x<span class="op">[</span><span class="dv">0</span><span class="op">];</span></span> <span id="cb16-23"><a href="#cb16-23" tabindex="-1"></a> <span class="cf">for</span><span class="op">(</span><span class="dt">int</span> i <span class="op">=</span> <span class="dv">1</span><span class="op">;</span> i <span class="op">&lt;</span> n<span class="op">;</span> <span class="op">++</span>i<span class="op">)</span> <span class="op">{</span></span> <span id="cb16-24"><a href="#cb16-24" tabindex="-1"></a> out<span class="op">[</span>i<span class="op">]</span> <span class="op">=</span> out<span class="op">[</span>i <span class="op">-</span> <span class="dv">1</span><span class="op">]</span> <span class="op">+</span> x<span class="op">[</span>i<span class="op">];</span></span> <span id="cb16-25"><a href="#cb16-25" tabindex="-1"></a> <span class="op">}</span></span> <span id="cb16-26"><a href="#cb16-26" tabindex="-1"></a> <span class="cf">return</span> out<span class="op">;</span></span> <span id="cb16-27"><a href="#cb16-27" tabindex="-1"></a><span class="op">}</span></span> <span id="cb16-28"><a href="#cb16-28" tabindex="-1"></a></span> <span id="cb16-29"><a href="#cb16-29" tabindex="-1"></a><span class="op">[[</span><span class="at">cpp11</span><span class="op">::</span><span class="at">register</span><span class="op">]]</span></span> <span id="cb16-30"><a href="#cb16-30" tabindex="-1"></a><span class="dt">bool</span> f3<span class="op">(</span>logicals x<span class="op">)</span> <span class="op">{</span></span> <span id="cb16-31"><a href="#cb16-31" tabindex="-1"></a> <span class="dt">int</span> n <span class="op">=</span> x<span class="op">.</span>size<span class="op">();</span></span> <span id="cb16-32"><a href="#cb16-32" tabindex="-1"></a></span> <span id="cb16-33"><a href="#cb16-33" tabindex="-1"></a> <span class="cf">for</span><span class="op">(</span><span class="dt">int</span> i <span class="op">=</span> <span class="dv">0</span><span class="op">;</span> i <span class="op">&lt;</span> n<span class="op">;</span> <span class="op">++</span>i<span class="op">)</span> <span class="op">{</span></span> <span id="cb16-34"><a href="#cb16-34" tabindex="-1"></a> <span class="cf">if</span> <span class="op">(</span>x<span class="op">[</span>i<span class="op">])</span> <span class="op">{</span></span> <span id="cb16-35"><a href="#cb16-35" tabindex="-1"></a> <span class="cf">return</span> <span class="kw">true</span><span class="op">;</span></span> <span id="cb16-36"><a href="#cb16-36" tabindex="-1"></a> <span class="op">}</span></span> <span id="cb16-37"><a href="#cb16-37" tabindex="-1"></a> <span class="op">}</span></span> <span id="cb16-38"><a href="#cb16-38" tabindex="-1"></a> <span class="cf">return</span> <span class="kw">false</span><span class="op">;</span></span> <span id="cb16-39"><a href="#cb16-39" tabindex="-1"></a><span class="op">}</span></span> <span id="cb16-40"><a href="#cb16-40" tabindex="-1"></a></span> <span id="cb16-41"><a href="#cb16-41" tabindex="-1"></a><span class="op">[[</span><span class="at">cpp11</span><span class="op">::</span><span class="at">register</span><span class="op">]]</span></span> <span id="cb16-42"><a href="#cb16-42" tabindex="-1"></a><span class="dt">int</span> f4<span class="op">(</span>cpp11<span class="op">::</span>function pred<span class="op">,</span> list x<span class="op">)</span> <span class="op">{</span></span> <span id="cb16-43"><a href="#cb16-43" tabindex="-1"></a> <span class="dt">int</span> n <span class="op">=</span> x<span class="op">.</span>size<span class="op">();</span></span> <span id="cb16-44"><a href="#cb16-44" tabindex="-1"></a></span> <span id="cb16-45"><a href="#cb16-45" tabindex="-1"></a> <span class="cf">for</span><span class="op">(</span><span class="dt">int</span> i <span class="op">=</span> <span class="dv">0</span><span class="op">;</span> i <span class="op">&lt;</span> n<span class="op">;</span> <span class="op">++</span>i<span class="op">)</span> <span class="op">{</span></span> <span id="cb16-46"><a href="#cb16-46" tabindex="-1"></a> logicals res<span class="op">(</span>pred<span class="op">(</span>x<span class="op">[</span>i<span class="op">]));</span></span> <span id="cb16-47"><a href="#cb16-47" tabindex="-1"></a> <span class="cf">if</span> <span class="op">(</span>res<span class="op">[</span><span class="dv">0</span><span class="op">])</span> <span class="op">{</span></span> <span id="cb16-48"><a href="#cb16-48" tabindex="-1"></a> <span class="cf">return</span> i <span class="op">+</span> <span class="dv">1</span><span class="op">;</span></span> <span id="cb16-49"><a href="#cb16-49" tabindex="-1"></a> <span class="op">}</span></span> <span id="cb16-50"><a href="#cb16-50" tabindex="-1"></a> <span class="op">}</span></span> <span id="cb16-51"><a href="#cb16-51" tabindex="-1"></a> <span class="cf">return</span> <span class="dv">0</span><span class="op">;</span></span> <span id="cb16-52"><a href="#cb16-52" tabindex="-1"></a><span class="op">}</span></span></code></pre></div> <ol style="list-style-type: decimal"> <li><p>To practice your function writing skills, convert the following functions into C++. For now, assume the inputs have no missing values.</p> <ol style="list-style-type: decimal"> <li><p><code>all()</code>.</p></li> <li><p><code>cumprod()</code>, <code>cummin()</code>, <code>cummax()</code>.</p></li> <li><p><code>diff()</code>. Start by assuming lag 1, and then generalise for lag <code>n</code>.</p></li> <li><p><code>range()</code>.</p></li> <li><p><code>var()</code>. Read about the approaches you can take on <a href="https://en.wikipedia.org/wiki/Algorithms_for_calculating_variance">Wikipedia</a>. Whenever implementing a numerical algorithm, it’s always good to check what is already known about the problem.</p></li> </ol></li> </ol> </div> </div> <div id="classes" class="section level2"> <h2>Other classes</h2> <p>You’ve already seen the basic vector classes (<code>integers</code>, <code>doubles</code>, <code>logicals</code>, <code>strings</code>) and their scalar (<code>int</code>, <code>double</code>, <code>bool</code>, <code>string</code>) equivalents. cpp11 also provides wrappers for other base data types. The most important are for lists and data frames, functions, and attributes, as described below.</p> <div id="lists-and-data-frames" class="section level3"> <h3>Lists and data frames</h3> <p>cpp11 also provides <code>list</code> and <code>data_frame</code> classes, but they are more useful for output than input. This is because lists and data frames can contain arbitrary classes but C++ needs to know their classes in advance. If the list has known structure (e.g., it’s an S3 object), you can extract the components and manually convert them to their C++ equivalents with <code>as_cpp()</code>. For example, the object created by <code>lm()</code>, the function that fits a linear model, is a list whose components are always of the same type.</p> <p>The following code illustrates how you might extract the mean percentage error (<code>mpe()</code>) of a linear model. This isn’t a good example of when to use C++, because it’s so easily implemented in R, but it shows how to work with an important S3 class. Note the use of <code>Rf_inherits()</code> and the <code>stop()</code> to check that the object really is a linear model.</p> <!-- FIXME: needs better motivation --> <div class="sourceCode" id="cb17"><pre class="sourceCode cpp"><code class="sourceCode cpp"><span id="cb17-1"><a href="#cb17-1" tabindex="-1"></a><span class="pp">#include </span><span class="im">&quot;cpp11.hpp&quot;</span></span> <span id="cb17-2"><a href="#cb17-2" tabindex="-1"></a><span class="kw">using</span> <span class="kw">namespace</span> cpp11<span class="op">;</span></span> <span id="cb17-3"><a href="#cb17-3" tabindex="-1"></a></span> <span id="cb17-4"><a href="#cb17-4" tabindex="-1"></a><span class="op">[[</span><span class="at">cpp11</span><span class="op">::</span><span class="at">register</span><span class="op">]]</span></span> <span id="cb17-5"><a href="#cb17-5" tabindex="-1"></a><span class="dt">double</span> mpe<span class="op">(</span>list mod<span class="op">)</span> <span class="op">{</span></span> <span id="cb17-6"><a href="#cb17-6" tabindex="-1"></a> <span class="cf">if</span> <span class="op">(!</span>Rf_inherits<span class="op">(</span>mod<span class="op">,</span> <span class="st">&quot;lm&quot;</span><span class="op">))</span> <span class="op">{</span></span> <span id="cb17-7"><a href="#cb17-7" tabindex="-1"></a> stop<span class="op">(</span><span class="st">&quot;Input must be a linear model&quot;</span><span class="op">);</span></span> <span id="cb17-8"><a href="#cb17-8" tabindex="-1"></a> <span class="op">}</span></span> <span id="cb17-9"><a href="#cb17-9" tabindex="-1"></a> doubles resid<span class="op">(</span>mod<span class="op">[</span><span class="st">&quot;residuals&quot;</span><span class="op">]);</span></span> <span id="cb17-10"><a href="#cb17-10" tabindex="-1"></a> doubles fitted<span class="op">(</span>mod<span class="op">[</span><span class="st">&quot;fitted.values&quot;</span><span class="op">]);</span></span> <span id="cb17-11"><a href="#cb17-11" tabindex="-1"></a> <span class="dt">int</span> n <span class="op">=</span> resid<span class="op">.</span>size<span class="op">();</span></span> <span id="cb17-12"><a href="#cb17-12" tabindex="-1"></a> <span class="dt">double</span> err <span class="op">=</span> <span class="dv">0</span><span class="op">;</span></span> <span id="cb17-13"><a href="#cb17-13" tabindex="-1"></a> <span class="cf">for</span><span class="op">(</span><span class="dt">int</span> i <span class="op">=</span> <span class="dv">0</span><span class="op">;</span> i <span class="op">&lt;</span> n<span class="op">;</span> <span class="op">++</span>i<span class="op">)</span> <span class="op">{</span></span> <span id="cb17-14"><a href="#cb17-14" tabindex="-1"></a> err <span class="op">+=</span> resid<span class="op">[</span>i<span class="op">]</span> <span class="op">/</span> <span class="op">(</span>fitted<span class="op">[</span>i<span class="op">]</span> <span class="op">+</span> resid<span class="op">[</span>i<span class="op">]);</span></span> <span id="cb17-15"><a href="#cb17-15" tabindex="-1"></a> <span class="op">}</span></span> <span id="cb17-16"><a href="#cb17-16" tabindex="-1"></a> <span class="cf">return</span> err <span class="op">/</span> n<span class="op">;</span></span> <span id="cb17-17"><a href="#cb17-17" tabindex="-1"></a><span class="op">}</span></span></code></pre></div> <div class="sourceCode" id="cb18"><pre class="sourceCode r"><code class="sourceCode r"><span id="cb18-1"><a href="#cb18-1" tabindex="-1"></a>mod <span class="ot">&lt;-</span> <span class="fu">lm</span>(mpg <span class="sc">~</span> wt, <span class="at">data =</span> mtcars)</span> <span id="cb18-2"><a href="#cb18-2" tabindex="-1"></a><span class="fu">mpe</span>(mod)</span> <span id="cb18-3"><a href="#cb18-3" tabindex="-1"></a><span class="co">#&gt; [1] -0.01541615</span></span></code></pre></div> </div> <div id="functions-cpp11" class