<?xml version="1.0" encoding="UTF-8"?>
<rss  xmlns:atom="http://www.w3.org/2005/Atom" 
      xmlns:media="http://search.yahoo.com/mrss/" 
      xmlns:content="http://purl.org/rss/1.0/modules/content/" 
      xmlns:dc="http://purl.org/dc/elements/1.1/" 
      version="2.0">
<channel>
<title>Tidy Ecology</title>
<link>https://tidyecology.com/</link>
<atom:link href="https://tidyecology.com/index.xml" rel="self" type="application/rss+xml"/>
<description>Reproducible R and QGIS tutorials for ecologists: diversity, ordination, occupancy and spatial analysis, each with the model checks that go with it.</description>
<image>
<url>https://tidyecology.com/og-image.png</url>
<title>Tidy Ecology</title>
<link>https://tidyecology.com/</link>
<height>76</height>
<width>144</width>
</image>
<generator>quarto-1.9.38</generator>
<lastBuildDate>Mon, 28 Sep 2026 11:00:00 GMT</lastBuildDate>
<item>
  <title>Records on grid lines and floating point in R</title>
  <dc:creator>Tidy Ecology</dc:creator>
  <link>https://tidyecology.com/posts/records-on-grid-lines-and-floating-point/</link>
  <description><![CDATA[ 





<p><em>Corrected 14 October 2026: the post said that beside every empty column or row of the floor() map lies one with twice the records; that holds for the columns, while in the rows the doubled row is two rows south of the empty one, and the text now says so.</em></p>
<p>A plant atlas maps records in cells of 0.1 degree, from 20 to 30 degrees east and from 44 to 48 degrees north: one hundred columns and forty rows. The records come from herbarium sheets and an online occurrence export, and they carry coordinates to one decimal place, 23.4 east, 46.7 north. The column of a record is worked out the way a textbook would put it: subtract the western edge of the atlas, divide by the cell size, round down. <code>floor((lon - 20) / 0.1)</code>. The map that comes out has empty columns in a regular pattern, each one beside a column with twice the records.</p>
<p>Every one-decimal longitude on this atlas lies exactly on a cell edge, so every record depends on how the arithmetic settles a tie that exists in the decimal number but not in the binary number R stores. This post counts what three common routes do with such records: the formula above, <code>cellFromXY()</code> from terra, and a spatial join with sf. It then shows the fix, which is to decide first which cell owns a point on a line and then to do the cell arithmetic in whole numbers.</p>
<p>Floating point has come up on this site before, in a narrower form. <a href="https://tidyecology.com/posts/pinning-package-versions-with-renv/">Pinning package versions with renv</a> shows two routes to the same sum disagreeing in the last bits and says this matters “at exactly one place: an equality test”. <a href="https://tidyecology.com/posts/checking-an-analysis-script/">Checking an analysis script</a> finds that the usual worry about summation order is misplaced for its totals. A cell index is an equality test in disguise, and it is where the last bits decide something. <a href="https://tidyecology.com/posts/snapped-coordinates-and-clustering/">Snapped coordinates and a clustering verdict</a> grids continuous coordinates into cells of whole units, where no record sits on a line, and <a href="https://tidyecology.com/posts/rounded-and-coarsened-measurements/">Rounded and coarsened measurements</a> is about what rounding does to statistics, not to which cell a value lands in. <a href="https://tidyecology.com/posts/richness-mapping-sf/">Mapping species richness in R with sf</a> joins records to a grid with <code>st_join()</code>; its records have continuous coordinates, so the question of a record on a cell edge does not arise there.</p>
<p><strong>The short answer.</strong> Decimal fractions such as 0.1 and 20.2 are stored in binary as the nearest representable number, which is a little above or a little below the value you typed. On a grid line that difference decides the cell. Choose an edge rule before you grid anything (here: a cell owns its western and southern edges), turn the coordinates into whole numbers of the smallest unit you trust with <code>round()</code>, and compute the cell index with integer division. Hand terra or sf the cell centre, not the raw record.</p>
<p>The records below are synthetic and the seed is in the code. The misassignment shares are counts over every grid-line value, not Monte Carlo estimates: the random records only decide how often each value occurs.</p>
<div class="cell">
<div class="code-copy-outer-scaffold"><div class="sourceCode cell-code" id="cb1" style="background: #f1f3f5;"><pre class="sourceCode r code-with-copy"><code class="sourceCode r"><span id="cb1-1"><span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">library</span>(ggplot2)</span>
<span id="cb1-2"><span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">library</span>(terra)</span>
<span id="cb1-3"><span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">library</span>(sf)</span>
<span id="cb1-4"></span>
<span id="cb1-5">te_paper  <span class="ot" style="color: #003B4F;
background-color: null;
font-style: inherit;">&lt;-</span> <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"#f5f4ee"</span></span>
<span id="cb1-6">te_ink    <span class="ot" style="color: #003B4F;
background-color: null;
font-style: inherit;">&lt;-</span> <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"#16241d"</span></span>
<span id="cb1-7">te_body   <span class="ot" style="color: #003B4F;
background-color: null;
font-style: inherit;">&lt;-</span> <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"#2c3a31"</span></span>
<span id="cb1-8">te_forest <span class="ot" style="color: #003B4F;
background-color: null;
font-style: inherit;">&lt;-</span> <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"#275139"</span></span>
<span id="cb1-9">te_rust   <span class="ot" style="color: #003B4F;
background-color: null;
font-style: inherit;">&lt;-</span> <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"#b5534e"</span></span>
<span id="cb1-10">te_gold   <span class="ot" style="color: #003B4F;
background-color: null;
font-style: inherit;">&lt;-</span> <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"#c9b458"</span></span>
<span id="cb1-11">te_line   <span class="ot" style="color: #003B4F;
background-color: null;
font-style: inherit;">&lt;-</span> <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"#dad9ca"</span></span>
<span id="cb1-12"></span>
<span id="cb1-13">theme_datasheet <span class="ot" style="color: #003B4F;
background-color: null;
font-style: inherit;">&lt;-</span> <span class="cf" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">function</span>() {</span>
<span id="cb1-14">  <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">theme_minimal</span>(<span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">base_size =</span> <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">12</span>) <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">+</span></span>
<span id="cb1-15">    <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">theme</span>(<span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">plot.background  =</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">element_rect</span>(<span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">fill =</span> te_paper, <span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">colour =</span> <span class="cn" style="color: #8f5902;
background-color: null;
font-style: inherit;">NA</span>),</span>
<span id="cb1-16">          <span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">panel.background =</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">element_rect</span>(<span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">fill =</span> te_paper, <span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">colour =</span> <span class="cn" style="color: #8f5902;
background-color: null;
font-style: inherit;">NA</span>),</span>
<span id="cb1-17">          <span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">panel.grid.major =</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">element_line</span>(<span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">colour =</span> te_line, <span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">linewidth =</span> <span class="fl" style="color: #AD0000;
background-color: null;
font-style: inherit;">0.3</span>),</span>
<span id="cb1-18">          <span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">panel.grid.minor =</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">element_blank</span>(),</span>
<span id="cb1-19">          <span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">text             =</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">element_text</span>(<span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">colour =</span> te_body),</span>
<span id="cb1-20">          <span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">axis.text        =</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">element_text</span>(<span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">colour =</span> te_body),</span>
<span id="cb1-21">          <span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">strip.text       =</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">element_text</span>(<span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">colour =</span> te_ink, <span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">face =</span> <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"bold"</span>),</span>
<span id="cb1-22">          <span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">legend.position  =</span> <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"top"</span>)</span>
<span id="cb1-23">}</span>
<span id="cb1-24"></span>
<span id="cb1-25">versions <span class="ot" style="color: #003B4F;
background-color: null;
font-style: inherit;">&lt;-</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">c</span>(<span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">R =</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">paste</span>(R.version<span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">$</span>major, R.version<span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">$</span>minor, <span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">sep =</span> <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"."</span>),</span>
<span id="cb1-26">              <span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">terra =</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">packageDescription</span>(<span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"terra"</span>)<span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">$</span>Version,</span>
<span id="cb1-27">              <span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">sf =</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">packageDescription</span>(<span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"sf"</span>)<span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">$</span>Version)</span>
<span id="cb1-28">terra_year <span class="ot" style="color: #003B4F;
background-color: null;
font-style: inherit;">&lt;-</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">sub</span>(<span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"^NA$"</span>, <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"n.d."</span>, <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">format</span>(utils<span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">::</span><span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">packageDate</span>(<span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"terra"</span>), <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"%Y"</span>))</span>
<span id="cb1-29">versions</span></code></pre></div></div>
<div class="cell-output cell-output-stdout">
<pre><code>       R    terra       sf 
 "4.5.3" "1.9-50"  "1.1-3" </code></pre>
</div>
</div>
<section id="a-tenth-is-not-stored-as-a-tenth" class="level2">
<h2 id="a-tenth-is-not-stored-as-a-tenth-h" class="anchored" data-anchor-id="a-tenth-is-not-stored-as-a-tenth">A tenth is not stored as a tenth</h2>
<p>Start away from maps. A sediment core is cut into slices every 10 cm and the depths are generated with <code>seq()</code>; four depths that went to the lab are typed in by hand.</p>
<div class="cell">
<div class="code-copy-outer-scaffold"><div class="sourceCode cell-code" id="cb3" style="background: #f1f3f5;"><pre class="sourceCode r code-with-copy"><code class="sourceCode r"><span id="cb3-1">depth <span class="ot" style="color: #003B4F;
background-color: null;
font-style: inherit;">&lt;-</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">seq</span>(<span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">0</span>, <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">2</span>, <span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">by =</span> <span class="fl" style="color: #AD0000;
background-color: null;
font-style: inherit;">0.1</span>)                <span class="co" style="color: #5E5E5E;
background-color: null;
font-style: inherit;"># slice depths, metres</span></span>
<span id="cb3-2">typed <span class="ot" style="color: #003B4F;
background-color: null;
font-style: inherit;">&lt;-</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">c</span>(<span class="fl" style="color: #AD0000;
background-color: null;
font-style: inherit;">0.3</span>, <span class="fl" style="color: #AD0000;
background-color: null;
font-style: inherit;">0.6</span>, <span class="fl" style="color: #AD0000;
background-color: null;
font-style: inherit;">0.7</span>, <span class="fl" style="color: #AD0000;
background-color: null;
font-style: inherit;">1.2</span>)              <span class="co" style="color: #5E5E5E;
background-color: null;
font-style: inherit;"># depths typed from the lab sheet</span></span>
<span id="cb3-3"><span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">stopifnot</span>(<span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">identical</span>(depth, <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">0</span> <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">+</span> (<span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">0</span><span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">:</span><span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">20</span>) <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">*</span> <span class="fl" style="color: #AD0000;
background-color: null;
font-style: inherit;">0.1</span>))   <span class="co" style="color: #5E5E5E;
background-color: null;
font-style: inherit;"># seq() builds from + i * by</span></span>
<span id="cb3-4">found       <span class="ot" style="color: #003B4F;
background-color: null;
font-style: inherit;">&lt;-</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">sum</span>(depth <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">%in%</span> typed)</span>
<span id="cb3-5">same_typed  <span class="ot" style="color: #003B4F;
background-color: null;
font-style: inherit;">&lt;-</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">sum</span>(depth <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">==</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">round</span>(depth, <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">1</span>))</span>
<span id="cb3-6">found_round <span class="ot" style="color: #003B4F;
background-color: null;
font-style: inherit;">&lt;-</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">sum</span>(<span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">round</span>(depth, <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">1</span>) <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">%in%</span> typed)</span>
<span id="cb3-7"><span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">c</span>(<span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">found =</span> found, <span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">seq_equal_to_typed =</span> same_typed, <span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">of =</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">length</span>(depth),</span>
<span id="cb3-8">  <span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">found_after_round =</span> found_round)</span></code></pre></div></div>
<div class="cell-output cell-output-stdout">
<pre><code>             found seq_equal_to_typed                 of  found_after_round 
                 0                 14                 21                  4 </code></pre>
</div>
<div class="code-copy-outer-scaffold"><div class="sourceCode cell-code" id="cb5" style="background: #f1f3f5;"><pre class="sourceCode r code-with-copy"><code class="sourceCode r"><span id="cb5-1"><span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">sprintf</span>(<span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"%.20f"</span>, <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">c</span>(<span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">seq_value =</span> depth[<span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">4</span>], <span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">typed_value =</span> <span class="fl" style="color: #AD0000;
background-color: null;
font-style: inherit;">0.3</span>))</span></code></pre></div></div>
<div class="cell-output cell-output-stdout">
<pre><code>[1] "0.30000000000000004441" "0.29999999999999998890"</code></pre>
</div>
<div class="code-copy-outer-scaffold"><div class="sourceCode cell-code" id="cb7" style="background: #f1f3f5;"><pre class="sourceCode r code-with-copy"><code class="sourceCode r"><span id="cb7-1">gap_03 <span class="ot" style="color: #003B4F;
background-color: null;
font-style: inherit;">&lt;-</span> depth[<span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">4</span>] <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">-</span> <span class="fl" style="color: #AD0000;
background-color: null;
font-style: inherit;">0.3</span></span>
<span id="cb7-2"><span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">stopifnot</span>(gap_03 <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">==</span> <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">2</span><span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">^-</span><span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">54</span>)                   <span class="co" style="color: #5E5E5E;
background-color: null;
font-style: inherit;"># one binary step at this size</span></span></code></pre></div></div>
</div>
<p><code>%in%</code> looks for exact matches and finds 0 of the 4 depths. <code>seq()</code> builds each value as the start plus i times the step, and <code>3 * 0.1</code> is not the same binary number as the <code>0.3</code> the parser makes from the text “0.3”; the two differ by <img src="https://latex.codecogs.com/png.latex?5.55%20%5Ctimes%2010%5E%7B-17%7D">, which is 2 to the power -54, one step of the binary number line at this size. Of the 21 depths, 14 equal the value you would get by typing them and 7 do not. <code>round(depth, 1)</code> maps each one back to the nearest typed value, and then all 4 are found. This is the problem question 7.31 of the R FAQ answers (Hornik and R Core Team 2023; its own examples are <code>sqrt(2) * sqrt(2) == 2</code> and <code>.3 + .6 == .9</code>), and Goldberg (1991) explains the arithmetic behind it. So far nothing is new: compare with a tolerance, or round first.</p>
</section>
<section id="one-formula-one-hundred-longitudes" class="level2">
<h2 id="one-formula-one-hundred-longitudes-h" class="anchored" data-anchor-id="one-formula-one-hundred-longitudes">One formula, one hundred longitudes</h2>
<p>The atlas is the same problem at every record. Its edge rule is written down before any arithmetic: a cell includes its western and southern edges, so the column of longitude 23.4 is the cell from 23.4 to 23.5, column 34 counted from 0. In whole tenths of a degree that rule is exact: 23.4 is 234 tenths, and 234 minus 200 is 34.</p>
<p>The chunk below takes all 100 one-decimal longitudes of the atlas, from 20.0 to 29.9, parsed from text as they would be read from a file, and computes the column three ways: dividing by 0.1, multiplying by 10, and in whole tenths.</p>
<div class="cell">
<div class="code-copy-outer-scaffold"><div class="sourceCode cell-code" id="cb8" style="background: #f1f3f5;"><pre class="sourceCode r code-with-copy"><code class="sourceCode r"><span id="cb8-1">x0 <span class="ot" style="color: #003B4F;
background-color: null;
font-style: inherit;">&lt;-</span> <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">20</span>; y0 <span class="ot" style="color: #003B4F;
background-color: null;
font-style: inherit;">&lt;-</span> <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">44</span>; cell <span class="ot" style="color: #003B4F;
background-color: null;
font-style: inherit;">&lt;-</span> <span class="fl" style="color: #AD0000;
background-color: null;
font-style: inherit;">0.1</span>                          <span class="co" style="color: #5E5E5E;
background-color: null;
font-style: inherit;"># atlas origin and cell size, degrees</span></span>
<span id="cb8-2">lon_values <span class="ot" style="color: #003B4F;
background-color: null;
font-style: inherit;">&lt;-</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">as.numeric</span>(<span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">sprintf</span>(<span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"%.1f"</span>, <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">200</span><span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">:</span><span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">299</span> <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">/</span> <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">10</span>))    <span class="co" style="color: #5E5E5E;
background-color: null;
font-style: inherit;"># 20.0, 20.1, ..., 29.9</span></span>
<span id="cb8-3">tenths     <span class="ot" style="color: #003B4F;
background-color: null;
font-style: inherit;">&lt;-</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">round</span>(lon_values <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">*</span> <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">10</span>)                       <span class="co" style="color: #5E5E5E;
background-color: null;
font-style: inherit;"># whole tenths: exact</span></span>
<span id="cb8-4">cols <span class="ot" style="color: #003B4F;
background-color: null;
font-style: inherit;">&lt;-</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">data.frame</span>(<span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">lon =</span> lon_values,</span>
<span id="cb8-5">                   <span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">intended =</span> tenths <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">-</span> <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">200</span>,                <span class="co" style="color: #5E5E5E;
background-color: null;
font-style: inherit;"># the edge rule, in integers</span></span>
<span id="cb8-6">                   <span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">divide   =</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">floor</span>((lon_values <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">-</span> x0) <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">/</span> cell),</span>
<span id="cb8-7">                   <span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">multiply =</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">floor</span>((lon_values <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">-</span> x0) <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">*</span> <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">10</span>))</span>
<span id="cb8-8">wrong_col <span class="ot" style="color: #003B4F;
background-color: null;
font-style: inherit;">&lt;-</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">colSums</span>(cols[, <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">c</span>(<span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"divide"</span>, <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"multiply"</span>)] <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">!=</span> cols<span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">$</span>intended)</span>
<span id="cb8-9"><span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">stopifnot</span>(<span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">all</span>(cols<span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">$</span>divide[cols<span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">$</span>multiply <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">!=</span> cols<span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">$</span>intended] <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">!=</span> cols<span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">$</span>intended[cols<span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">$</span>multiply <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">!=</span> cols<span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">$</span>intended]))</span>
<span id="cb8-10">wrong_col</span></code></pre></div></div>
<div class="cell-output cell-output-stdout">
<pre><code>  divide multiply 
      40       33 </code></pre>
</div>
<div class="code-copy-outer-scaffold"><div class="sourceCode cell-code" id="cb10" style="background: #f1f3f5;"><pre class="sourceCode r code-with-copy"><code class="sourceCode r"><span id="cb10-1"><span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">table</span>(<span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">divide_minus_intended =</span> cols<span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">$</span>divide <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">-</span> cols<span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">$</span>intended)</span></code></pre></div></div>
<div class="cell-output cell-output-stdout">
<pre><code>divide_minus_intended
-1  0 
40 60 </code></pre>
</div>
<div class="code-copy-outer-scaffold"><div class="sourceCode cell-code" id="cb12" style="background: #f1f3f5;"><pre class="sourceCode r code-with-copy"><code class="sourceCode r"><span id="cb12-1">wrong_lon <span class="ot" style="color: #003B4F;
background-color: null;
font-style: inherit;">&lt;-</span> cols<span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">$</span>lon[cols<span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">$</span>divide <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">!=</span> cols<span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">$</span>intended]</span>
<span id="cb12-2">wrong_per_degree <span class="ot" style="color: #003B4F;
background-color: null;
font-style: inherit;">&lt;-</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">table</span>(<span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">floor</span>(wrong_lon))</span>
<span id="cb12-3">wrong_tenths <span class="ot" style="color: #003B4F;
background-color: null;
font-style: inherit;">&lt;-</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">sort</span>(<span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">unique</span>(<span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">round</span>(wrong_lon <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">*</span> <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">10</span>) <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">%%</span> <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">10</span>))</span>
<span id="cb12-4"><span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">c</span>(<span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">values_per_degree =</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">unique</span>(<span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">as.vector</span>(wrong_per_degree)))</span></code></pre></div></div>
<div class="cell-output cell-output-stdout">
<pre><code>values_per_degree 
                4 </code></pre>
</div>
<div class="code-copy-outer-scaffold"><div class="sourceCode cell-code" id="cb14" style="background: #f1f3f5;"><pre class="sourceCode r code-with-copy"><code class="sourceCode r"><span id="cb14-1"><span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">sprintf</span>(<span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"%.20f"</span>, <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">c</span>(<span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">lon =</span> <span class="fl" style="color: #AD0000;
background-color: null;
font-style: inherit;">20.2</span>, <span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">minus_origin =</span> <span class="fl" style="color: #AD0000;
background-color: null;
font-style: inherit;">20.2</span> <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">-</span> x0, <span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">divided =</span> (<span class="fl" style="color: #AD0000;
background-color: null;
font-style: inherit;">20.2</span> <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">-</span> x0) <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">/</span> cell))</span></code></pre></div></div>
<div class="cell-output cell-output-stdout">
<pre><code>[1] "20.19999999999999928946" "0.19999999999999928946" 
[3] "1.99999999999999289457" </code></pre>
</div>
</div>
<p><code>floor((lon - 20) / 0.1)</code> puts 40 of the 100 longitudes in the wrong column, and every one of them one column to the west. In every degree they are the same 4 values, those ending in .2, .4, .7, .9. The last line shows why for 20.2. The stored number is slightly below 20.2; subtracting 20 is exact and leaves the small error standing next to a small number, so the difference is 0.19999999999999929: the tiny error of 20.2 now sits beside a number a hundred times smaller, and relative to that number it is a hundred times larger. Dividing by the stored 0.1, which is slightly above one tenth, lowers it again, and <code>floor()</code> of 1.99999999999999 is 1. Multiplying by 10 instead gets 33 wrong, all of them among the 40 (the <code>stopifnot()</code> line checks this). Neither route is careless; both ask <code>floor()</code> to settle a tie that only exists in decimal.</p>
<div class="cell">
<div class="cell-output-display">
<div id="fig-longitudes" class="quarto-float quarto-figure quarto-figure-center anchored" alt="Two horizontal rows of 100 narrow bars, one bar for each one-decimal longitude from 20.0 to 29.9, on an axis from 20 to 30 degrees east. The upper row, floor((lon - 20) / 0.1), repeats one pattern in every degree: four rust bars, at .2, .4, .7 and .9, among six green ones. The lower row, floor((lon - 20) * 10), has four rust bars per degree from 20 to 25, three in 26 and two per degree from 27 to 29, with green bars elsewhere.">
<figure class="quarto-float quarto-float-fig figure">
<div aria-describedby="fig-longitudes-caption-0ceaefa1-69ba-4598-a22c-09a6ac19f8ca">
<img src="https://tidyecology.com/posts/records-on-grid-lines-and-floating-point/index_files/figure-html/fig-longitudes-1.png" class="img-fluid figure-img" alt="Two horizontal rows of 100 narrow bars, one bar for each one-decimal longitude from 20.0 to 29.9, on an axis from 20 to 30 degrees east. The upper row, floor((lon - 20) / 0.1), repeats one pattern in every degree: four rust bars, at .2, .4, .7 and .9, among six green ones. The lower row, floor((lon - 20) * 10), has four rust bars per degree from 20 to 25, three in 26 and two per degree from 27 to 29, with green bars elsewhere." width="720">
</div>
<figcaption class="quarto-float-caption-bottom quarto-float-caption quarto-float-fig" id="fig-longitudes-caption-0ceaefa1-69ba-4598-a22c-09a6ac19f8ca">
Figure&nbsp;1: All 100 one-decimal longitudes of the atlas, each on a cell edge, and the column two formulas give them. Each bar is one recorded value: rust bars land one column west of the column the edge rule assigns, green bars land where the rule puts them. The integer rule is correct by construction, so it is not drawn.
</figcaption>
</figure>
</div>
</div>
</div>
<p>How many values go wrong depends on the origin, the cell size and the number of decimals. The next chunk repeats the count for other grids. Each row is an exact enumeration of every recorded value in a span of ten degrees (four for the latitude row); there is no sampling in it.</p>
<div class="cell">
<div class="code-copy-outer-scaffold"><div class="sourceCode cell-code" id="cb16" style="background: #f1f3f5;"><pre class="sourceCode r code-with-copy"><code class="sourceCode r"><span id="cb16-1">count_wrong <span class="ot" style="color: #003B4F;
background-color: null;
font-style: inherit;">&lt;-</span> <span class="cf" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">function</span>(origin, cell_units, dec, <span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">span =</span> <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">10</span>) {</span>
<span id="cb16-2">  <span class="co" style="color: #5E5E5E;
background-color: null;
font-style: inherit;"># cell_units: the cell size in units of the last recorded decimal</span></span>
<span id="cb16-3">  k <span class="ot" style="color: #003B4F;
background-color: null;
font-style: inherit;">&lt;-</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">round</span>(origin <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">*</span> <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">10</span><span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">^</span>dec) <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">+</span> <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">0</span><span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">:</span>(span <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">*</span> <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">10</span><span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">^</span>dec <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">-</span> <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">1</span>)          <span class="co" style="color: #5E5E5E;
background-color: null;
font-style: inherit;"># every value, in integers</span></span>
<span id="cb16-4">  v <span class="ot" style="color: #003B4F;
background-color: null;
font-style: inherit;">&lt;-</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">as.numeric</span>(<span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">sprintf</span>(<span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">paste0</span>(<span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"%."</span>, dec, <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"f"</span>), k <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">/</span> <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">10</span><span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">^</span>dec))  <span class="co" style="color: #5E5E5E;
background-color: null;
font-style: inherit;"># as read from text</span></span>
<span id="cb16-5">  cell_size <span class="ot" style="color: #003B4F;
background-color: null;
font-style: inherit;">&lt;-</span> cell_units <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">/</span> <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">10</span><span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">^</span>dec</span>
<span id="cb16-6">  intended  <span class="ot" style="color: #003B4F;
background-color: null;
font-style: inherit;">&lt;-</span> (k <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">-</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">round</span>(origin <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">*</span> <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">10</span><span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">^</span>dec)) <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">%/%</span> cell_units</span>
<span id="cb16-7">  on_line   <span class="ot" style="color: #003B4F;
background-color: null;
font-style: inherit;">&lt;-</span> (k <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">-</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">round</span>(origin <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">*</span> <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">10</span><span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">^</span>dec)) <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">%%</span> cell_units <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">==</span> <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">0</span></span>
<span id="cb16-8">  divide    <span class="ot" style="color: #003B4F;
background-color: null;
font-style: inherit;">&lt;-</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">floor</span>((v <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">-</span> origin) <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">/</span> cell_size)</span>
<span id="cb16-9">  <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">c</span>(<span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">values =</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">length</span>(v), <span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">on_a_line =</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">sum</span>(on_line), <span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">wrong =</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">sum</span>(divide <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">!=</span> intended),</span>
<span id="cb16-10">    <span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">wrong_off_a_line =</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">sum</span>(divide <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">!=</span> intended <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">&amp;</span> <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">!</span>on_line))</span>
<span id="cb16-11">}</span>
<span id="cb16-12">grids <span class="ot" style="color: #003B4F;
background-color: null;
font-style: inherit;">&lt;-</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">rbind</span>(</span>
<span id="cb16-13">  <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"lon from 20, 0.1 cells, 1 decimal"</span>   <span class="ot" style="color: #003B4F;
background-color: null;
font-style: inherit;">=</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">count_wrong</span>(<span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">20</span>, <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">1</span>, <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">1</span>),</span>
<span id="cb16-14">  <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"lon from 16, 0.1 cells, 1 decimal"</span>   <span class="ot" style="color: #003B4F;
background-color: null;
font-style: inherit;">=</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">count_wrong</span>(<span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">16</span>, <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">1</span>, <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">1</span>),</span>
<span id="cb16-15">  <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"lat from 44, 0.1 cells, 1 decimal"</span>   <span class="ot" style="color: #003B4F;
background-color: null;
font-style: inherit;">=</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">count_wrong</span>(<span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">44</span>, <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">1</span>, <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">1</span>, <span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">span =</span> <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">4</span>),</span>
<span id="cb16-16">  <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"lon from 20, 0.5 cells, 1 decimal"</span>   <span class="ot" style="color: #003B4F;
background-color: null;
font-style: inherit;">=</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">count_wrong</span>(<span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">20</span>, <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">5</span>, <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">1</span>),</span>
<span id="cb16-17">  <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"lon from 15.9, 0.5 cells, 1 decimal"</span> <span class="ot" style="color: #003B4F;
background-color: null;
font-style: inherit;">=</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">count_wrong</span>(<span class="fl" style="color: #AD0000;
background-color: null;
font-style: inherit;">15.9</span>, <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">5</span>, <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">1</span>),</span>
<span id="cb16-18">  <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"lon from 20, 0.1 cells, 2 decimals"</span>  <span class="ot" style="color: #003B4F;
background-color: null;
font-style: inherit;">=</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">count_wrong</span>(<span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">20</span>, <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">10</span>, <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">2</span>),</span>
<span id="cb16-19">  <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"lon from 20, 0.05 cells, 2 decimals"</span> <span class="ot" style="color: #003B4F;
background-color: null;
font-style: inherit;">=</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">count_wrong</span>(<span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">20</span>, <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">5</span>, <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">2</span>),</span>
<span id="cb16-20">  <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"lon from 20, 0.25 cells, 2 decimals"</span> <span class="ot" style="color: #003B4F;
background-color: null;
font-style: inherit;">=</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">count_wrong</span>(<span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">20</span>, <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">25</span>, <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">2</span>),</span>
<span id="cb16-21">  <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"lon from 20, 0.01 cells, 2 decimals"</span> <span class="ot" style="color: #003B4F;
background-color: null;
font-style: inherit;">=</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">count_wrong</span>(<span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">20</span>, <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">1</span>, <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">2</span>))</span>
<span id="cb16-22">grids</span></code></pre></div></div>
<div class="cell-output cell-output-stdout">
<pre><code>                                    values on_a_line wrong wrong_off_a_line
lon from 20, 0.1 cells, 1 decimal      100       100    40                0
lon from 16, 0.1 cells, 1 decimal      100       100    40                0
lat from 44, 0.1 cells, 1 decimal       40        40    16                0
lon from 20, 0.5 cells, 1 decimal      100        20     0                0
lon from 15.9, 0.5 cells, 1 decimal    100        20    19                0
lon from 20, 0.1 cells, 2 decimals    1000       100    40                0
lon from 20, 0.05 cells, 2 decimals   1000       200    80                0
lon from 20, 0.25 cells, 2 decimals   1000        40     0                0
lon from 20, 0.01 cells, 2 decimals   1000      1000   423                0</code></pre>
</div>
<div class="code-copy-outer-scaffold"><div class="sourceCode cell-code" id="cb18" style="background: #f1f3f5;"><pre class="sourceCode r code-with-copy"><code class="sourceCode r"><span id="cb18-1"><span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">stopifnot</span>(<span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">all</span>(grids[, <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"wrong_off_a_line"</span>] <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">==</span> <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">0</span>))</span>
<span id="cb18-2">whole_origins <span class="ot" style="color: #003B4F;
background-color: null;
font-style: inherit;">&lt;-</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">sapply</span>(<span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">-</span><span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">179</span><span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">:</span><span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">179</span>, <span class="cf" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">function</span>(o) <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">count_wrong</span>(o, <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">5</span>, <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">1</span>)[[<span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"wrong"</span>]] <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">+</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">count_wrong</span>(o, <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">25</span>, <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">2</span>)[[<span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"wrong"</span>]])</span>
<span id="cb18-3"><span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">stopifnot</span>(<span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">all</span>(whole_origins <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">==</span> <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">0</span>))    <span class="co" style="color: #5E5E5E;
background-color: null;
font-style: inherit;"># 0.5 and 0.25 cells from every whole-degree origin</span></span></code></pre></div></div>
</div>
<p>Two things hold in every row. Only values on a line are ever misplaced (the last column is zero throughout), and the share at risk is the share on a line: all of them for one-decimal records on a 0.1 grid, one in ten for two-decimal records on the same grid. Among the values on a line, the share that goes wrong is not a constant. It is 40 of 100 for the atlas longitudes, 16 of 40 for its latitudes and 423 of 1000 for a 0.01 degree grid, and it is zero for 0.5 and 0.25 degree cells that start on a whole degree, because a half and a quarter are exact in binary and so is every line of such a grid (the second <code>stopifnot()</code> checks every whole-degree origin from 179 west to 179 east). The origin has to be exact too: the same 0.5 degree cells starting at 15.9 misplace 19 of 20 values on a line. The count also depends on the magnitude of the coordinates, so check it on your own extent rather than borrowing these.</p>
</section>
<section id="what-the-stripes-do-to-an-atlas-map" class="level2">
<h2 id="what-the-stripes-do-to-an-atlas-map-h" class="anchored" data-anchor-id="what-the-stripes-do-to-an-atlas-map">What the stripes do to an atlas map</h2>
<p>The atlas gets 20000 synthetic records, one decimal in each coordinate, with every value in the atlas equally likely. Rows are assigned the same two ways as columns.</p>
<div class="cell">
<div class="code-copy-outer-scaffold"><div class="sourceCode cell-code" id="cb19" style="background: #f1f3f5;"><pre class="sourceCode r code-with-copy"><code class="sourceCode r"><span id="cb19-1"><span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">set.seed</span>(<span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">2210</span>)</span>
<span id="cb19-2">n_rec <span class="ot" style="color: #003B4F;
background-color: null;
font-style: inherit;">&lt;-</span> <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">20000</span></span>
<span id="cb19-3">lon_k <span class="ot" style="color: #003B4F;
background-color: null;
font-style: inherit;">&lt;-</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">sample</span>(<span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">200</span><span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">:</span><span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">299</span>, n_rec, <span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">replace =</span> <span class="cn" style="color: #8f5902;
background-color: null;
font-style: inherit;">TRUE</span>)            <span class="co" style="color: #5E5E5E;
background-color: null;
font-style: inherit;"># tenths of a degree</span></span>
<span id="cb19-4">lat_k <span class="ot" style="color: #003B4F;
background-color: null;
font-style: inherit;">&lt;-</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">sample</span>(<span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">440</span><span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">:</span><span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">479</span>, n_rec, <span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">replace =</span> <span class="cn" style="color: #8f5902;
background-color: null;
font-style: inherit;">TRUE</span>)</span>
<span id="cb19-5">records <span class="ot" style="color: #003B4F;
background-color: null;
font-style: inherit;">&lt;-</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">data.frame</span>(<span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">lon =</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">as.numeric</span>(<span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">sprintf</span>(<span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"%.1f"</span>, lon_k <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">/</span> <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">10</span>)),</span>
<span id="cb19-6">                      <span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">lat =</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">as.numeric</span>(<span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">sprintf</span>(<span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"%.1f"</span>, lat_k <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">/</span> <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">10</span>)))</span>
<span id="cb19-7">col_rule  <span class="ot" style="color: #003B4F;
background-color: null;
font-style: inherit;">&lt;-</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">round</span>(records<span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">$</span>lon <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">*</span> <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">10</span>) <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">-</span> <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">200</span>                 <span class="co" style="color: #5E5E5E;
background-color: null;
font-style: inherit;"># edge rule, integers</span></span>
<span id="cb19-8">row_rule  <span class="ot" style="color: #003B4F;
background-color: null;
font-style: inherit;">&lt;-</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">round</span>(records<span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">$</span>lat <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">*</span> <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">10</span>) <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">-</span> <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">440</span></span>
<span id="cb19-9">col_floor <span class="ot" style="color: #003B4F;
background-color: null;
font-style: inherit;">&lt;-</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">floor</span>((records<span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">$</span>lon <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">-</span> x0) <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">/</span> cell)</span>
<span id="cb19-10">row_floor <span class="ot" style="color: #003B4F;
background-color: null;
font-style: inherit;">&lt;-</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">floor</span>((records<span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">$</span>lat <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">-</span> y0) <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">/</span> cell)</span>
<span id="cb19-11">per_cell <span class="ot" style="color: #003B4F;
background-color: null;
font-style: inherit;">&lt;-</span> <span class="cf" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">function</span>(col, row) <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">tabulate</span>(row <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">*</span> <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">100</span> <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">+</span> col <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">+</span> <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">1</span>, <span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">nbins =</span> <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">4000</span>)</span>
<span id="cb19-12">n_rule  <span class="ot" style="color: #003B4F;
background-color: null;
font-style: inherit;">&lt;-</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">per_cell</span>(col_rule, row_rule)</span>
<span id="cb19-13">n_floor <span class="ot" style="color: #003B4F;
background-color: null;
font-style: inherit;">&lt;-</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">per_cell</span>(col_floor, row_floor)</span>
<span id="cb19-14">lat_values <span class="ot" style="color: #003B4F;
background-color: null;
font-style: inherit;">&lt;-</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">as.numeric</span>(<span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">sprintf</span>(<span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"%.1f"</span>, <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">440</span><span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">:</span><span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">479</span> <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">/</span> <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">10</span>))</span>
<span id="cb19-15">wrong_lat  <span class="ot" style="color: #003B4F;
background-color: null;
font-style: inherit;">&lt;-</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">sum</span>(<span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">floor</span>((lat_values <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">-</span> y0) <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">/</span> cell) <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">!=</span> <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">0</span><span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">:</span><span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">39</span>)</span>
<span id="cb19-16">share_expected <span class="ot" style="color: #003B4F;
background-color: null;
font-style: inherit;">&lt;-</span> <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">1</span> <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">-</span> (<span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">1</span> <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">-</span> wrong_col[[<span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"divide"</span>]] <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">/</span> <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">100</span>) <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">*</span> (<span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">1</span> <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">-</span> wrong_lat <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">/</span> <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">40</span>)</span>
<span id="cb19-17">share_moved    <span class="ot" style="color: #003B4F;
background-color: null;
font-style: inherit;">&lt;-</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">mean</span>(col_floor <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">!=</span> col_rule <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">|</span> row_floor <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">!=</span> row_rule)</span>
<span id="cb19-18"><span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">c</span>(<span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">empty_cells_rule =</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">sum</span>(n_rule <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">==</span> <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">0</span>), <span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">empty_cells_floor =</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">sum</span>(n_floor <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">==</span> <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">0</span>),</span>
<span id="cb19-19">  <span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">max_per_cell_rule =</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">max</span>(n_rule), <span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">max_per_cell_floor =</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">max</span>(n_floor),</span>
<span id="cb19-20">  <span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">share_expected =</span> share_expected, <span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">share_moved =</span> share_moved,</span>
<span id="cb19-21">  <span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">empty_expected_by_chance =</span> <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">4000</span> <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">*</span> (<span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">1</span> <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">-</span> <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">1</span> <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">/</span> <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">4000</span>)<span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">^</span>n_rec)</span></code></pre></div></div>
<div class="cell-output cell-output-stdout">
<pre><code>        empty_cells_rule        empty_cells_floor        max_per_cell_rule 
                21.00000               2085.00000                 15.00000 
      max_per_cell_floor           share_expected              share_moved 
                36.00000                  0.64000                  0.64105 
empty_expected_by_chance 
                26.93495 </code></pre>
</div>
</div>
<p>A record keeps its cell only if both its column and its row come out right. With every value equally likely, that has probability (1 - 40/100) times (1 - 16/40), so the expected share of records in the wrong cell is 0.64: arithmetic, not a simulation result. Of the 20000 drawn records a share of 0.6411 is in the wrong cell, which differs from 0.64 only because the draw does not hit every value equally often. Under the edge rule 21 of the 4000 cells have no record, in line with the 26.9 that chance alone leaves empty on average at five records per cell. Under <code>floor()</code> 2085 cells are empty and the fullest cell holds 36 records against 15. The empty cells are not scattered. A misplaced value moves into the neighbouring column or row; where nothing moves in to replace it, its own is left empty. In the columns the neighbour then holds twice the records. In the rows the misplaced latitudes come in pairs of neighbouring values, so both rows beside an empty one keep a normal count and the row with twice the records is two rows south of it. So the map shows stripes, and a richness or occupancy map built on it has gaps that look like a survey pattern.</p>
<div class="cell">
<div class="cell-output-display">
<div id="fig-atlas" class="quarto-float quarto-figure quarto-figure-center anchored" alt="Two maps of the atlas from 20 to 30 degrees east and 44 to 48 degrees north, each made of 4000 small cells shaded from pale to dark green by records per cell, with a colour bar marked 10, 20 and 30. Top panel, edge rule in whole tenths: an even pale green speckle with about twenty isolated rust cells. Bottom panel, floor((lon - 20) / 0.1) and floor((lat - 44) / 0.1): a lattice of rust stripes, four narrow vertical stripes in every degree of longitude and two horizontal stripes in every degree of latitude, one of them the top row, with darker green cells between them.">
<figure class="quarto-float quarto-float-fig figure">
<div aria-describedby="fig-atlas-caption-0ceaefa1-69ba-4598-a22c-09a6ac19f8ca">
<img src="https://tidyecology.com/posts/records-on-grid-lines-and-floating-point/index_files/figure-html/fig-atlas-1.png" class="img-fluid figure-img" alt="Two maps of the atlas from 20 to 30 degrees east and 44 to 48 degrees north, each made of 4000 small cells shaded from pale to dark green by records per cell, with a colour bar marked 10, 20 and 30. Top panel, edge rule in whole tenths: an even pale green speckle with about twenty isolated rust cells. Bottom panel, floor((lon - 20) / 0.1) and floor((lat - 44) / 0.1): a lattice of rust stripes, four narrow vertical stripes in every degree of longitude and two horizontal stripes in every degree of latitude, one of them the top row, with darker green cells between them." width="720">
</div>
<figcaption class="quarto-float-caption-bottom quarto-float-caption quarto-float-fig" id="fig-atlas-caption-0ceaefa1-69ba-4598-a22c-09a6ac19f8ca">
Figure&nbsp;2: Records per 0.1 degree cell for the same 20000 synthetic one-decimal records, gridded with the edge rule in whole tenths (top) and with floor((coordinate - origin) / 0.1) (bottom). Empty cells are rust.
</figcaption>
</figure>
</div>
</div>
</div>
</section>
<section id="terra-its-own-rule-and-the-same-arithmetic" class="level2">
<h2 id="terra-its-own-rule-and-the-same-arithmetic-h" class="anchored" data-anchor-id="terra-its-own-rule-and-the-same-arithmetic">terra: its own rule, and the same arithmetic</h2>
<p><code>cellFromXY()</code> in terra (Hijmans 2026) has an edge rule of its own. Its help page (terra 1.9-50, the CRAN version when this was written) says that a point on the edge of two or four cells goes to the cell on the right, the cell below, or on a corner the cell below and to the right, and a comment in the C++ source adds that points on the right-hand and bottom edges of the raster are kept inside. The first lines of the chunk check all three cases and both edges on a small raster of 0.5 degree cells, where every coordinate is exact in binary. So terra’s column rule is the atlas rule, and its row rule is the opposite one: a record on 46.7 north belongs to the cell from 46.6 to 46.7. The chunk compares what <code>cellFromXY()</code> returns for every grid-line longitude and latitude with terra’s own stated rule.</p>
<div class="cell">
<div class="code-copy-outer-scaffold"><div class="sourceCode cell-code" id="cb21" style="background: #f1f3f5;"><pre class="sourceCode r code-with-copy"><code class="sourceCode r"><span id="cb21-1">r05 <span class="ot" style="color: #003B4F;
background-color: null;
font-style: inherit;">&lt;-</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">rast</span>(<span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">xmin =</span> <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">20</span>, <span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">xmax =</span> <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">22</span>, <span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">ymin =</span> <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">44</span>, <span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">ymax =</span> <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">46</span>, <span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">resolution =</span> <span class="fl" style="color: #AD0000;
background-color: null;
font-style: inherit;">0.5</span>)</span>
<span id="cb21-2">rc <span class="ot" style="color: #003B4F;
background-color: null;
font-style: inherit;">&lt;-</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">rowColFromCell</span>(r05, <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">cellFromXY</span>(r05, <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">rbind</span>(<span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">c</span>(<span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">21</span>, <span class="fl" style="color: #AD0000;
background-color: null;
font-style: inherit;">45.25</span>), <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">c</span>(<span class="fl" style="color: #AD0000;
background-color: null;
font-style: inherit;">20.75</span>, <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">45</span>), <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">c</span>(<span class="fl" style="color: #AD0000;
background-color: null;
font-style: inherit;">20.75</span>, <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">44</span>), <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">c</span>(<span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">22</span>, <span class="fl" style="color: #AD0000;
background-color: null;
font-style: inherit;">45.25</span>), <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">c</span>(<span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">21</span>, <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">45</span>))))</span>
<span id="cb21-3"><span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">stopifnot</span>(rc[<span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">1</span>, <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">2</span>] <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">==</span> <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">3</span>, rc[<span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">2</span>, <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">1</span>] <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">==</span> <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">3</span>, rc[<span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">3</span>, <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">1</span>] <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">==</span> <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">4</span>, rc[<span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">4</span>, <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">2</span>] <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">==</span> <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">4</span>, rc[<span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">5</span>, ] <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">==</span> <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">3</span>)   <span class="co" style="color: #5E5E5E;
background-color: null;
font-style: inherit;"># right, below, corner; outer edges inside</span></span>
<span id="cb21-4">atlas_r <span class="ot" style="color: #003B4F;
background-color: null;
font-style: inherit;">&lt;-</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">rast</span>(<span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">xmin =</span> <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">20</span>, <span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">xmax =</span> <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">30</span>, <span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">ymin =</span> <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">44</span>, <span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">ymax =</span> <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">48</span>, <span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">resolution =</span> <span class="fl" style="color: #AD0000;
background-color: null;
font-style: inherit;">0.1</span>)</span>
<span id="cb21-5">col_terra <span class="ot" style="color: #003B4F;
background-color: null;
font-style: inherit;">&lt;-</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">colFromCell</span>(atlas_r, <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">cellFromXY</span>(atlas_r, <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">cbind</span>(lon_values, <span class="fl" style="color: #AD0000;
background-color: null;
font-style: inherit;">46.05</span>))) <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">-</span> <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">1</span>   <span class="co" style="color: #5E5E5E;
background-color: null;
font-style: inherit;"># 0 = west</span></span>
<span id="cb21-6">row_terra <span class="ot" style="color: #003B4F;
background-color: null;
font-style: inherit;">&lt;-</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">rowFromCell</span>(atlas_r, <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">cellFromXY</span>(atlas_r, <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">cbind</span>(<span class="fl" style="color: #AD0000;
background-color: null;
font-style: inherit;">25.05</span>, lat_values)))</span>
<span id="cb21-7">row_below <span class="ot" style="color: #003B4F;
background-color: null;
font-style: inherit;">&lt;-</span> <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">40</span> <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">-</span> (<span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">0</span><span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">:</span><span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">39</span>) <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">+</span> <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">1</span>                  <span class="co" style="color: #5E5E5E;
background-color: null;
font-style: inherit;"># row, counted from the top, just below the line</span></span>
<span id="cb21-8">row_below[lat_values <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">==</span> <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">44</span>] <span class="ot" style="color: #003B4F;
background-color: null;
font-style: inherit;">&lt;-</span> <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">40</span>             <span class="co" style="color: #5E5E5E;
background-color: null;
font-style: inherit;"># the bottom edge goes up into the raster</span></span>
<span id="cb21-9">terra_col_off <span class="ot" style="color: #003B4F;
background-color: null;
font-style: inherit;">&lt;-</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">sum</span>(col_terra <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">!=</span> cols<span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">$</span>intended)</span>
<span id="cb21-10">terra_row_off <span class="ot" style="color: #003B4F;
background-color: null;
font-style: inherit;">&lt;-</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">sum</span>(row_terra <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">!=</span> row_below)</span>
<span id="cb21-11">terra_same_as_multiply <span class="ot" style="color: #003B4F;
background-color: null;
font-style: inherit;">&lt;-</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">identical</span>(<span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">as.numeric</span>(col_terra), <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">as.numeric</span>(cols<span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">$</span>multiply))</span>
<span id="cb21-12"><span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">c</span>(<span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">columns_off_rule =</span> terra_col_off, <span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">of =</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">length</span>(lon_values),</span>
<span id="cb21-13">  <span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">rows_off_rule =</span> terra_row_off, <span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">of =</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">length</span>(lat_values),</span>
<span id="cb21-14">  <span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">columns_as_floor_times_10 =</span> terra_same_as_multiply)</span></code></pre></div></div>
<div class="cell-output cell-output-stdout">
<pre><code>         columns_off_rule                        of             rows_off_rule 
                       33                       100                        16 
                       of columns_as_floor_times_10 
                       40                         1 </code></pre>
</div>
<div class="code-copy-outer-scaffold"><div class="sourceCode cell-code" id="cb23" style="background: #f1f3f5;"><pre class="sourceCode r code-with-copy"><code class="sourceCode r"><span id="cb23-1">cell_terra <span class="ot" style="color: #003B4F;
background-color: null;
font-style: inherit;">&lt;-</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">cellFromXY</span>(atlas_r, <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">as.matrix</span>(records))</span>
<span id="cb23-2">n_terra    <span class="ot" style="color: #003B4F;
background-color: null;
font-style: inherit;">&lt;-</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">tabulate</span>(cell_terra, <span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">nbins =</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">ncell</span>(atlas_r))</span>
<span id="cb23-3">top_row_records <span class="ot" style="color: #003B4F;
background-color: null;
font-style: inherit;">&lt;-</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">sum</span>(n_terra[<span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">1</span><span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">:</span><span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">100</span>])        <span class="co" style="color: #5E5E5E;
background-color: null;
font-style: inherit;"># cells 1 to 100: the row from 47.9 to 48</span></span>
<span id="cb23-4"><span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">c</span>(<span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">empty_cells_terra =</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">sum</span>(n_terra <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">==</span> <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">0</span>), <span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">records_in_top_row =</span> top_row_records)</span></code></pre></div></div>
<div class="cell-output cell-output-stdout">
<pre><code> empty_cells_terra records_in_top_row 
              1862                  0 </code></pre>
</div>
</div>
<p>With terra 1.9-50 on this page, 33 of the 100 grid-line longitudes land one column west of the column terra’s rule gives, and 16 of the 40 latitudes land in the row above the line instead of below it. Its columns are exactly those of <code>floor((lon - 20) * 10)</code> from the chunk before, because it computes the column the same way: subtract the western edge, multiply by the number of columns per degree, round down. On the 20000 records, 1862 of the 4000 cells of the raster are empty. Two causes are mixed in that count: the stripes from misplaced values, and the difference between terra’s row rule and the atlas rule. Under terra’s rule the records on 47.9 north belong to the row below, no record reaches the top row from 47.9 to 48, and all 100 of its cells are empty. None of this is a fault in terra. A point on a shared edge has no correct cell until somebody chooses a rule; terra chose one and writes it down, and floating point decides whether a given record meets it.</p>
</section>
<section id="sf-a-record-on-a-corner-belongs-to-four-cells" class="level2">
<h2 id="sf-a-record-on-a-corner-belongs-to-four-cells-h" class="anchored" data-anchor-id="sf-a-record-on-a-corner-belongs-to-four-cells">sf: a record on a corner belongs to four cells</h2>
<p>A spatial join asks a different question. <code>st_join()</code> pairs each point with every cell polygon it intersects (its default predicate is <code>st_intersects</code>), and a point on a shared edge intersects both cells. The grid below is the same atlas made with <code>st_make_grid()</code> from sf (Pebesma 2018). Spherical geometry is switched off so that sf treats longitude and latitude as plain x and y, the way the atlas is drawn.</p>
<div class="cell">
<div class="code-copy-outer-scaffold"><div class="sourceCode cell-code" id="cb25" style="background: #f1f3f5;"><pre class="sourceCode r code-with-copy"><code class="sourceCode r"><span id="cb25-1"><span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">stopifnot</span>(<span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">identical</span>(<span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">formals</span>(sf<span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">:::</span>st_join.sf)<span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">$</span>join, <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">quote</span>(st_intersects)))</span>
<span id="cb25-2"><span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">invisible</span>(<span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">suppressMessages</span>(<span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">sf_use_s2</span>(<span class="cn" style="color: #8f5902;
background-color: null;
font-style: inherit;">FALSE</span>)))</span>
<span id="cb25-3">atlas_bbox <span class="ot" style="color: #003B4F;
background-color: null;
font-style: inherit;">&lt;-</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">st_as_sfc</span>(<span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">st_bbox</span>(<span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">c</span>(<span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">xmin =</span> <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">20</span>, <span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">ymin =</span> <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">44</span>, <span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">xmax =</span> <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">30</span>, <span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">ymax =</span> <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">48</span>), <span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">crs =</span> <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">4326</span>))</span>
<span id="cb25-4">atlas_sf <span class="ot" style="color: #003B4F;
background-color: null;
font-style: inherit;">&lt;-</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">st_sf</span>(<span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">cell =</span> <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">1</span><span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">:</span><span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">4000</span>, <span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">geometry =</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">st_make_grid</span>(atlas_bbox, <span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">cellsize =</span> <span class="fl" style="color: #AD0000;
background-color: null;
font-style: inherit;">0.1</span>))</span>
<span id="cb25-5">rec_sf   <span class="ot" style="color: #003B4F;
background-color: null;
font-style: inherit;">&lt;-</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">st_as_sf</span>(records, <span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">coords =</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">c</span>(<span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"lon"</span>, <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"lat"</span>), <span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">crs =</span> <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">4326</span>, <span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">remove =</span> <span class="cn" style="color: #8f5902;
background-color: null;
font-style: inherit;">FALSE</span>)</span>
<span id="cb25-6">cells_hit <span class="ot" style="color: #003B4F;
background-color: null;
font-style: inherit;">&lt;-</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">lengths</span>(<span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">suppressMessages</span>(<span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">st_intersects</span>(rec_sf, atlas_sf)))</span>
<span id="cb25-7">joined    <span class="ot" style="color: #003B4F;
background-color: null;
font-style: inherit;">&lt;-</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">suppressMessages</span>(<span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">st_join</span>(rec_sf, atlas_sf))</span>
<span id="cb25-8">within_n  <span class="ot" style="color: #003B4F;
background-color: null;
font-style: inherit;">&lt;-</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">lengths</span>(<span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">suppressMessages</span>(<span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">st_within</span>(rec_sf, atlas_sf)))</span>
<span id="cb25-9"><span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">c</span>(<span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">records =</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">nrow</span>(rec_sf), <span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">joined_rows =</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">nrow</span>(joined), <span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">sum_cells_hit =</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">sum</span>(cells_hit))</span></code></pre></div></div>
<div class="cell-output cell-output-stdout">
<pre><code>      records   joined_rows sum_cells_hit 
        20000         76971         76971 </code></pre>
</div>
<div class="code-copy-outer-scaffold"><div class="sourceCode cell-code" id="cb27" style="background: #f1f3f5;"><pre class="sourceCode r code-with-copy"><code class="sourceCode r"><span id="cb27-1"><span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">table</span>(<span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">cells_per_record =</span> cells_hit)</span></code></pre></div></div>
<div class="cell-output cell-output-stdout">
<pre><code>cells_per_record
    1     2     4 
   29  1471 18500 </code></pre>
</div>
<div class="code-copy-outer-scaffold"><div class="sourceCode cell-code" id="cb29" style="background: #f1f3f5;"><pre class="sourceCode r code-with-copy"><code class="sourceCode r"><span id="cb29-1"><span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">table</span>(<span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">cells_within =</span> within_n)</span></code></pre></div></div>
<div class="cell-output cell-output-stdout">
<pre><code>cells_within
    0 
20000 </code></pre>
</div>
<div class="code-copy-outer-scaffold"><div class="sourceCode cell-code" id="cb31" style="background: #f1f3f5;"><pre class="sourceCode r code-with-copy"><code class="sourceCode r"><span id="cb31-1">line_x <span class="ot" style="color: #003B4F;
background-color: null;
font-style: inherit;">&lt;-</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">sort</span>(<span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">unique</span>(<span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">st_coordinates</span>(atlas_sf)[, <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"X"</span>]))   <span class="co" style="color: #5E5E5E;
background-color: null;
font-style: inherit;"># the lines sf computes, axis by axis</span></span>
<span id="cb31-2">line_y <span class="ot" style="color: #003B4F;
background-color: null;
font-style: inherit;">&lt;-</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">sort</span>(<span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">unique</span>(<span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">st_coordinates</span>(atlas_sf)[, <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"Y"</span>]))</span>
<span id="cb31-3">inner_x <span class="ot" style="color: #003B4F;
background-color: null;
font-style: inherit;">&lt;-</span> line_x[<span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">-</span><span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">c</span>(<span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">1</span>, <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">length</span>(line_x))]; inner_y <span class="ot" style="color: #003B4F;
background-color: null;
font-style: inherit;">&lt;-</span> line_y[<span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">-</span><span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">c</span>(<span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">1</span>, <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">length</span>(line_y))]</span>
<span id="cb31-4">touch_x <span class="ot" style="color: #003B4F;
background-color: null;
font-style: inherit;">&lt;-</span> <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">1</span> <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">+</span> records<span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">$</span>lon <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">%in%</span> inner_x</span>
<span id="cb31-5">touch_y <span class="ot" style="color: #003B4F;
background-color: null;
font-style: inherit;">&lt;-</span> <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">1</span> <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">+</span> records<span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">$</span>lat <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">%in%</span> inner_y</span>
<span id="cb31-6"><span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">stopifnot</span>(<span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">all</span>(cells_hit <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">==</span> touch_x <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">*</span> touch_y), <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">sum</span>(cells_hit) <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">==</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">nrow</span>(joined),</span>
<span id="cb31-7">          <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">all</span>(records<span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">$</span>lat <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">%in%</span> line_y), <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">all</span>(within_n <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">==</span> <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">0</span>))   <span class="co" style="color: #5E5E5E;
background-color: null;
font-style: inherit;"># all on a latitude line; none within</span></span>
<span id="cb31-8">off_lines <span class="ot" style="color: #003B4F;
background-color: null;
font-style: inherit;">&lt;-</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">c</span>(line_x[<span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">!</span>(line_x <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">%in%</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">c</span>(lon_values, <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">30</span>))], line_y[<span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">!</span>(line_y <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">%in%</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">c</span>(lat_values, <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">48</span>))])</span>
<span id="cb31-9">off_lines                                     <span class="co" style="color: #5E5E5E;
background-color: null;
font-style: inherit;"># grid lines that are not a typed value</span></span></code></pre></div></div>
<div class="cell-output cell-output-stdout">
<pre><code>[1] 28.2 28.7 29.2 29.7</code></pre>
</div>
</div>
<p>The 20000 records become 76971 rows after the join. 92.5 per cent of the records intersect four cells, 7.4 per cent two and 0.1 per cent one (sf 1.1-3). The <code>stopifnot()</code> line checks where each extra row comes from: the number of cells a record touches is the number of cells across its longitude line times the number across its latitude line, which is 2 by 2 on an inner corner, 2 by 1 on the outer edge of the atlas or on one of the lines described next, and 1 by 1 where two such single-sided lines meet (the south-west corner, or one of those lines at 44 north). Of the 142 grid lines that sf computes, 4, at 28.2, 28.7, 29.2, 29.7 degrees, are not the number the typed coordinate parses to (this version places line i at the origin plus i times 0.1, and for these lines that sum lands one binary step away from the typed value), so records on them touch only the cell on one side of the line. Every duplicated row is a boundary tie, and a richness count per cell built on the join counts each corner record in four cells. Changing the predicate to <code>st_within</code> does not help. None of the 20000 records lies within any cell, because every one of them is on a latitude line: in the geometry sf follows, a point on a polygon’s boundary is not within it, so a left join with <code>join = st_within</code> keeps every record and gives none of them a cell.</p>
<div class="cell">
<div class="cell-output-display">
<div id="fig-corner" class="quarto-float quarto-figure quarto-figure-center anchored" alt="A patch of the sf grid from 28.0 to 28.4 degrees east and 45.1 to 45.3 degrees north, with dark grid lines every 0.1 degree and a point on each of the 15 line crossings, each labelled with the number of cells it intersects. The points at 28.0, 28.1, 28.3 and 28.4 east are dark green and labelled 4; the three points at 28.2 east are rust and labelled 2.">
<figure class="quarto-float quarto-float-fig figure">
<div aria-describedby="fig-corner-caption-0ceaefa1-69ba-4598-a22c-09a6ac19f8ca">
<img src="https://tidyecology.com/posts/records-on-grid-lines-and-floating-point/index_files/figure-html/fig-corner-1.png" class="img-fluid figure-img" alt="A patch of the sf grid from 28.0 to 28.4 degrees east and 45.1 to 45.3 degrees north, with dark grid lines every 0.1 degree and a point on each of the 15 line crossings, each labelled with the number of cells it intersects. The points at 28.0, 28.1, 28.3 and 28.4 east are dark green and labelled 4; the three points at 28.2 east are rust and labelled 2." width="720">
</div>
<figcaption class="quarto-float-caption-bottom quarto-float-caption quarto-float-fig" id="fig-corner-caption-0ceaefa1-69ba-4598-a22c-09a6ac19f8ca">
Figure&nbsp;3: A small part of the sf atlas grid around 28 degrees east. Each point is a one-decimal record on a cell corner, labelled with the number of grid cells it intersects. Where the grid line sf computes is not the number the typed longitude parses to, the records on it touch two cells, not four.
</figcaption>
</figure>
</div>
</div>
</div>
</section>
<section id="the-fix-choose-the-rule-then-count-in-whole-numbers" class="level2">
<h2 id="the-fix-choose-the-rule-then-count-in-whole-numbers-h" class="anchored" data-anchor-id="the-fix-choose-the-rule-then-count-in-whole-numbers">The fix: choose the rule, then count in whole numbers</h2>
<p>The fix has two parts, and the order matters. First write the edge rule down, in the methods and in the code: here a cell owns its western and southern edges. Then do the arithmetic in integers, where a tie is a tie. <code>round()</code> turns a coordinate into a whole number of small units without any doubt, because the stored number is within a tiny fraction of that whole number; integer division by the cell size in the same units then gives the index. Micro-degrees serve any record with up to six decimals (the chunk checks a sample of one hundred thousand six-decimal values between 20 and 30). They assume the numbers came from text or double-precision storage; if a coordinate may have passed through single precision (some databases and grid formats), round to the precision of the record itself, <code>round(lon * 10)</code> for tenths, instead.</p>
<div class="cell">
<div class="code-copy-outer-scaffold"><div class="sourceCode cell-code" id="cb33" style="background: #f1f3f5;"><pre class="sourceCode r code-with-copy"><code class="sourceCode r"><span id="cb33-1">cell_index <span class="ot" style="color: #003B4F;
background-color: null;
font-style: inherit;">&lt;-</span> <span class="cf" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">function</span>(coord, origin, cell_size) {</span>
<span id="cb33-2">  micro <span class="ot" style="color: #003B4F;
background-color: null;
font-style: inherit;">&lt;-</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">round</span>(coord <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">*</span> <span class="fl" style="color: #AD0000;
background-color: null;
font-style: inherit;">1e6</span>) <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">-</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">round</span>(origin <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">*</span> <span class="fl" style="color: #AD0000;
background-color: null;
font-style: inherit;">1e6</span>)    <span class="co" style="color: #5E5E5E;
background-color: null;
font-style: inherit;"># whole micro-degrees</span></span>
<span id="cb33-3">  micro <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">%/%</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">round</span>(cell_size <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">*</span> <span class="fl" style="color: #AD0000;
background-color: null;
font-style: inherit;">1e6</span>)</span>
<span id="cb33-4">}</span>
<span id="cb33-5"><span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">stopifnot</span>(<span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">identical</span>(<span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">cell_index</span>(cols<span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">$</span>lon, <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">20</span>, <span class="fl" style="color: #AD0000;
background-color: null;
font-style: inherit;">0.1</span>), cols<span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">$</span>intended),</span>
<span id="cb33-6">          <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">identical</span>(<span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">cell_index</span>(records<span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">$</span>lon, <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">20</span>, <span class="fl" style="color: #AD0000;
background-color: null;
font-style: inherit;">0.1</span>), col_rule),</span>
<span id="cb33-7">          <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">identical</span>(<span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">cell_index</span>(records<span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">$</span>lat, <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">44</span>, <span class="fl" style="color: #AD0000;
background-color: null;
font-style: inherit;">0.1</span>), row_rule))</span>
<span id="cb33-8">two_dec <span class="ot" style="color: #003B4F;
background-color: null;
font-style: inherit;">&lt;-</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">as.numeric</span>(<span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">sprintf</span>(<span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"%.2f"</span>, <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">2000</span><span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">:</span><span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">2999</span> <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">/</span> <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">100</span>))</span>
<span id="cb33-9"><span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">stopifnot</span>(<span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">all</span>(<span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">cell_index</span>(two_dec, <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">20</span>, <span class="fl" style="color: #AD0000;
background-color: null;
font-style: inherit;">0.05</span>) <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">==</span> (<span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">0</span><span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">:</span><span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">999</span>) <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">%/%</span> <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">5</span>),</span>
<span id="cb33-10">          <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">all</span>(<span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">cell_index</span>(two_dec, <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">20</span>, <span class="fl" style="color: #AD0000;
background-color: null;
font-style: inherit;">0.01</span>) <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">==</span> <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">0</span><span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">:</span><span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">999</span>))</span>
<span id="cb33-11">fix_ok <span class="ot" style="color: #003B4F;
background-color: null;
font-style: inherit;">&lt;-</span> <span class="cf" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">function</span>(origin, cell_units, dec, <span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">span =</span> <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">10</span>) {     <span class="co" style="color: #5E5E5E;
background-color: null;
font-style: inherit;"># the rows of the grids table</span></span>
<span id="cb33-12">  k <span class="ot" style="color: #003B4F;
background-color: null;
font-style: inherit;">&lt;-</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">round</span>(origin <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">*</span> <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">10</span><span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">^</span>dec) <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">+</span> <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">0</span><span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">:</span>(span <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">*</span> <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">10</span><span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">^</span>dec <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">-</span> <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">1</span>)</span>
<span id="cb33-13">  v <span class="ot" style="color: #003B4F;
background-color: null;
font-style: inherit;">&lt;-</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">as.numeric</span>(<span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">sprintf</span>(<span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">paste0</span>(<span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"%."</span>, dec, <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"f"</span>), k <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">/</span> <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">10</span><span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">^</span>dec))</span>
<span id="cb33-14">  <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">all</span>(<span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">cell_index</span>(v, origin, cell_units <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">/</span> <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">10</span><span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">^</span>dec) <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">==</span> (k <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">-</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">round</span>(origin <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">*</span> <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">10</span><span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">^</span>dec)) <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">%/%</span> cell_units)</span>
<span id="cb33-15">}</span>
<span id="cb33-16"><span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">stopifnot</span>(<span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">fix_ok</span>(<span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">16</span>, <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">1</span>, <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">1</span>), <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">fix_ok</span>(<span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">44</span>, <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">1</span>, <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">1</span>, <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">4</span>), <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">fix_ok</span>(<span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">20</span>, <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">5</span>, <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">1</span>), <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">fix_ok</span>(<span class="fl" style="color: #AD0000;
background-color: null;
font-style: inherit;">15.9</span>, <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">5</span>, <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">1</span>),</span>
<span id="cb33-17">          <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">fix_ok</span>(<span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">20</span>, <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">10</span>, <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">2</span>), <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">fix_ok</span>(<span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">20</span>, <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">25</span>, <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">2</span>))</span>
<span id="cb33-18">lon_single <span class="ot" style="color: #003B4F;
background-color: null;
font-style: inherit;">&lt;-</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">readBin</span>(<span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">writeBin</span>(lon_values, <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">raw</span>(), <span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">size =</span> <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">4</span>), <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"numeric"</span>, <span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">n =</span> <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">100</span>, <span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">size =</span> <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">4</span>)</span>
<span id="cb33-19"><span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">stopifnot</span>(<span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">identical</span>(<span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">round</span>(lon_single <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">*</span> <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">10</span>) <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">-</span> <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">200</span>, cols<span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">$</span>intended))   <span class="co" style="color: #5E5E5E;
background-color: null;
font-style: inherit;"># single precision: round to tenths</span></span>
<span id="cb33-20">micro_k <span class="ot" style="color: #003B4F;
background-color: null;
font-style: inherit;">&lt;-</span> <span class="fl" style="color: #AD0000;
background-color: null;
font-style: inherit;">20e6</span> <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">-</span> <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">1</span> <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">+</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">sample.int</span>(<span class="fl" style="color: #AD0000;
background-color: null;
font-style: inherit;">10e6</span>, <span class="fl" style="color: #AD0000;
background-color: null;
font-style: inherit;">1e5</span>)                       <span class="co" style="color: #5E5E5E;
background-color: null;
font-style: inherit;"># six-decimal values, a sample</span></span>
<span id="cb33-21"><span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">stopifnot</span>(<span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">all</span>(<span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">round</span>(<span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">as.numeric</span>(<span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">sprintf</span>(<span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"%.6f"</span>, micro_k <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">/</span> <span class="fl" style="color: #AD0000;
background-color: null;
font-style: inherit;">1e6</span>)) <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">*</span> <span class="fl" style="color: #AD0000;
background-color: null;
font-style: inherit;">1e6</span>) <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">==</span> micro_k))</span>
<span id="cb33-22"><span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">stopifnot</span>(<span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">all</span>(<span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">floor</span>((<span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">0</span><span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">:</span><span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">10000</span>) <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">/</span> <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">5</span>) <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">==</span> (<span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">0</span><span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">:</span><span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">10000</span>) <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">%/%</span> <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">5</span>))      <span class="co" style="color: #5E5E5E;
background-color: null;
font-style: inherit;"># whole metres, 5 m cells</span></span>
<span id="cb33-23"><span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">c</span>(<span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">one_decimal_floor_times_10_wrong =</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">sum</span>(<span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">floor</span>(lon_values <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">*</span> <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">10</span>) <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">-</span> <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">200</span> <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">!=</span> cols<span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">$</span>intended),</span>
<span id="cb33-24">  <span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">two_decimal_floor_times_100_wrong =</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">sum</span>(<span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">floor</span>(two_dec <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">*</span> <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">100</span>) <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">!=</span> <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">2000</span><span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">:</span><span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">2999</span>))</span></code></pre></div></div>
<div class="cell-output cell-output-stdout">
<pre><code> one_decimal_floor_times_10_wrong two_decimal_floor_times_100_wrong 
                                0                                 7 </code></pre>
</div>
<div class="code-copy-outer-scaffold"><div class="sourceCode cell-code" id="cb35" style="background: #f1f3f5;"><pre class="sourceCode r code-with-copy"><code class="sourceCode r"><span id="cb35-1">centre_lon <span class="ot" style="color: #003B4F;
background-color: null;
font-style: inherit;">&lt;-</span> x0 <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">+</span> (col_rule <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">+</span> <span class="fl" style="color: #AD0000;
background-color: null;
font-style: inherit;">0.5</span>) <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">*</span> cell            <span class="co" style="color: #5E5E5E;
background-color: null;
font-style: inherit;"># the cell centre, from the index</span></span>
<span id="cb35-2">centre_lat <span class="ot" style="color: #003B4F;
background-color: null;
font-style: inherit;">&lt;-</span> y0 <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">+</span> (row_rule <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">+</span> <span class="fl" style="color: #AD0000;
background-color: null;
font-style: inherit;">0.5</span>) <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">*</span> cell</span>
<span id="cb35-3">cell_from_centre <span class="ot" style="color: #003B4F;
background-color: null;
font-style: inherit;">&lt;-</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">cellFromXY</span>(atlas_r, <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">cbind</span>(centre_lon, centre_lat))</span>
<span id="cb35-4">centre_sf <span class="ot" style="color: #003B4F;
background-color: null;
font-style: inherit;">&lt;-</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">st_as_sf</span>(<span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">data.frame</span>(<span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">lon =</span> centre_lon, <span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">lat =</span> centre_lat),</span>
<span id="cb35-5">                      <span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">coords =</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">c</span>(<span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"lon"</span>, <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"lat"</span>), <span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">crs =</span> <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">4326</span>)</span>
<span id="cb35-6">hits_centre <span class="ot" style="color: #003B4F;
background-color: null;
font-style: inherit;">&lt;-</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">lengths</span>(<span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">suppressMessages</span>(<span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">st_intersects</span>(centre_sf, atlas_sf)))</span>
<span id="cb35-7"><span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">stopifnot</span>(<span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">all</span>(<span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">colFromCell</span>(atlas_r, cell_from_centre) <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">-</span> <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">1</span> <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">==</span> col_rule),</span>
<span id="cb35-8">          <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">all</span>(<span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">40</span> <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">-</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">rowFromCell</span>(atlas_r, cell_from_centre) <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">==</span> row_rule),</span>
<span id="cb35-9">          <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">all</span>(hits_centre <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">==</span> <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">1</span>))</span>
<span id="cb35-10"><span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">c</span>(<span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">records =</span> n_rec, <span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">sf_rows_after_join =</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">nrow</span>(<span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">suppressMessages</span>(<span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">st_join</span>(centre_sf, atlas_sf))))</span></code></pre></div></div>
<div class="cell-output cell-output-stdout">
<pre><code>           records sf_rows_after_join 
             20000              20000 </code></pre>
</div>
</div>
<p>The integer index agrees with the edge rule for every value in every enumeration above, including the 15.9 origin and the 0.05 and 0.01 degree cells on two-decimal records, and the <code>stopifnot()</code> lines make the page fail to build if it ever does not. Multiplying the raw longitude by a power of ten before anything else and rounding down happens to work for the one-decimal longitudes of this atlas (<code>floor(lon * 10)</code> misplaces 0 of the 100), but it is not a method: <code>floor(lon * 100)</code> on the thousand two-decimal longitudes from 20.00 to 29.99 gets 7 of them wrong. The step that makes the fix safe is <code>round()</code> to the unit, then integer arithmetic.</p>
<p>When the gridding has to happen in terra or sf, pass the cell centre computed from the integer index, not the record. A centre lies half a cell from every line, far beyond any rounding, so <code>cellFromXY()</code> returns the rule’s cell for all 20000 records and <code>st_join()</code> returns exactly one row per record. Keep the original coordinates in their own columns for everything else.</p>
</section>
<section id="what-to-check-in-your-own-data" class="level2">
<h2 id="what-to-check-in-your-own-data-h" class="anchored" data-anchor-id="what-to-check-in-your-own-data">What to check in your own data</h2>
<p>Count the records that sit on a line before you grid: with the coordinate in whole units of its last decimal, a record is on a line when that number is divisible by the cell size in the same units. If the count is zero, the question does not arise; each extra decimal place divides the share on a line by ten. The edge rule also needs an answer at the eastern and northern boundary: a record on 30.0 east gets column 100, outside the atlas. Decide whether such records are dropped or kept in the last column, and check <code>all(col &gt;= 0 &amp; col &lt; 100)</code> before you tabulate. After a spatial join to a grid, compare the number of rows with the number of records. More rows means boundary ties; fewer non-missing cells than records, with <code>st_within</code>, means the same ties seen from the other side. Compute the cell index two ways, your production route and the integer rule, and count the disagreements. On a fresh extent or a new package version this takes one line and replaces any assumption about what a function does on an edge. In the methods, state the edge rule and how many records it decided. A reader cannot recover either from the map.</p>
</section>
<section id="honest-limits" class="level2">
<h2 id="honest-limits-h" class="anchored" data-anchor-id="honest-limits">Honest limits</h2>
<p>The counts in this post belong to one atlas: origin 20 and 44 degrees, 0.1 degree cells, one- and two-decimal records. Other origins, resolutions and magnitudes give other counts, as the table shows, and the only general statements are the two the table supports: only values on a line are at risk, and a cell size and origin that are both exact in binary (0.5 or 0.25 degree cells starting on a whole degree) are safe for decimal records; the same 0.5 degree cells starting at 15.9 are not.</p>
<p>An edge rule makes the assignment reproducible; it does not make it true. A coordinate given to one decimal place stands for a square about 0.1 degree across (Wieczorek and colleagues 2004 treat such coordinates as an uncertainty, not a point), and if it was rounded rather than truncated the plant could be on either side of the line. No rule places such a record correctly. When most records are that coarse, an atlas at the same resolution is mapping the recording precision as much as the plant, and a coarser atlas or an analysis that carries the uncertainty is the honest choice.</p>
<p>The terra and sf numbers are for terra 1.9-50 and sf 1.1-3 with spherical geometry switched off, and the prose above is computed from whatever versions build the page. With spherical geometry on, sf hands the geometry to the s2 library instead; that case was not measured. Whole numbers are exact in binary, so whole-metre coordinates on a grid of whole-metre cells from a whole-metre origin are placed exactly by <code>floor()</code>, ties included (the whole-metre check in the fix chunk), and continuous coordinates such as those in <a href="https://tidyecology.com/posts/snapped-coordinates-and-clustering/">Snapped coordinates and a clustering verdict</a> almost never lie on a line at all.</p>
</section>
<section id="references" class="level2">
<h2 id="references-h" class="anchored" data-anchor-id="references">References</h2>
<p>Goldberg D 1991 ACM Computing Surveys 23(1):5-48 (<a href="https://doi.org/10.1145/103162.103163">10.1145/103162.103163</a>)</p>
<p>Hijmans RJ 2026 terra: Spatial Data Analysis. R package version 1.9-50, the version that built this page (https://CRAN.R-project.org/package=terra)</p>
<p>Hornik K, R Core Team 2023 The R FAQ, question 7.31 (https://CRAN.R-project.org/doc/FAQ/R-FAQ.html)</p>
<p>Pebesma E 2018 The R Journal 10(1):439-446 (<a href="https://doi.org/10.32614/RJ-2018-009">10.32614/RJ-2018-009</a>)</p>
<p>Wieczorek J, Guo Q, Hijmans RJ 2004 International Journal of Geographical Information Science 18(8):745-767 (<a href="https://doi.org/10.1080/13658810412331280211">10.1080/13658810412331280211</a>)</p>
</section>
<section id="related-tutorials" class="level2">
<h2 id="related-tutorials-h" class="anchored" data-anchor-id="related-tutorials">Related tutorials</h2>
<ul>
<li><a href="https://tidyecology.com/posts/richness-mapping-sf/">Mapping species richness in R with sf</a></li>
<li><a href="https://tidyecology.com/posts/pinning-package-versions-with-renv/">Pinning package versions with renv</a></li>
<li><a href="https://tidyecology.com/posts/snapped-coordinates-and-clustering/">Snapped coordinates and a clustering verdict</a></li>
<li><a href="https://tidyecology.com/posts/checking-an-analysis-script/">Checking an analysis script</a></li>
</ul>
<details class="te-repro" data-pagefind-ignore="">
<summary>Reproducibility</summary>
<ul>
<li>Code last run: 2026-10-15</li>
<li>R version 4.5.3 (2026-03-11), aarch64-apple-darwin20</li>
<li>Packages: ggplot2 4.0.3, sf 1.1-3, terra 1.9-50</li>
</ul>
</details>


<!-- -->

</section>

 ]]></description>
  <category>R</category>
  <category>GIS</category>
  <category>terra</category>
  <category>sf</category>
  <category>occurrence data</category>
  <category>data cleaning</category>
  <category>ecology tutorial</category>
  <guid isPermaLink="false">https://tidyecology.com/posts/records-on-grid-lines-and-floating-point/</guid>
  <pubDate>Mon, 28 Sep 2026 11:00:00 GMT</pubDate>
  <media:content url="https://tidyecology.com/posts/records-on-grid-lines-and-floating-point/thumbnail.png" medium="image" type="image/png" height="104" width="144"/>
</item>
<item>
  <title>When integrate() in R returns zero and says OK</title>
  <dc:creator>Tidy Ecology</dc:creator>
  <link>https://tidyecology.com/posts/when-integrate-returns-zero/</link>
  <description><![CDATA[ 





<p><em>Corrected 7 October 2026: the post said the example call on the help page fails as soon as the mean moves, but at the help page’s standard deviation it returns the right answer until the mean is well away from zero, and it now says the call fails once the mean sits far enough from zero for the width of the density. It also quoted words that the post on coordinate error and habitat assignment no longer contains, and now says in its own words what that post warns.</em></p>
<p><em>Corrected 1 October 2026: the post put the gap between the standardised and integrand-centred log-likelihoods down to the population-centred substitution itself; it now puts it down to the default tolerance of <code>integrate()</code>. The count of earlier posts that call <code>integrate()</code> and the furthest-out integrand among them are corrected too.</em></p>
<p>A fisheries student is fitting length at maturity. Each fish was measured with callipers to within a few millimetres, the lengths sit around 420 mm, and the model is a logistic regression of maturity on true length, not on the recorded one, because the student has read that measurement error in a predictor drags a slope towards zero. The honest likelihood for one fish integrates over the length it might really have had, and the student writes that integral the way the help page writes it: <code>integrate(f, -Inf, Inf)</code>. The fit runs, <code>optim()</code> reports convergence code 0, and the slope comes out with a sign nobody expected. Nothing printed a warning, and <code>integrate()</code> reported no trouble with any of the integrals behind that fit.</p>
<p>The mechanism is not new and this post claims no discovery. R’s <code>integrate()</code> is built on the QUADPACK routines of Piessens and colleagues, and for an infinite range it uses the <code>dqagi</code> transformation, which maps the whole real line onto a finite interval and then applies an adaptive Gauss-Kronrod rule there. The rule looks first where the transformed variable puts its points, and those points crowd around the origin of the original scale. A density that is narrow and sits far from zero can fall between them. The help page says as much in its Note, in general terms. What is measured here is how often that happens on the (mean, width) pairs an ecologist actually meets, what it does to a real likelihood fit, and which repair survives.</p>
<p>The tree already has dozens of posts that call <code>integrate()</code>. Every one of them uses it, none shows it failing, and the calls with an infinite limit are all on integrands that are standardised, have their mass at zero, or are wide enough near the origin for the first probes to land on them: the half-normal detection function in <a href="https://tidyecology.com/posts/call-rates-and-acoustic-density/">call rates and density from acoustic surveys</a>, the expected maximum of standard normals in <a href="https://tidyecology.com/posts/sap-flow-and-the-zero-flow-baseline/">the sap flow baseline post</a>. Chi-square densities with tens of degrees of freedom, in <a href="https://tidyecology.com/posts/home-away-and-local-foreign/">home vs away and local vs foreign</a> and <a href="https://tidyecology.com/posts/lasso-drops-the-confounder/">lasso, stepwise and the dropped confounder</a>, are the furthest out, and both integrate correctly. The site is safe by accident rather than by argument, and this post is the argument.</p>
<p>The nearest posts on the site are about computation choices too, and the difference matters. <a href="https://tidyecology.com/posts/ipm-eviction-and-mesh/">Eviction and mesh size in an IPM</a> shows a midpoint rule under-resolving a narrow kernel, but the mesh is a number the analyst typed and the loss shows up in the kernel for anyone who plots it. <a href="https://tidyecology.com/posts/cyclic-splines-for-seasonal-data/">Harmonics or cyclic splines for a narrow seasonal peak</a> turns on REML against UBRE as a smoothing criterion, <a href="https://tidyecology.com/posts/synthetic-likelihood-for-chaotic-dynamics/">synthetic likelihood for noisy population dynamics</a> on how many simulations to spend per evaluation, and <a href="https://tidyecology.com/posts/fat-tails-and-accelerating-spread/">fat tails and accelerating spread</a> on grid width, zero padding and a declared floor. All of those are choices the analyst declared and can see in their own code; this one is an undeclared default inside a base R function, the analyst declared nothing, and the loss is printed as “OK”. <a href="https://tidyecology.com/posts/coordinate-error-and-habitat-assignment/">Coordinate error and habitat assignment</a> warns that nothing bounds the error of a fixed grid of quadrature nodes when the integrand is an indicator, discontinuous at every patch edge, which is the opposite problem: here the integrand is as smooth as a function can be. <a href="https://tidyecology.com/posts/parameter-scale-and-what-optim-finds/">Parameter scale decides what optim() finds</a> is the closest case of all, an optimiser misled by the scale of its parameters, and it is not what happens here: both routes below move the same intercept and slope, on the same scale, from the same start, and what differs is the objective itself, which the diagnostic section recomputes.</p>
<p><a href="https://tidyecology.com/posts/the-laplace-approximation/">The Laplace approximation in R</a> checks a finite-difference Hessian against the analytic one, finds them in agreement, and concludes that the numerical route is fine for a model whose derivatives you cannot face writing out. The habit that post teaches, checking the numerical answer against an exact one, is the habit that catches what follows. <a href="https://tidyecology.com/posts/measurement-error-regression-dilution/">Measurement error and regression dilution</a> and <a href="https://tidyecology.com/posts/simex-measurement-error-correction/">correcting measurement error with SIMEX</a> are about what error in a predictor does to a slope and how to undo it. Those posts own the estimand this fit is trying to recover; this one is about the computation of that fit, and it is not a new correction.</p>
<div class="cell">
<div class="code-copy-outer-scaffold"><div class="sourceCode cell-code" id="cb1" style="background: #f1f3f5;"><pre class="sourceCode r code-with-copy"><code class="sourceCode r"><span id="cb1-1"><span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">library</span>(ggplot2)</span>
<span id="cb1-2"></span>
<span id="cb1-3">te_paper  <span class="ot" style="color: #003B4F;
background-color: null;
font-style: inherit;">&lt;-</span> <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"#f5f4ee"</span></span>
<span id="cb1-4">te_ink    <span class="ot" style="color: #003B4F;
background-color: null;
font-style: inherit;">&lt;-</span> <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"#16241d"</span></span>
<span id="cb1-5">te_body   <span class="ot" style="color: #003B4F;
background-color: null;
font-style: inherit;">&lt;-</span> <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"#2c3a31"</span></span>
<span id="cb1-6">te_forest <span class="ot" style="color: #003B4F;
background-color: null;
font-style: inherit;">&lt;-</span> <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"#275139"</span></span>
<span id="cb1-7">te_rust   <span class="ot" style="color: #003B4F;
background-color: null;
font-style: inherit;">&lt;-</span> <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"#b5534e"</span></span>
<span id="cb1-8">te_gold   <span class="ot" style="color: #003B4F;
background-color: null;
font-style: inherit;">&lt;-</span> <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"#c9b458"</span></span>
<span id="cb1-9">te_line   <span class="ot" style="color: #003B4F;
background-color: null;
font-style: inherit;">&lt;-</span> <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"#dad9ca"</span></span>
<span id="cb1-10"></span>
<span id="cb1-11">theme_datasheet <span class="ot" style="color: #003B4F;
background-color: null;
font-style: inherit;">&lt;-</span> <span class="cf" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">function</span>() {</span>
<span id="cb1-12">  <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">theme_minimal</span>(<span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">base_size =</span> <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">12</span>) <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">+</span></span>
<span id="cb1-13">    <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">theme</span>(<span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">plot.background  =</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">element_rect</span>(<span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">fill =</span> te_paper, <span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">colour =</span> <span class="cn" style="color: #8f5902;
background-color: null;
font-style: inherit;">NA</span>),</span>
<span id="cb1-14">          <span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">panel.background =</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">element_rect</span>(<span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">fill =</span> te_paper, <span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">colour =</span> <span class="cn" style="color: #8f5902;
background-color: null;
font-style: inherit;">NA</span>),</span>
<span id="cb1-15">          <span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">panel.grid.major =</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">element_line</span>(<span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">colour =</span> te_line, <span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">linewidth =</span> <span class="fl" style="color: #AD0000;
background-color: null;
font-style: inherit;">0.3</span>),</span>
<span id="cb1-16">          <span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">panel.grid.minor =</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">element_blank</span>(),</span>
<span id="cb1-17">          <span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">text             =</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">element_text</span>(<span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">colour =</span> te_body),</span>
<span id="cb1-18">          <span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">plot.title       =</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">element_text</span>(<span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">colour =</span> te_ink, <span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">face =</span> <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"bold"</span>),</span>
<span id="cb1-19">          <span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">plot.subtitle    =</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">element_text</span>(<span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">colour =</span> te_body),</span>
<span id="cb1-20">          <span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">axis.text        =</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">element_text</span>(<span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">colour =</span> te_body))</span>
<span id="cb1-21">}</span>
<span id="cb1-22"></span>
<span id="cb1-23">fmt_e <span class="ot" style="color: #003B4F;
background-color: null;
font-style: inherit;">&lt;-</span> <span class="cf" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">function</span>(x) <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">formatC</span>(x, <span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">format =</span> <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"e"</span>, <span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">digits =</span> <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">2</span>)</span></code></pre></div></div>
</div>
<section id="where-integrate-looks" class="level2">
<h2 id="where-integrate-looks-h" class="anchored" data-anchor-id="where-integrate-looks">Where integrate() looks</h2>
<p>The quickest way to see the problem is to ask <code>integrate()</code> where it evaluated the function. The wrapper below records every point it was handed, for three normal densities: the standard normal from the help page, a density with mean 20 and standard deviation 1, and one with mean 420 and standard deviation 15, which is the true length distribution of the fish above.</p>
<div class="cell">
<div class="code-copy-outer-scaffold"><div class="sourceCode cell-code" id="cb2" style="background: #f1f3f5;"><pre class="sourceCode r code-with-copy"><code class="sourceCode r"><span id="cb2-1">probe_call <span class="ot" style="color: #003B4F;
background-color: null;
font-style: inherit;">&lt;-</span> <span class="cf" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">function</span>(mu, s) {</span>
<span id="cb2-2">  seen <span class="ot" style="color: #003B4F;
background-color: null;
font-style: inherit;">&lt;-</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">numeric</span>(<span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">0</span>)</span>
<span id="cb2-3">  res  <span class="ot" style="color: #003B4F;
background-color: null;
font-style: inherit;">&lt;-</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">integrate</span>(<span class="cf" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">function</span>(x) {</span>
<span id="cb2-4">    seen <span class="ot" style="color: #003B4F;
background-color: null;
font-style: inherit;">&lt;&lt;-</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">c</span>(seen, x)</span>
<span id="cb2-5">    <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">dnorm</span>(x, mu, s)</span>
<span id="cb2-6">  }, <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">-</span><span class="cn" style="color: #8f5902;
background-color: null;
font-style: inherit;">Inf</span>, <span class="cn" style="color: #8f5902;
background-color: null;
font-style: inherit;">Inf</span>, <span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">stop.on.error =</span> <span class="cn" style="color: #8f5902;
background-color: null;
font-style: inherit;">FALSE</span>)</span>
<span id="cb2-7">  <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">list</span>(<span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">res =</span> res, <span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">pts =</span> seen)</span>
<span id="cb2-8">}</span>
<span id="cb2-9"></span>
<span id="cb2-10">probe_mu <span class="ot" style="color: #003B4F;
background-color: null;
font-style: inherit;">&lt;-</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">c</span>(<span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">0</span>, <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">20</span>, <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">420</span>)</span>
<span id="cb2-11">probe_sd <span class="ot" style="color: #003B4F;
background-color: null;
font-style: inherit;">&lt;-</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">c</span>(<span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">1</span>, <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">1</span>, <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">15</span>)</span>
<span id="cb2-12">probe_out <span class="ot" style="color: #003B4F;
background-color: null;
font-style: inherit;">&lt;-</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">Map</span>(probe_call, probe_mu, probe_sd)</span>
<span id="cb2-13"></span>
<span id="cb2-14">probe_val  <span class="ot" style="color: #003B4F;
background-color: null;
font-style: inherit;">&lt;-</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">vapply</span>(probe_out, <span class="cf" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">function</span>(p) p<span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">$</span>res<span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">$</span>value, <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">0</span>)</span>
<span id="cb2-15">probe_msg  <span class="ot" style="color: #003B4F;
background-color: null;
font-style: inherit;">&lt;-</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">vapply</span>(probe_out, <span class="cf" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">function</span>(p) p<span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">$</span>res<span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">$</span>message, <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">""</span>)</span>
<span id="cb2-16">probe_err  <span class="ot" style="color: #003B4F;
background-color: null;
font-style: inherit;">&lt;-</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">vapply</span>(probe_out, <span class="cf" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">function</span>(p) p<span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">$</span>res<span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">$</span>abs.error, <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">0</span>)</span>
<span id="cb2-17">probe_n    <span class="ot" style="color: #003B4F;
background-color: null;
font-style: inherit;">&lt;-</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">vapply</span>(probe_out, <span class="cf" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">function</span>(p) <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">length</span>(p<span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">$</span>pts), <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">0</span>)</span>
<span id="cb2-18"></span>
<span id="cb2-19">pts_far    <span class="ot" style="color: #003B4F;
background-color: null;
font-style: inherit;">&lt;-</span> probe_out[[<span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">3</span>]]<span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">$</span>pts</span>
<span id="cb2-20">n_near0    <span class="ot" style="color: #003B4F;
background-color: null;
font-style: inherit;">&lt;-</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">sum</span>(<span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">abs</span>(pts_far) <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">&lt;</span> <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">10</span>)</span>
<span id="cb2-21">far_below  <span class="ot" style="color: #003B4F;
background-color: null;
font-style: inherit;">&lt;-</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">max</span>(<span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">abs</span>(pts_far)[<span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">abs</span>(pts_far) <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">&lt;</span> <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">420</span>])</span>
<span id="cb2-22">far_above  <span class="ot" style="color: #003B4F;
background-color: null;
font-style: inherit;">&lt;-</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">min</span>(<span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">abs</span>(pts_far)[<span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">abs</span>(pts_far) <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">&gt;</span> <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">420</span>])</span>
<span id="cb2-23">seen_max   <span class="ot" style="color: #003B4F;
background-color: null;
font-style: inherit;">&lt;-</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">max</span>(<span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">dnorm</span>(pts_far, <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">420</span>, <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">15</span>))</span>
<span id="cb2-24">peak_far   <span class="ot" style="color: #003B4F;
background-color: null;
font-style: inherit;">&lt;-</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">dnorm</span>(<span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">420</span>, <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">420</span>, <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">15</span>)</span>
<span id="cb2-25">seen_ratio <span class="ot" style="color: #003B4F;
background-color: null;
font-style: inherit;">&lt;-</span> seen_max <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">/</span> peak_far</span></code></pre></div></div>
</div>
<p>For the standard normal the call returns 1.000000 with message <code>"OK"</code>. For the mean of 20 it returns <img src="https://latex.codecogs.com/png.latex?7.94%20%5Ctimes%2010%5E%7B-7%7D">, and for the fish lengths it returns <img src="https://latex.codecogs.com/png.latex?3.55%20%5Ctimes%2010%5E%7B-67%7D"> with a reported absolute error of 0. All three messages read <code>"OK"</code> (<code>all(probe_msg == "OK")</code> returns TRUE). The calls were made with <code>stop.on.error = FALSE</code>. With the default, any failure the routine detects is raised as an error, so a value that comes back at all says OK; switching it off is what makes the message worth reading. The true answer is 1 in all three cases.</p>
<p>The fish-length call evaluated the density at 150 points. Of those, 124 lie within 10 mm of zero, a length no fish in the sample could have. The two probes nearest the mass sit at 233 mm and 467 mm, either side of a density whose mass lies within a few tens of millimetres of 420. The largest density value any probe saw was <img src="https://latex.codecogs.com/png.latex?1.91%20%5Ctimes%2010%5E%7B-4%7D">, which is 0.0072 of the peak.</p>
<p>Where those two probes came from explains the “OK”. QUADPACK integrates each piece of the transformed interval twice, with a 15-point Kronrod rule and with the 7-point Gauss rule whose points are a subset of it, and builds its error estimate from the gap between the two. The chunk below recomputes both rules by hand on the pieces the routine used, with the transformation x = (1 - t) / t that <code>dqagi</code> applies to both signs of x.</p>
<div class="cell">
<div class="code-copy-outer-scaffold"><div class="sourceCode cell-code" id="cb3" style="background: #f1f3f5;"><pre class="sourceCode r code-with-copy"><code class="sourceCode r"><span id="cb3-1"><span class="co" style="color: #5E5E5E;
background-color: null;
font-style: inherit;"># nodes and weights of QUADPACK's 15-point Kronrod rule (half of the</span></span>
<span id="cb3-2"><span class="co" style="color: #5E5E5E;
background-color: null;
font-style: inherit;"># symmetric set) and of the 7-point Gauss rule embedded in it</span></span>
<span id="cb3-3">xgk <span class="ot" style="color: #003B4F;
background-color: null;
font-style: inherit;">&lt;-</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">c</span>(<span class="fl" style="color: #AD0000;
background-color: null;
font-style: inherit;">0.991455371120813</span>, <span class="fl" style="color: #AD0000;
background-color: null;
font-style: inherit;">0.949107912342759</span>, <span class="fl" style="color: #AD0000;
background-color: null;
font-style: inherit;">0.864864423359769</span>,</span>
<span id="cb3-4">         <span class="fl" style="color: #AD0000;
background-color: null;
font-style: inherit;">0.741531185599394</span>, <span class="fl" style="color: #AD0000;
background-color: null;
font-style: inherit;">0.586087235467691</span>, <span class="fl" style="color: #AD0000;
background-color: null;
font-style: inherit;">0.405845151377397</span>,</span>
<span id="cb3-5">         <span class="fl" style="color: #AD0000;
background-color: null;
font-style: inherit;">0.207784955007898</span>, <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">0</span>)</span>
<span id="cb3-6">wgk <span class="ot" style="color: #003B4F;
background-color: null;
font-style: inherit;">&lt;-</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">c</span>(<span class="fl" style="color: #AD0000;
background-color: null;
font-style: inherit;">0.022935322010529</span>, <span class="fl" style="color: #AD0000;
background-color: null;
font-style: inherit;">0.063092092629979</span>, <span class="fl" style="color: #AD0000;
background-color: null;
font-style: inherit;">0.104790010322250</span>,</span>
<span id="cb3-7">         <span class="fl" style="color: #AD0000;
background-color: null;
font-style: inherit;">0.140653259715525</span>, <span class="fl" style="color: #AD0000;
background-color: null;
font-style: inherit;">0.169004726639267</span>, <span class="fl" style="color: #AD0000;
background-color: null;
font-style: inherit;">0.190350578064785</span>,</span>
<span id="cb3-8">         <span class="fl" style="color: #AD0000;
background-color: null;
font-style: inherit;">0.204432940075298</span>, <span class="fl" style="color: #AD0000;
background-color: null;
font-style: inherit;">0.209482141084728</span>)</span>
<span id="cb3-9">wg  <span class="ot" style="color: #003B4F;
background-color: null;
font-style: inherit;">&lt;-</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">c</span>(<span class="fl" style="color: #AD0000;
background-color: null;
font-style: inherit;">0.129484966168870</span>, <span class="fl" style="color: #AD0000;
background-color: null;
font-style: inherit;">0.279705391489277</span>, <span class="fl" style="color: #AD0000;
background-color: null;
font-style: inherit;">0.381830050505119</span>,</span>
<span id="cb3-10">         <span class="fl" style="color: #AD0000;
background-color: null;
font-style: inherit;">0.417959183673469</span>)</span>
<span id="cb3-11"></span>
<span id="cb3-12">gk_pair <span class="ot" style="color: #003B4F;
background-color: null;
font-style: inherit;">&lt;-</span> <span class="cf" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">function</span>(g, a, b) {</span>
<span id="cb3-13">  cen <span class="ot" style="color: #003B4F;
background-color: null;
font-style: inherit;">&lt;-</span> (a <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">+</span> b) <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">/</span> <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">2</span></span>
<span id="cb3-14">  hw  <span class="ot" style="color: #003B4F;
background-color: null;
font-style: inherit;">&lt;-</span> (b <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">-</span> a) <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">/</span> <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">2</span></span>
<span id="cb3-15">  kron  <span class="ot" style="color: #003B4F;
background-color: null;
font-style: inherit;">&lt;-</span> hw <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">*</span> (<span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">sum</span>(wgk[<span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">1</span><span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">:</span><span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">7</span>] <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">*</span> (<span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">g</span>(cen <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">-</span> hw <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">*</span> xgk[<span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">1</span><span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">:</span><span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">7</span>]) <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">+</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">g</span>(cen <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">+</span> hw <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">*</span> xgk[<span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">1</span><span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">:</span><span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">7</span>]))) <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">+</span></span>
<span id="cb3-16">                   wgk[<span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">8</span>] <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">*</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">g</span>(cen))</span>
<span id="cb3-17">  gauss <span class="ot" style="color: #003B4F;
background-color: null;
font-style: inherit;">&lt;-</span> hw <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">*</span> (<span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">sum</span>(wg[<span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">1</span><span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">:</span><span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">3</span>] <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">*</span> (<span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">g</span>(cen <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">-</span> hw <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">*</span> xgk[<span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">c</span>(<span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">2</span>, <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">4</span>, <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">6</span>)]) <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">+</span></span>
<span id="cb3-18">                                  <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">g</span>(cen <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">+</span> hw <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">*</span> xgk[<span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">c</span>(<span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">2</span>, <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">4</span>, <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">6</span>)]))) <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">+</span> wg[<span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">4</span>] <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">*</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">g</span>(cen))</span>
<span id="cb3-19">  <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">c</span>(<span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">kronrod =</span> kron, <span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">gauss =</span> gauss)</span>
<span id="cb3-20">}</span>
<span id="cb3-21">nodes_x <span class="ot" style="color: #003B4F;
background-color: null;
font-style: inherit;">&lt;-</span> <span class="cf" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">function</span>(a, b) {</span>
<span id="cb3-22">  tt <span class="ot" style="color: #003B4F;
background-color: null;
font-style: inherit;">&lt;-</span> (a <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">+</span> b) <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">/</span> <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">2</span> <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">+</span> (b <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">-</span> a) <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">/</span> <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">2</span> <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">*</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">c</span>(<span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">-</span>xgk, <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">rev</span>(xgk[<span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">1</span><span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">:</span><span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">7</span>]))</span>
<span id="cb3-23">  (<span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">1</span> <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">-</span> tt) <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">/</span> tt</span>
<span id="cb3-24">}</span>
<span id="cb3-25"></span>
<span id="cb3-26">g_fish <span class="ot" style="color: #003B4F;
background-color: null;
font-style: inherit;">&lt;-</span> <span class="cf" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">function</span>(t) {</span>
<span id="cb3-27">  x <span class="ot" style="color: #003B4F;
background-color: null;
font-style: inherit;">&lt;-</span> (<span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">1</span> <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">-</span> t) <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">/</span> t</span>
<span id="cb3-28">  (<span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">dnorm</span>(x, <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">420</span>, <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">15</span>) <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">+</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">dnorm</span>(<span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">-</span>x, <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">420</span>, <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">15</span>)) <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">/</span> t<span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">^</span><span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">2</span></span>
<span id="cb3-29">}</span>
<span id="cb3-30">first_half <span class="ot" style="color: #003B4F;
background-color: null;
font-style: inherit;">&lt;-</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">gk_pair</span>(g_fish, <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">0</span>, <span class="fl" style="color: #AD0000;
background-color: null;
font-style: inherit;">0.5</span>)</span>
<span id="cb3-31">x_outer    <span class="ot" style="color: #003B4F;
background-color: null;
font-style: inherit;">&lt;-</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">max</span>(<span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">nodes_x</span>(<span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">0</span>, <span class="fl" style="color: #AD0000;
background-color: null;
font-style: inherit;">0.5</span>))</span>
<span id="cb3-32">kids_x     <span class="ot" style="color: #003B4F;
background-color: null;
font-style: inherit;">&lt;-</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">c</span>(<span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">nodes_x</span>(<span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">0</span>, <span class="fl" style="color: #AD0000;
background-color: null;
font-style: inherit;">0.25</span>), <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">nodes_x</span>(<span class="fl" style="color: #AD0000;
background-color: null;
font-style: inherit;">0.25</span>, <span class="fl" style="color: #AD0000;
background-color: null;
font-style: inherit;">0.5</span>))</span>
<span id="cb3-33">kid_below  <span class="ot" style="color: #003B4F;
background-color: null;
font-style: inherit;">&lt;-</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">max</span>(kids_x[kids_x <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">&lt;</span> <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">420</span>])</span>
<span id="cb3-34">kid_above  <span class="ot" style="color: #003B4F;
background-color: null;
font-style: inherit;">&lt;-</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">min</span>(kids_x[kids_x <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">&gt;</span> <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">420</span>])</span>
<span id="cb3-35">final_sum  <span class="ot" style="color: #003B4F;
background-color: null;
font-style: inherit;">&lt;-</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">gk_pair</span>(g_fish, <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">0</span>, <span class="fl" style="color: #AD0000;
background-color: null;
font-style: inherit;">0.25</span>)[<span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"kronrod"</span>] <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">+</span></span>
<span id="cb3-36">  <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">gk_pair</span>(g_fish, <span class="fl" style="color: #AD0000;
background-color: null;
font-style: inherit;">0.25</span>, <span class="fl" style="color: #AD0000;
background-color: null;
font-style: inherit;">0.5</span>)[<span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"kronrod"</span>] <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">+</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">gk_pair</span>(g_fish, <span class="fl" style="color: #AD0000;
background-color: null;
font-style: inherit;">0.5</span>, <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">1</span>)[<span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"kronrod"</span>]</span>
<span id="cb3-37">hand_match <span class="ot" style="color: #003B4F;
background-color: null;
font-style: inherit;">&lt;-</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">abs</span>(final_sum <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">/</span> probe_val[<span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">3</span>] <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">-</span> <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">1</span>)</span></code></pre></div></div>
</div>
<p>The three pieces the routine finished on, recomputed this way, add up to the value <code>integrate()</code> returned to a relative difference of <img src="https://latex.codecogs.com/png.latex?2.09%20%5Ctimes%2010%5E%7B-12%7D">, so the hand rules are the ones it used. The probe at 467 mm is the outermost Kronrod point on the half of the transformed interval that covers |x| of 1 and more, and the embedded Gauss rule does not share it. On that half the Kronrod estimate was 0.240, about a quarter of the answer, and the Gauss estimate was <img src="https://latex.codecogs.com/png.latex?3.79%20%5Ctimes%2010%5E%7B-113%7D">. That disagreement is exactly what makes the routine split the piece, and neither new piece had a point between 156 mm and 935 mm. Both returned next to nothing, the error estimate for the total came out as 0, and the routine reported the result as a success.</p>
<div class="cell">
<div class="code-copy-outer-scaffold"><div class="sourceCode cell-code" id="cb4" style="background: #f1f3f5;"><pre class="sourceCode r code-with-copy"><code class="sourceCode r"><span id="cb4-1">probe_pm  <span class="ot" style="color: #003B4F;
background-color: null;
font-style: inherit;">&lt;-</span> <span class="cf" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">function</span>(x) {                 <span class="co" style="color: #5E5E5E;
background-color: null;
font-style: inherit;"># "7.94" %*% 10^-7 for the strip labels</span></span>
<span id="cb4-2">  s <span class="ot" style="color: #003B4F;
background-color: null;
font-style: inherit;">&lt;-</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">fmt_e</span>(x)</span>
<span id="cb4-3">  <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">paste0</span>(<span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">'"'</span>, <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">sub</span>(<span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"e.*"</span>, <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">""</span>, s), <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">'" %*% 10^'</span>, <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">as.integer</span>(<span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">sub</span>(<span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">".*e"</span>, <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">""</span>, s)))</span>
<span id="cb4-4">}</span>
<span id="cb4-5">probe_lab <span class="ot" style="color: #003B4F;
background-color: null;
font-style: inherit;">&lt;-</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">sprintf</span>(<span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">'paste("mean %g, sd %g: returned ", %s)'</span>, probe_mu, probe_sd,</span>
<span id="cb4-6">                     <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">c</span>(<span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">sprintf</span>(<span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">'"%.3f"'</span>, probe_val[<span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">1</span>]), <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">probe_pm</span>(probe_val[<span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">2</span><span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">:</span><span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">3</span>])))</span>
<span id="cb4-7">probe_lab <span class="ot" style="color: #003B4F;
background-color: null;
font-style: inherit;">&lt;-</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">factor</span>(probe_lab, <span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">levels =</span> probe_lab)</span>
<span id="cb4-8">x_curve   <span class="ot" style="color: #003B4F;
background-color: null;
font-style: inherit;">&lt;-</span> <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">10</span><span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">^</span><span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">seq</span>(<span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">-</span><span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">3</span>, <span class="fl" style="color: #AD0000;
background-color: null;
font-style: inherit;">3.1</span>, <span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">length.out =</span> <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">3000</span>)</span>
<span id="cb4-9">curve_df  <span class="ot" style="color: #003B4F;
background-color: null;
font-style: inherit;">&lt;-</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">do.call</span>(rbind, <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">lapply</span>(<span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">1</span><span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">:</span><span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">3</span>, <span class="cf" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">function</span>(k) {</span>
<span id="cb4-10">  dens <span class="ot" style="color: #003B4F;
background-color: null;
font-style: inherit;">&lt;-</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">dnorm</span>(x_curve, probe_mu[k], probe_sd[k])</span>
<span id="cb4-11">  <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">data.frame</span>(<span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">x =</span> x_curve, <span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">y =</span> dens <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">/</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">max</span>(dens), <span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">call =</span> probe_lab[k])</span>
<span id="cb4-12">}))</span>
<span id="cb4-13">tick_df <span class="ot" style="color: #003B4F;
background-color: null;
font-style: inherit;">&lt;-</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">do.call</span>(rbind, <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">lapply</span>(<span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">1</span><span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">:</span><span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">3</span>, <span class="cf" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">function</span>(k) {</span>
<span id="cb4-14">  a <span class="ot" style="color: #003B4F;
background-color: null;
font-style: inherit;">&lt;-</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">abs</span>(probe_out[[k]]<span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">$</span>pts)</span>
<span id="cb4-15">  a <span class="ot" style="color: #003B4F;
background-color: null;
font-style: inherit;">&lt;-</span> a[a <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">&gt;</span> <span class="fl" style="color: #AD0000;
background-color: null;
font-style: inherit;">1e-3</span>]</span>
<span id="cb4-16">  <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">data.frame</span>(<span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">x =</span> a, <span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">call =</span> probe_lab[k])</span>
<span id="cb4-17">}))</span>
<span id="cb4-18"></span>
<span id="cb4-19"><span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">ggplot</span>() <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">+</span></span>
<span id="cb4-20">  <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">geom_area</span>(<span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">data =</span> curve_df, <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">aes</span>(x, y), <span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">fill =</span> te_forest, <span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">alpha =</span> <span class="fl" style="color: #AD0000;
background-color: null;
font-style: inherit;">0.25</span>,</span>
<span id="cb4-21">            <span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">colour =</span> te_forest, <span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">linewidth =</span> <span class="fl" style="color: #AD0000;
background-color: null;
font-style: inherit;">0.6</span>) <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">+</span></span>
<span id="cb4-22">  <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">geom_segment</span>(<span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">data =</span> tick_df, <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">aes</span>(<span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">x =</span> x, <span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">xend =</span> x, <span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">y =</span> <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">-</span><span class="fl" style="color: #AD0000;
background-color: null;
font-style: inherit;">0.12</span>, <span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">yend =</span> <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">-</span><span class="fl" style="color: #AD0000;
background-color: null;
font-style: inherit;">0.02</span>),</span>
<span id="cb4-23">               <span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">colour =</span> te_rust, <span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">linewidth =</span> <span class="fl" style="color: #AD0000;
background-color: null;
font-style: inherit;">0.5</span>) <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">+</span></span>
<span id="cb4-24">  <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">facet_wrap</span>(<span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">~</span> call, <span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">ncol =</span> <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">1</span>, <span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">labeller =</span> label_parsed) <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">+</span></span>
<span id="cb4-25">  <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">scale_x_log10</span>(<span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">breaks =</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">c</span>(<span class="fl" style="color: #AD0000;
background-color: null;
font-style: inherit;">0.001</span>, <span class="fl" style="color: #AD0000;
background-color: null;
font-style: inherit;">0.01</span>, <span class="fl" style="color: #AD0000;
background-color: null;
font-style: inherit;">0.1</span>, <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">1</span>, <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">10</span>, <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">100</span>, <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">1000</span>),</span>
<span id="cb4-26">                <span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">labels =</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">c</span>(<span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"0.001"</span>, <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"0.01"</span>, <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"0.1"</span>, <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"1"</span>, <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"10"</span>, <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"100"</span>, <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"1000"</span>)) <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">+</span></span>
<span id="cb4-27">  <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">labs</span>(<span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">x =</span> <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"absolute value of x (log scale)"</span>, <span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">y =</span> <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"density / its peak"</span>,</span>
<span id="cb4-28">       <span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">title =</span> <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"The probes crowd near zero"</span>,</span>
<span id="cb4-29">       <span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">subtitle =</span> <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"red ticks: points where integrate() evaluated the function"</span>) <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">+</span></span>
<span id="cb4-30">  <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">theme_datasheet</span>() <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">+</span></span>
<span id="cb4-31">  <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">theme</span>(<span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">strip.text =</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">element_text</span>(<span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">colour =</span> te_ink, <span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">hjust =</span> <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">0</span>))</span></code></pre></div></div>
<div class="cell-output-display">
<div id="fig-probes" class="quarto-float quarto-figure quarto-figure-center anchored" alt="Three stacked panels on warm off-white paper, each with a horizontal logarithmic axis for the absolute value of x from 0.001 to 1000 and a row of short red ticks under a dark green density curve scaled to a height of one. Top panel, mean 0 and sd 1, returned 1.000: the shaded curve is flat at one up to about 0.3 and falls to zero by about 4, and the ticks are densest between 1 and 3, where the curve drops. Middle panel, mean 20 and sd 1, returned 7.94 times 10 to the minus 7: a thin spike at 20, with the nearest ticks at about 14 below it and 29 above it but none on it. Bottom panel, mean 420 and sd 15, returned 3.55 times 10 to the minus 67: a thin spike at 420; the ticks run from 0.002 to near 1000 and are densest between 1 and 10, and the nearest ones sit at about 230 and 470, either side of the spike.">
<figure class="quarto-float quarto-float-fig figure">
<div aria-describedby="fig-probes-caption-0ceaefa1-69ba-4598-a22c-09a6ac19f8ca">
<img src="https://tidyecology.com/posts/when-integrate-returns-zero/index_files/figure-html/fig-probes-1.png" class="img-fluid figure-img" alt="Three stacked panels on warm off-white paper, each with a horizontal logarithmic axis for the absolute value of x from 0.001 to 1000 and a row of short red ticks under a dark green density curve scaled to a height of one. Top panel, mean 0 and sd 1, returned 1.000: the shaded curve is flat at one up to about 0.3 and falls to zero by about 4, and the ticks are densest between 1 and 3, where the curve drops. Middle panel, mean 20 and sd 1, returned 7.94 times 10 to the minus 7: a thin spike at 20, with the nearest ticks at about 14 below it and 29 above it but none on it. Bottom panel, mean 420 and sd 15, returned 3.55 times 10 to the minus 67: a thin spike at 420; the ticks run from 0.002 to near 1000 and are densest between 1 and 10, and the nearest ones sit at about 230 and 470, either side of the spike." width="672">
</div>
<figcaption class="quarto-float-caption-bottom quarto-float-caption quarto-float-fig" id="fig-probes-caption-0ceaefa1-69ba-4598-a22c-09a6ac19f8ca">
Figure&nbsp;1: Where integrate() evaluated three normal densities over the whole real line. Ticks: the probe points on the absolute scale; curves: each density scaled to its own peak.
</figcaption>
</figure>
</div>
</div>
</div>
</section>
<section id="a-failure-map-over-the-means-and-widths-ecologists-meet" class="level2">
<h2 id="a-failure-map-over-the-means-and-widths-ecologists-meet-h" class="anchored" data-anchor-id="a-failure-map-over-the-means-and-widths-ecologists-meet">A failure map over the means and widths ecologists meet</h2>
<p>One failing call is an anecdote. The grid below crosses nine means with six standard deviations and asks the same question of every cell: does <code>integrate(dnorm, -Inf, Inf, mean, sd)</code> return 1?</p>
<p>The grid is a choice, and the failure share is a direct function of how far out it reaches, so it needs defending in the open. The means run from 0 and 1, where a proportion or a standardised covariate lives, through 2, 5 and 10, where a log count or a logged body mass sits, to 20, 50, 100 and 420, which cover a water temperature, a plant height in centimetres, a wing length and a body length in millimetres. The standard deviations run from 1 down to 0.003. The small ones are not exotic: the integrand inside a likelihood is the product of a prior spread and a measurement kernel, and a precise measurement makes that product narrow even when the population is wide. The share is also reported for the three widest standard deviations alone, so that a reader who rejects the narrow half of the grid still gets a number.</p>
<div class="cell">
<div class="code-copy-outer-scaffold"><div class="sourceCode cell-code" id="cb5" style="background: #f1f3f5;"><pre class="sourceCode r code-with-copy"><code class="sourceCode r"><span id="cb5-1">grid_mu <span class="ot" style="color: #003B4F;
background-color: null;
font-style: inherit;">&lt;-</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">c</span>(<span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">0</span>, <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">1</span>, <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">2</span>, <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">5</span>, <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">10</span>, <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">20</span>, <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">50</span>, <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">100</span>, <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">420</span>)</span>
<span id="cb5-2">grid_sd <span class="ot" style="color: #003B4F;
background-color: null;
font-style: inherit;">&lt;-</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">c</span>(<span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">1</span>, <span class="fl" style="color: #AD0000;
background-color: null;
font-style: inherit;">0.3</span>, <span class="fl" style="color: #AD0000;
background-color: null;
font-style: inherit;">0.1</span>, <span class="fl" style="color: #AD0000;
background-color: null;
font-style: inherit;">0.03</span>, <span class="fl" style="color: #AD0000;
background-color: null;
font-style: inherit;">0.01</span>, <span class="fl" style="color: #AD0000;
background-color: null;
font-style: inherit;">0.003</span>)</span>
<span id="cb5-3">fail_map <span class="ot" style="color: #003B4F;
background-color: null;
font-style: inherit;">&lt;-</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">expand.grid</span>(<span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">mu =</span> grid_mu, <span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">sd =</span> grid_sd)</span>
<span id="cb5-4"></span>
<span id="cb5-5">one_cell <span class="ot" style="color: #003B4F;
background-color: null;
font-style: inherit;">&lt;-</span> <span class="cf" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">function</span>(mu, s) {</span>
<span id="cb5-6">  full <span class="ot" style="color: #003B4F;
background-color: null;
font-style: inherit;">&lt;-</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">integrate</span>(dnorm, <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">-</span><span class="cn" style="color: #8f5902;
background-color: null;
font-style: inherit;">Inf</span>, <span class="cn" style="color: #8f5902;
background-color: null;
font-style: inherit;">Inf</span>, <span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">mean =</span> mu, <span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">sd =</span> s, <span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">stop.on.error =</span> <span class="cn" style="color: #8f5902;
background-color: null;
font-style: inherit;">FALSE</span>)</span>
<span id="cb5-7">  half <span class="ot" style="color: #003B4F;
background-color: null;
font-style: inherit;">&lt;-</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">integrate</span>(dnorm, <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">0</span>, <span class="cn" style="color: #8f5902;
background-color: null;
font-style: inherit;">Inf</span>, <span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">mean =</span> mu, <span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">sd =</span> s, <span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">stop.on.error =</span> <span class="cn" style="color: #8f5902;
background-color: null;
font-style: inherit;">FALSE</span>)</span>
<span id="cb5-8">  subst <span class="ot" style="color: #003B4F;
background-color: null;
font-style: inherit;">&lt;-</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">integrate</span>(<span class="cf" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">function</span>(z) <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">dnorm</span>(mu <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">+</span> s <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">*</span> z, mu, s) <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">*</span> s, <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">-</span><span class="cn" style="color: #8f5902;
background-color: null;
font-style: inherit;">Inf</span>, <span class="cn" style="color: #8f5902;
background-color: null;
font-style: inherit;">Inf</span>)</span>
<span id="cb5-9">  finite <span class="ot" style="color: #003B4F;
background-color: null;
font-style: inherit;">&lt;-</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">integrate</span>(dnorm, mu <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">-</span> <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">8</span> <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">*</span> s, mu <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">+</span> <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">8</span> <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">*</span> s, <span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">mean =</span> mu, <span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">sd =</span> s)</span>
<span id="cb5-10">  <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">c</span>(<span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">full =</span> full<span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">$</span>value, <span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">full_ok =</span> full<span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">$</span>message <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">==</span> <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"OK"</span>,</span>
<span id="cb5-11">    <span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">full_abserr =</span> full<span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">$</span>abs.error,</span>
<span id="cb5-12">    <span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">half =</span> half<span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">$</span>value, <span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">half_ok =</span> half<span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">$</span>message <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">==</span> <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"OK"</span>,</span>
<span id="cb5-13">    <span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">subst =</span> subst<span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">$</span>value, <span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">finite =</span> finite<span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">$</span>value)</span>
<span id="cb5-14">}</span>
<span id="cb5-15">cell_res <span class="ot" style="color: #003B4F;
background-color: null;
font-style: inherit;">&lt;-</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">t</span>(<span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">mapply</span>(one_cell, fail_map<span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">$</span>mu, fail_map<span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">$</span>sd))</span>
<span id="cb5-16">fail_map <span class="ot" style="color: #003B4F;
background-color: null;
font-style: inherit;">&lt;-</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">cbind</span>(fail_map, cell_res)</span>
<span id="cb5-17">fail_map<span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">$</span>half_target <span class="ot" style="color: #003B4F;
background-color: null;
font-style: inherit;">&lt;-</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">pnorm</span>(<span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">0</span>, fail_map<span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">$</span>mu, fail_map<span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">$</span>sd, <span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">lower.tail =</span> <span class="cn" style="color: #8f5902;
background-color: null;
font-style: inherit;">FALSE</span>)</span>
<span id="cb5-18"></span>
<span id="cb5-19">fail_map<span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">$</span>full_wrong <span class="ot" style="color: #003B4F;
background-color: null;
font-style: inherit;">&lt;-</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">abs</span>(fail_map<span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">$</span>full <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">-</span> <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">1</span>) <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">&gt;</span> <span class="fl" style="color: #AD0000;
background-color: null;
font-style: inherit;">0.01</span></span>
<span id="cb5-20">fail_map<span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">$</span>half_wrong <span class="ot" style="color: #003B4F;
background-color: null;
font-style: inherit;">&lt;-</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">abs</span>(fail_map<span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">$</span>half <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">-</span> fail_map<span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">$</span>half_target) <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">&gt;</span></span>
<span id="cb5-21">  <span class="fl" style="color: #AD0000;
background-color: null;
font-style: inherit;">0.01</span> <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">*</span> fail_map<span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">$</span>half_target</span>
<span id="cb5-22"></span>
<span id="cb5-23">n_cell      <span class="ot" style="color: #003B4F;
background-color: null;
font-style: inherit;">&lt;-</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">nrow</span>(fail_map)</span>
<span id="cb5-24">share_wrong <span class="ot" style="color: #003B4F;
background-color: null;
font-style: inherit;">&lt;-</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">mean</span>(fail_map<span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">$</span>full_wrong)</span>
<span id="cb5-25">share_zero  <span class="ot" style="color: #003B4F;
background-color: null;
font-style: inherit;">&lt;-</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">mean</span>(fail_map<span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">$</span>full <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">==</span> <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">0</span>)</span>
<span id="cb5-26">n_wrong     <span class="ot" style="color: #003B4F;
background-color: null;
font-style: inherit;">&lt;-</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">sum</span>(fail_map<span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">$</span>full_wrong)</span>
<span id="cb5-27">ok_in_fail  <span class="ot" style="color: #003B4F;
background-color: null;
font-style: inherit;">&lt;-</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">mean</span>(fail_map<span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">$</span>full_ok[fail_map<span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">$</span>full_wrong] <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">==</span> <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">1</span>)</span>
<span id="cb5-28">n_not_ok    <span class="ot" style="color: #003B4F;
background-color: null;
font-style: inherit;">&lt;-</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">sum</span>(fail_map<span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">$</span>full_ok <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">==</span> <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">0</span>) <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">+</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">sum</span>(fail_map<span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">$</span>half_ok <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">==</span> <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">0</span>)</span>
<span id="cb5-29">share_half  <span class="ot" style="color: #003B4F;
background-color: null;
font-style: inherit;">&lt;-</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">mean</span>(fail_map<span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">$</span>half_wrong)</span>
<span id="cb5-30">half_agree  <span class="ot" style="color: #003B4F;
background-color: null;
font-style: inherit;">&lt;-</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">mean</span>(fail_map<span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">$</span>half_wrong <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">==</span> fail_map<span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">$</span>full_wrong)</span>
<span id="cb5-31">wide_rows   <span class="ot" style="color: #003B4F;
background-color: null;
font-style: inherit;">&lt;-</span> fail_map<span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">$</span>sd <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">&gt;=</span> <span class="fl" style="color: #AD0000;
background-color: null;
font-style: inherit;">0.1</span></span>
<span id="cb5-32">share_wide  <span class="ot" style="color: #003B4F;
background-color: null;
font-style: inherit;">&lt;-</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">mean</span>(fail_map<span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">$</span>full_wrong[wide_rows])</span>
<span id="cb5-33">n_wide      <span class="ot" style="color: #003B4F;
background-color: null;
font-style: inherit;">&lt;-</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">sum</span>(wide_rows)</span>
<span id="cb5-34">first_fail_sd1 <span class="ot" style="color: #003B4F;
background-color: null;
font-style: inherit;">&lt;-</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">min</span>(fail_map<span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">$</span>mu[fail_map<span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">$</span>sd <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">==</span> <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">1</span> <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">&amp;</span> fail_map<span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">$</span>full_wrong])</span>
<span id="cb5-35">fail_abserr_max <span class="ot" style="color: #003B4F;
background-color: null;
font-style: inherit;">&lt;-</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">max</span>(fail_map<span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">$</span>full_abserr[fail_map<span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">$</span>full_wrong])</span>
<span id="cb5-36">gold_rows   <span class="ot" style="color: #003B4F;
background-color: null;
font-style: inherit;">&lt;-</span> fail_map<span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">$</span>full_wrong <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">&amp;</span> fail_map<span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">$</span>full <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">!=</span> <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">0</span></span>
<span id="cb5-37">n_gold      <span class="ot" style="color: #003B4F;
background-color: null;
font-style: inherit;">&lt;-</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">sum</span>(gold_rows)</span>
<span id="cb5-38">n_gold_big  <span class="ot" style="color: #003B4F;
background-color: null;
font-style: inherit;">&lt;-</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">sum</span>(fail_map<span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">$</span>full_abserr[gold_rows] <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">&gt;</span> fail_map<span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">$</span>full[gold_rows])</span>
<span id="cb5-39">default_tol <span class="ot" style="color: #003B4F;
background-color: null;
font-style: inherit;">&lt;-</span> .Machine<span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">$</span>double.eps<span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">^</span><span class="fl" style="color: #AD0000;
background-color: null;
font-style: inherit;">0.25</span></span>
<span id="cb5-40"></span>
<span id="cb5-41">near_one <span class="ot" style="color: #003B4F;
background-color: null;
font-style: inherit;">&lt;-</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">vapply</span>(<span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">c</span>(<span class="fl" style="color: #AD0000;
background-color: null;
font-style: inherit;">0.9</span>, <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">1</span>, <span class="fl" style="color: #AD0000;
background-color: null;
font-style: inherit;">1.1</span>), <span class="cf" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">function</span>(m)</span>
<span id="cb5-42">  <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">integrate</span>(dnorm, <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">-</span><span class="cn" style="color: #8f5902;
background-color: null;
font-style: inherit;">Inf</span>, <span class="cn" style="color: #8f5902;
background-color: null;
font-style: inherit;">Inf</span>, <span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">mean =</span> m, <span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">sd =</span> <span class="fl" style="color: #AD0000;
background-color: null;
font-style: inherit;">0.003</span>)<span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">$</span>value, <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">0</span>)</span>
<span id="cb5-43">nz_grid <span class="ot" style="color: #003B4F;
background-color: null;
font-style: inherit;">&lt;-</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">expand.grid</span>(<span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">mu =</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">c</span>(<span class="fl" style="color: #AD0000;
background-color: null;
font-style: inherit;">0.25</span>, <span class="fl" style="color: #AD0000;
background-color: null;
font-style: inherit;">0.5</span>, <span class="fl" style="color: #AD0000;
background-color: null;
font-style: inherit;">0.75</span>, <span class="fl" style="color: #AD0000;
background-color: null;
font-style: inherit;">1.25</span>, <span class="fl" style="color: #AD0000;
background-color: null;
font-style: inherit;">1.5</span>, <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">2</span>),</span>
<span id="cb5-44">                       <span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">sd =</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">c</span>(<span class="fl" style="color: #AD0000;
background-color: null;
font-style: inherit;">0.1</span>, <span class="fl" style="color: #AD0000;
background-color: null;
font-style: inherit;">0.03</span>, <span class="fl" style="color: #AD0000;
background-color: null;
font-style: inherit;">0.01</span>, <span class="fl" style="color: #AD0000;
background-color: null;
font-style: inherit;">0.003</span>))</span>
<span id="cb5-45">nz_grid<span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">$</span>wrong <span class="ot" style="color: #003B4F;
background-color: null;
font-style: inherit;">&lt;-</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">mapply</span>(<span class="cf" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">function</span>(m, s)</span>
<span id="cb5-46">  <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">abs</span>(<span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">integrate</span>(dnorm, <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">-</span><span class="cn" style="color: #8f5902;
background-color: null;
font-style: inherit;">Inf</span>, <span class="cn" style="color: #8f5902;
background-color: null;
font-style: inherit;">Inf</span>, <span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">mean =</span> m, <span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">sd =</span> s)<span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">$</span>value <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">-</span> <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">1</span>) <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">&gt;</span> <span class="fl" style="color: #AD0000;
background-color: null;
font-style: inherit;">0.01</span>,</span>
<span id="cb5-47">  nz_grid<span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">$</span>mu, nz_grid<span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">$</span>sd)</span>
<span id="cb5-48">nz_n_fail  <span class="ot" style="color: #003B4F;
background-color: null;
font-style: inherit;">&lt;-</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">sum</span>(nz_grid<span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">$</span>wrong)</span>
<span id="cb5-49">nz_sd_max  <span class="ot" style="color: #003B4F;
background-color: null;
font-style: inherit;">&lt;-</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">max</span>(nz_grid<span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">$</span>sd[nz_grid<span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">$</span>wrong])</span>
<span id="cb5-50">nz_sd3     <span class="ot" style="color: #003B4F;
background-color: null;
font-style: inherit;">&lt;-</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">sum</span>(nz_grid<span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">$</span>wrong[nz_grid<span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">$</span>sd <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">==</span> <span class="fl" style="color: #AD0000;
background-color: null;
font-style: inherit;">0.003</span>])</span>
<span id="cb5-51"></span>
<span id="cb5-52">worst_subst  <span class="ot" style="color: #003B4F;
background-color: null;
font-style: inherit;">&lt;-</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">max</span>(<span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">abs</span>(fail_map<span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">$</span>subst <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">-</span> <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">1</span>))</span>
<span id="cb5-53">worst_finite <span class="ot" style="color: #003B4F;
background-color: null;
font-style: inherit;">&lt;-</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">max</span>(<span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">abs</span>(fail_map<span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">$</span>finite <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">-</span> <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">1</span>))</span>
<span id="cb5-54"></span>
<span id="cb5-55">hn_sigma <span class="ot" style="color: #003B4F;
background-color: null;
font-style: inherit;">&lt;-</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">c</span>(<span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">1</span>, <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">10</span>, <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">50</span>, <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">100</span>, <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">500</span>)</span>
<span id="cb5-56">hn_err <span class="ot" style="color: #003B4F;
background-color: null;
font-style: inherit;">&lt;-</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">vapply</span>(hn_sigma, <span class="cf" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">function</span>(sg) {</span>
<span id="cb5-57">  num <span class="ot" style="color: #003B4F;
background-color: null;
font-style: inherit;">&lt;-</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">integrate</span>(<span class="cf" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">function</span>(r) <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">exp</span>(<span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">-</span>r<span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">^</span><span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">2</span> <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">/</span> (<span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">2</span> <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">*</span> sg<span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">^</span><span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">2</span>)), <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">0</span>, <span class="cn" style="color: #8f5902;
background-color: null;
font-style: inherit;">Inf</span>)<span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">$</span>value</span>
<span id="cb5-58">  <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">abs</span>(num <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">/</span> (sg <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">*</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">sqrt</span>(pi <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">/</span> <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">2</span>)) <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">-</span> <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">1</span>)</span>
<span id="cb5-59">}, <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">0</span>)</span>
<span id="cb5-60">hn_worst <span class="ot" style="color: #003B4F;
background-color: null;
font-style: inherit;">&lt;-</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">max</span>(hn_err)</span>
<span id="cb5-61"></span>
<span id="cb5-62">tight_call <span class="ot" style="color: #003B4F;
background-color: null;
font-style: inherit;">&lt;-</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">integrate</span>(dnorm, <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">-</span><span class="cn" style="color: #8f5902;
background-color: null;
font-style: inherit;">Inf</span>, <span class="cn" style="color: #8f5902;
background-color: null;
font-style: inherit;">Inf</span>, <span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">mean =</span> <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">420</span>, <span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">sd =</span> <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">15</span>,</span>
<span id="cb5-63">                        <span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">rel.tol =</span> <span class="fl" style="color: #AD0000;
background-color: null;
font-style: inherit;">1e-10</span>, <span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">subdivisions =</span> <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">1000</span>L)</span>
<span id="cb5-64">tight_val <span class="ot" style="color: #003B4F;
background-color: null;
font-style: inherit;">&lt;-</span> tight_call<span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">$</span>value</span>
<span id="cb5-65">tight_msg <span class="ot" style="color: #003B4F;
background-color: null;
font-style: inherit;">&lt;-</span> tight_call<span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">$</span>message</span>
<span id="cb5-66"></span>
<span id="cb5-67">help_20000 <span class="ot" style="color: #003B4F;
background-color: null;
font-style: inherit;">&lt;-</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">integrate</span>(dnorm, <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">0</span>, <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">20000</span>)<span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">$</span>value</span>
<span id="cb5-68">help_inf   <span class="ot" style="color: #003B4F;
background-color: null;
font-style: inherit;">&lt;-</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">integrate</span>(dnorm, <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">0</span>, <span class="cn" style="color: #8f5902;
background-color: null;
font-style: inherit;">Inf</span>)<span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">$</span>value</span></code></pre></div></div>
</div>
<p>Of the 54 cells, 35 come back more than 1 per cent wrong, a share of 0.648, and 0.519 of all cells come back as exactly 0. These calls, too, were made with <code>stop.on.error = FALSE</code>: under the default a failure the routine detects stops with an error, and the OK share below could not be anything but 1. Among the failures, the share whose message is <code>"OK"</code> is 1.000, and the number of cells anywhere on the grid, whole line or half line, with any other message is 0. The informative fact is that the routine flagged nothing: its own error test was satisfied in every one of these cells. The largest absolute error <code>integrate()</code> reported for a failing cell was <img src="https://latex.codecogs.com/png.latex?1.55%20%5Ctimes%2010%5E%7B-5%7D">, and that small number is no comfort. In 6 of the 7 failing cells that are not exactly 0, the reported error is larger than the value itself. It passes because the default <code>abs.tol</code> equals <code>rel.tol</code>, <code>.Machine$double.eps^0.25</code> or <img src="https://latex.codecogs.com/png.latex?1.22%20%5Ctimes%2010%5E%7B-4%7D">, and it is an absolute tolerance: an integral smaller than that can be accepted whatever its relative error. Restricted to the 27 cells with a standard deviation of 0.1 or more, the failure share is 0.519. At a standard deviation of 1 the first mean that fails is 20.</p>
<p>The all-green column at a mean of 1 is luck rather than safety: x = 1 is where the transformation puts the centre point of the rule’s first pass. At a standard deviation of 0.003, means of 0.9, 1 and 1.1 return <img src="https://latex.codecogs.com/png.latex?1.09%20%5Ctimes%2010%5E%7B-16%7D">, 1.000 and <img src="https://latex.codecogs.com/png.latex?3.18%20%5Ctimes%2010%5E%7B-48%7D">.</p>
<p>The trap is not confined to doubly infinite limits. Integrating the same densities over the half line from 0 to infinity, against the exact target from <code>pnorm()</code>, 0.648 of cells are more than 1 per cent wrong, and the half line and the whole line agree on which cells fail in 1.000 of the grid. What does not fail is a half-normal detection function with its scale in metres, the most common detection function in distance sampling, over the same half line: at a scale of 1, 10, 50, 100 and 500 m the worst relative error is <img src="https://latex.codecogs.com/png.latex?2.58%20%5Ctimes%2010%5E%7B-10%7D">. Its mass sits at zero, where the probes are.</p>
<div class="cell">
<div class="code-copy-outer-scaffold"><div class="sourceCode cell-code" id="cb6" style="background: #f1f3f5;"><pre class="sourceCode r code-with-copy"><code class="sourceCode r"><span id="cb6-1">fail_map<span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">$</span>verdict <span class="ot" style="color: #003B4F;
background-color: null;
font-style: inherit;">&lt;-</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">ifelse</span>(<span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">!</span>fail_map<span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">$</span>full_wrong, <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"within 1 per cent of 1"</span>,</span>
<span id="cb6-2">                    <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">ifelse</span>(fail_map<span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">$</span>full <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">==</span> <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">0</span>, <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"exactly 0"</span>, <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"wrong, not zero"</span>))</span>
<span id="cb6-3">fail_map<span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">$</span>verdict <span class="ot" style="color: #003B4F;
background-color: null;
font-style: inherit;">&lt;-</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">factor</span>(fail_map<span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">$</span>verdict,</span>
<span id="cb6-4">  <span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">levels =</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">c</span>(<span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"within 1 per cent of 1"</span>, <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"wrong, not zero"</span>, <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"exactly 0"</span>))</span>
<span id="cb6-5">fail_map<span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">$</span>lab <span class="ot" style="color: #003B4F;
background-color: null;
font-style: inherit;">&lt;-</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">ifelse</span>(fail_map<span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">$</span>full <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">==</span> <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">0</span>, <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"0"</span>,</span>
<span id="cb6-6">                <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">ifelse</span>(fail_map<span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">$</span>full_wrong,</span>
<span id="cb6-7">                       <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">sub</span>(<span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"e(.*)"</span>, <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">" %*% 10^</span><span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">\\</span><span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">1"</span>, <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">sprintf</span>(<span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"%.0e"</span>, fail_map<span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">$</span>full)), <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"1"</span>))</span>
<span id="cb6-8">fail_map<span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">$</span>lab <span class="ot" style="color: #003B4F;
background-color: null;
font-style: inherit;">&lt;-</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">gsub</span>(<span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"</span><span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">\\</span><span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">^([+-]?)0*([0-9])"</span>, <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"^</span><span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">\\</span><span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">1</span><span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">\\</span><span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">2"</span>, fail_map<span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">$</span>lab)  <span class="co" style="color: #5E5E5E;
background-color: null;
font-style: inherit;"># 10^-07 -&gt; 10^-7</span></span>
<span id="cb6-9"></span>
<span id="cb6-10"><span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">ggplot</span>(fail_map, <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">aes</span>(<span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">factor</span>(mu), <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">factor</span>(sd, <span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">levels =</span> grid_sd))) <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">+</span></span>
<span id="cb6-11">  <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">geom_tile</span>(<span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">aes</span>(<span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">fill =</span> verdict), <span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">colour =</span> te_paper, <span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">linewidth =</span> <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">1</span>) <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">+</span></span>
<span id="cb6-12">  <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">geom_text</span>(<span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">aes</span>(<span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">label =</span> lab), <span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">size =</span> <span class="fl" style="color: #AD0000;
background-color: null;
font-style: inherit;">2.9</span>, <span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">parse =</span> <span class="cn" style="color: #8f5902;
background-color: null;
font-style: inherit;">TRUE</span>,</span>
<span id="cb6-13">            <span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">colour =</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">ifelse</span>(fail_map<span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">$</span>verdict <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">==</span> <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"within 1 per cent of 1"</span>,</span>
<span id="cb6-14">                            te_paper, te_ink)) <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">+</span></span>
<span id="cb6-15">  <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">scale_fill_manual</span>(<span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">values =</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">c</span>(te_forest, te_gold, te_rust), <span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">name =</span> <span class="cn" style="color: #8f5902;
background-color: null;
font-style: inherit;">NULL</span>,</span>
<span id="cb6-16">                    <span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">drop =</span> <span class="cn" style="color: #8f5902;
background-color: null;
font-style: inherit;">FALSE</span>) <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">+</span></span>
<span id="cb6-17">  <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">labs</span>(<span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">x =</span> <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"mean"</span>, <span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">y =</span> <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"standard deviation"</span>,</span>
<span id="cb6-18">       <span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">title =</span> <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"Every failure reports OK"</span>,</span>
<span id="cb6-19">       <span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">subtitle =</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">sprintf</span>(<span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"cell text: the value returned; no error raised, message OK in all %d cells"</span>, n_cell)) <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">+</span></span>
<span id="cb6-20">  <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">theme_datasheet</span>() <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">+</span></span>
<span id="cb6-21">  <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">theme</span>(<span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">legend.position =</span> <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"bottom"</span>, <span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">panel.grid.major =</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">element_blank</span>())</span></code></pre></div></div>
<div class="cell-output-display">
<div id="fig-failmap" class="quarto-float quarto-figure quarto-figure-center anchored" alt="A grid of 54 coloured tiles on warm off-white paper, nine means from 0 to 420 across and six standard deviations from 1 at the bottom to 0.003 at the top. Dark green tiles labelled 1 fill the two left columns and a staircase in the lower left that reaches a mean of 10 for standard deviations of 1 and 0.3, a mean of 2 at 0.1, and only means 0 and 1 above that. Gold tiles, wrong but not zero, sit along the edge of the staircase with values such as 8 times 10 to the minus 7 and 3 times 10 to the minus 99 at sd 1 and 3 times 10 to the minus 73 at sd 0.3. Every tile to the upper right is red and labelled 0, including every tile at means of 100 and 420.">
<figure class="quarto-float quarto-float-fig figure">
<div aria-describedby="fig-failmap-caption-0ceaefa1-69ba-4598-a22c-09a6ac19f8ca">
<img src="https://tidyecology.com/posts/when-integrate-returns-zero/index_files/figure-html/fig-failmap-1.png" class="img-fluid figure-img" alt="A grid of 54 coloured tiles on warm off-white paper, nine means from 0 to 420 across and six standard deviations from 1 at the bottom to 0.003 at the top. Dark green tiles labelled 1 fill the two left columns and a staircase in the lower left that reaches a mean of 10 for standard deviations of 1 and 0.3, a mean of 2 at 0.1, and only means 0 and 1 above that. Gold tiles, wrong but not zero, sit along the edge of the staircase with values such as 8 times 10 to the minus 7 and 3 times 10 to the minus 99 at sd 1 and 3 times 10 to the minus 73 at sd 0.3. Every tile to the upper right is red and labelled 0, including every tile at means of 100 and 420." width="672">
</div>
<figcaption class="quarto-float-caption-bottom quarto-float-caption quarto-float-fig" id="fig-failmap-caption-0ceaefa1-69ba-4598-a22c-09a6ac19f8ca">
Figure&nbsp;2: What integrate(dnorm, -Inf, Inf) returns over a grid of means and standard deviations. The correct answer is 1 in every cell.
</figcaption>
</figure>
</div>
</div>
</div>
</section>
<section id="the-help-page-points-the-other-way" class="level2">
<h2 id="the-help-page-points-the-other-way-h" class="anchored" data-anchor-id="the-help-page-points-the-other-way">The help page points the other way</h2>
<p>The help page warns in general terms, then points the reader the wrong way. The second example in <code>?integrate</code> is <code>integrate(dnorm, -Inf, Inf)</code>, the call that fails above once the mean sits far enough from zero for the width of the density. Further down, the Examples block shows the infinite limit as the repair for a failure on a wide finite range:</p>
<pre><code>## integrate can fail if misused
integrate(dnorm, 0, 20000) ## fails on many systems
integrate(dnorm, 0, Inf)   ## works</code></pre>
<p>On this machine the first returns 0 and the second 0.500000. The Note section of the page makes two points that matter here, in this order. The first is the general warning: “If the function is approximately constant (in particular, zero) over nearly all its range it is possible that the result and error estimate may be seriously wrong.” The second is the advice those two example lines act out: “When integrating over infinite intervals do so explicitly, rather than just using a large number as the endpoint. This increases the chance of a correct answer - any function whose integral over an infinite interval is finite must be near zero for most of that interval.” For a density centred at zero the advice is right. A density at 420 mm is near zero over nearly all of the real line as well, which is the first warning’s case, and the explicit infinite limit is exactly the call that misses it. The rule to take away is about where the mass sits relative to the points the routine tries first, not about whether the limits are finite.</p>
</section>
<section id="two-repairs-and-which-gives-way-first" class="level2">
<h2 id="two-repairs-and-which-gives-way-first-h" class="anchored" data-anchor-id="two-repairs-and-which-gives-way-first">Two repairs, and which gives way first</h2>
<p>On the grid above, both of the usual repairs are exact. Substituting the standardised variable, so that the routine integrates over z with x equal to the mean plus sd times z, gives a worst absolute error of <img src="https://latex.codecogs.com/png.latex?2.06%20%5Ctimes%2010%5E%7B-10%7D">; finite limits at the mean plus and minus 8 standard deviations give <img src="https://latex.codecogs.com/png.latex?2.08%20%5Ctimes%2010%5E%7B-12%7D">. That comparison flatters the substitution, though: for a single normal density the substituted integrand is the standard normal in every cell, so its exactness there is a tautology. The test that separates them is the integrand the fish likelihood actually needs.</p>
<p>For one fish with recorded length w, the integrand over its true length x is the measurement kernel, a normal density for w centred on x with sd equal to the measurement error, times the population density of x. Without the logistic term its integral has a closed form, a normal density for w with variance equal to the sum of the two variances, which makes it a benchmark. Both repairs are built from the population scale: the substitution centres on the population mean and scales by the population sd, and the finite limits sit 8 population sds either side. As the measurement error shrinks, the integrand becomes a narrow spike somewhere inside that range, and the question is which repair loses it first. A third route centres and scales on the integrand itself, on the mean and sd of the true length given that fish’s record, which is the idea behind the adaptive Gauss-Hermite rule of Liu and Pierce.</p>
<div class="cell">
<div class="code-copy-outer-scaffold"><div class="sourceCode cell-code" id="cb8" style="background: #f1f3f5;"><pre class="sourceCode r code-with-copy"><code class="sourceCode r"><span id="cb8-1">pop_mu <span class="ot" style="color: #003B4F;
background-color: null;
font-style: inherit;">&lt;-</span> <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">420</span></span>
<span id="cb8-2">pop_sd <span class="ot" style="color: #003B4F;
background-color: null;
font-style: inherit;">&lt;-</span> <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">15</span></span>
<span id="cb8-3">me_grid <span class="ot" style="color: #003B4F;
background-color: null;
font-style: inherit;">&lt;-</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">c</span>(<span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">8</span>, <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">4</span>, <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">2</span>, <span class="fl" style="color: #AD0000;
background-color: null;
font-style: inherit;">1.4</span>, <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">1</span>, <span class="fl" style="color: #AD0000;
background-color: null;
font-style: inherit;">0.7</span>, <span class="fl" style="color: #AD0000;
background-color: null;
font-style: inherit;">0.5</span>, <span class="fl" style="color: #AD0000;
background-color: null;
font-style: inherit;">0.35</span>, <span class="fl" style="color: #AD0000;
background-color: null;
font-style: inherit;">0.25</span>, <span class="fl" style="color: #AD0000;
background-color: null;
font-style: inherit;">0.1</span>)</span>
<span id="cb8-4">w_offsets <span class="ot" style="color: #003B4F;
background-color: null;
font-style: inherit;">&lt;-</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">c</span>(<span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">-</span><span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">2</span>, <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">-</span><span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">1</span>, <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">0</span>, <span class="fl" style="color: #AD0000;
background-color: null;
font-style: inherit;">0.5</span>, <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">1</span>, <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">2</span>)</span>
<span id="cb8-5"></span>
<span id="cb8-6">repair_cell <span class="ot" style="color: #003B4F;
background-color: null;
font-style: inherit;">&lt;-</span> <span class="cf" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">function</span>(me_sd, w_rec) {</span>
<span id="cb8-7">  f_raw  <span class="ot" style="color: #003B4F;
background-color: null;
font-style: inherit;">&lt;-</span> <span class="cf" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">function</span>(x) <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">dnorm</span>(w_rec, x, me_sd) <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">*</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">dnorm</span>(x, pop_mu, pop_sd)</span>
<span id="cb8-8">  target <span class="ot" style="color: #003B4F;
background-color: null;
font-style: inherit;">&lt;-</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">dnorm</span>(w_rec, pop_mu, <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">sqrt</span>(pop_sd<span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">^</span><span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">2</span> <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">+</span> me_sd<span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">^</span><span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">2</span>))</span>
<span id="cb8-9">  post_sd <span class="ot" style="color: #003B4F;
background-color: null;
font-style: inherit;">&lt;-</span> <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">1</span> <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">/</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">sqrt</span>(<span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">1</span> <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">/</span> pop_sd<span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">^</span><span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">2</span> <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">+</span> <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">1</span> <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">/</span> me_sd<span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">^</span><span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">2</span>)</span>
<span id="cb8-10">  post_mu <span class="ot" style="color: #003B4F;
background-color: null;
font-style: inherit;">&lt;-</span> post_sd<span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">^</span><span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">2</span> <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">*</span> (w_rec <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">/</span> me_sd<span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">^</span><span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">2</span> <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">+</span> pop_mu <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">/</span> pop_sd<span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">^</span><span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">2</span>)</span>
<span id="cb8-11">  r_sub <span class="ot" style="color: #003B4F;
background-color: null;
font-style: inherit;">&lt;-</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">integrate</span>(<span class="cf" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">function</span>(z) <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">f_raw</span>(pop_mu <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">+</span> pop_sd <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">*</span> z) <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">*</span> pop_sd, <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">-</span><span class="cn" style="color: #8f5902;
background-color: null;
font-style: inherit;">Inf</span>, <span class="cn" style="color: #8f5902;
background-color: null;
font-style: inherit;">Inf</span>,</span>
<span id="cb8-12">                     <span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">stop.on.error =</span> <span class="cn" style="color: #8f5902;
background-color: null;
font-style: inherit;">FALSE</span>)</span>
<span id="cb8-13">  r_fin <span class="ot" style="color: #003B4F;
background-color: null;
font-style: inherit;">&lt;-</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">integrate</span>(f_raw, pop_mu <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">-</span> <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">8</span> <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">*</span> pop_sd, pop_mu <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">+</span> <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">8</span> <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">*</span> pop_sd,</span>
<span id="cb8-14">                     <span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">stop.on.error =</span> <span class="cn" style="color: #8f5902;
background-color: null;
font-style: inherit;">FALSE</span>)</span>
<span id="cb8-15">  r_own <span class="ot" style="color: #003B4F;
background-color: null;
font-style: inherit;">&lt;-</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">integrate</span>(<span class="cf" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">function</span>(z) <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">f_raw</span>(post_mu <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">+</span> post_sd <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">*</span> z) <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">*</span> post_sd,</span>
<span id="cb8-16">                     <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">-</span><span class="cn" style="color: #8f5902;
background-color: null;
font-style: inherit;">Inf</span>, <span class="cn" style="color: #8f5902;
background-color: null;
font-style: inherit;">Inf</span>, <span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">stop.on.error =</span> <span class="cn" style="color: #8f5902;
background-color: null;
font-style: inherit;">FALSE</span>)</span>
<span id="cb8-17">  <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">c</span>(<span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">sub =</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">abs</span>(r_sub<span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">$</span>value <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">/</span> target <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">-</span> <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">1</span>), <span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">fin =</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">abs</span>(r_fin<span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">$</span>value <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">/</span> target <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">-</span> <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">1</span>),</span>
<span id="cb8-18">    <span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">own =</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">abs</span>(r_own<span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">$</span>value <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">/</span> target <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">-</span> <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">1</span>),</span>
<span id="cb8-19">    <span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">msg_ok =</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">all</span>(<span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">c</span>(r_sub<span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">$</span>message, r_fin<span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">$</span>message, r_own<span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">$</span>message) <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">==</span> <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"OK"</span>))</span>
<span id="cb8-20">}</span>
<span id="cb8-21"></span>
<span id="cb8-22">repair_tab <span class="ot" style="color: #003B4F;
background-color: null;
font-style: inherit;">&lt;-</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">do.call</span>(rbind, <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">lapply</span>(me_grid, <span class="cf" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">function</span>(me_sd) {</span>
<span id="cb8-23">  cells <span class="ot" style="color: #003B4F;
background-color: null;
font-style: inherit;">&lt;-</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">vapply</span>(pop_mu <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">+</span> pop_sd <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">*</span> w_offsets,</span>
<span id="cb8-24">                  <span class="cf" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">function</span>(w_rec) <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">repair_cell</span>(me_sd, w_rec), <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">numeric</span>(<span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">4</span>))</span>
<span id="cb8-25">  <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">data.frame</span>(<span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">me_sd =</span> me_sd, <span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">ratio =</span> pop_sd <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">/</span> me_sd,</span>
<span id="cb8-26">             <span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">sub =</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">max</span>(cells[<span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"sub"</span>, ]), <span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">fin =</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">max</span>(cells[<span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"fin"</span>, ]),</span>
<span id="cb8-27">             <span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">own =</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">max</span>(cells[<span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"own"</span>, ]), <span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">all_ok =</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">all</span>(cells[<span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"msg_ok"</span>, ] <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">==</span> <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">1</span>))</span>
<span id="cb8-28">}))</span>
<span id="cb8-29"></span>
<span id="cb8-30">fin_first <span class="ot" style="color: #003B4F;
background-color: null;
font-style: inherit;">&lt;-</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">max</span>(repair_tab<span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">$</span>me_sd[repair_tab<span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">$</span>fin <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">&gt;</span> <span class="fl" style="color: #AD0000;
background-color: null;
font-style: inherit;">0.01</span>])</span>
<span id="cb8-31">sub_first <span class="ot" style="color: #003B4F;
background-color: null;
font-style: inherit;">&lt;-</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">max</span>(repair_tab<span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">$</span>me_sd[repair_tab<span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">$</span>sub <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">&gt;</span> <span class="fl" style="color: #AD0000;
background-color: null;
font-style: inherit;">0.01</span>])</span>
<span id="cb8-32">own_worst <span class="ot" style="color: #003B4F;
background-color: null;
font-style: inherit;">&lt;-</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">max</span>(repair_tab<span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">$</span>own)</span>
<span id="cb8-33">repair_all_ok <span class="ot" style="color: #003B4F;
background-color: null;
font-style: inherit;">&lt;-</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">all</span>(repair_tab<span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">$</span>all_ok)</span>
<span id="cb8-34">fin_ratio <span class="ot" style="color: #003B4F;
background-color: null;
font-style: inherit;">&lt;-</span> pop_sd <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">/</span> fin_first</span>
<span id="cb8-35">sub_ratio <span class="ot" style="color: #003B4F;
background-color: null;
font-style: inherit;">&lt;-</span> pop_sd <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">/</span> sub_first</span></code></pre></div></div>
</div>
<p>With a population sd of 15 mm, the finite limits first miss by more than 1 per cent at a measurement error of 1.0 mm, a population-to-error ratio of 15. The prior-centred substitution survives a little longer and first fails at 0.7 mm, a ratio of 21.4. The two are one step apart on this grid, and which goes first depends on the 8 sd width and on the recorded lengths tried, so the order is no ranking of the two. Below that both return essentially nothing. Centring and scaling on the integrand’s own location and width is exact to a worst relative error of <img src="https://latex.codecogs.com/png.latex?2.06%20%5Ctimes%2010%5E%7B-10%7D"> across the whole range, including a measurement error of 0.10 mm. With <code>stop.on.error = FALSE</code> again, the message was <code>"OK"</code> in every one of these calls, failures included (the check over all of them returns TRUE).</p>
<p>So the answer to which repair to recommend is neither of the two usual ones. Both borrow their location and scale from the population, and both fail once the measurement is precise enough that one fish’s integrand is much narrower than the population it came from. A calliper error of a millimetre on fish that vary by 15 mm is enough to break the finite limits. The repair that holds is to put the routine’s origin on the integrand’s own centre and its unit on the integrand’s own width. For the Gaussian part of this model both are available in closed form, and the logistic term only tilts the integrand gently on the scale of one over the slope; for a model where they are not, a few Newton steps to the mode of each integrand give them.</p>
<div class="cell">
<div class="code-copy-outer-scaffold"><div class="sourceCode cell-code" id="cb9" style="background: #f1f3f5;"><pre class="sourceCode r code-with-copy"><code class="sourceCode r"><span id="cb9-1">err_floor <span class="ot" style="color: #003B4F;
background-color: null;
font-style: inherit;">&lt;-</span> <span class="fl" style="color: #AD0000;
background-color: null;
font-style: inherit;">1e-14</span></span>
<span id="cb9-2">repair_long <span class="ot" style="color: #003B4F;
background-color: null;
font-style: inherit;">&lt;-</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">rbind</span>(</span>
<span id="cb9-3">  <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">data.frame</span>(<span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">ratio =</span> repair_tab<span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">$</span>ratio, <span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">err =</span> repair_tab<span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">$</span>fin,</span>
<span id="cb9-4">             <span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">route =</span> <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"finite limits at population mean +/- 8 sd"</span>),</span>
<span id="cb9-5">  <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">data.frame</span>(<span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">ratio =</span> repair_tab<span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">$</span>ratio, <span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">err =</span> repair_tab<span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">$</span>sub,</span>
<span id="cb9-6">             <span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">route =</span> <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"substitution on the population scale"</span>),</span>
<span id="cb9-7">  <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">data.frame</span>(<span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">ratio =</span> repair_tab<span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">$</span>ratio, <span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">err =</span> repair_tab<span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">$</span>own,</span>
<span id="cb9-8">             <span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">route =</span> <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"substitution on the integrand's own scale"</span>))</span>
<span id="cb9-9">repair_long<span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">$</span>err <span class="ot" style="color: #003B4F;
background-color: null;
font-style: inherit;">&lt;-</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">pmax</span>(repair_long<span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">$</span>err, err_floor)</span>
<span id="cb9-10"></span>
<span id="cb9-11"><span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">ggplot</span>(repair_long, <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">aes</span>(ratio, err, <span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">colour =</span> route)) <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">+</span></span>
<span id="cb9-12">  <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">geom_hline</span>(<span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">yintercept =</span> <span class="fl" style="color: #AD0000;
background-color: null;
font-style: inherit;">0.01</span>, <span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">linetype =</span> <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"dashed"</span>, <span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">colour =</span> te_body,</span>
<span id="cb9-13">             <span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">linewidth =</span> <span class="fl" style="color: #AD0000;
background-color: null;
font-style: inherit;">0.5</span>) <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">+</span></span>
<span id="cb9-14">  <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">geom_line</span>(<span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">linewidth =</span> <span class="fl" style="color: #AD0000;
background-color: null;
font-style: inherit;">0.9</span>) <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">+</span></span>
<span id="cb9-15">  <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">geom_point</span>(<span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">size =</span> <span class="fl" style="color: #AD0000;
background-color: null;
font-style: inherit;">2.2</span>) <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">+</span></span>
<span id="cb9-16">  <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">scale_x_log10</span>() <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">+</span></span>
<span id="cb9-17">  <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">scale_y_log10</span>(<span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">breaks =</span> <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">10</span><span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">^</span><span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">c</span>(<span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">-</span><span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">14</span>, <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">-</span><span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">10</span>, <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">-</span><span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">6</span>, <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">-</span><span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">2</span>, <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">0</span>),</span>
<span id="cb9-18">                <span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">labels =</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">expression</span>(<span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">10</span><span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">^-</span><span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">14</span>, <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">10</span><span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">^-</span><span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">10</span>, <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">10</span><span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">^-</span><span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">6</span>, <span class="fl" style="color: #AD0000;
background-color: null;
font-style: inherit;">0.01</span>, <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">1</span>)) <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">+</span></span>
<span id="cb9-19">  <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">scale_colour_manual</span>(<span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">values =</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">c</span>(te_rust, te_gold, te_forest), <span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">name =</span> <span class="cn" style="color: #8f5902;
background-color: null;
font-style: inherit;">NULL</span>) <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">+</span></span>
<span id="cb9-20">  <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">guides</span>(<span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">colour =</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">guide_legend</span>(<span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">ncol =</span> <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">1</span>)) <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">+</span></span>
<span id="cb9-21">  <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">labs</span>(<span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">x =</span> <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"population sd / measurement error sd (log scale)"</span>,</span>
<span id="cb9-22">       <span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">y =</span> <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"worst relative error (log scale)"</span>,</span>
<span id="cb9-23">       <span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">title =</span> <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"Borrowed scales fail as measurement sharpens"</span>,</span>
<span id="cb9-24">       <span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">subtitle =</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">expression</span>(<span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"dashed: 1 per cent; errors below "</span> <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">*</span> <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">10</span><span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">^-</span><span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">14</span> <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">*</span> <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">" drawn at the floor"</span>)) <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">+</span></span>
<span id="cb9-25">  <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">theme_datasheet</span>() <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">+</span></span>
<span id="cb9-26">  <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">theme</span>(<span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">legend.position =</span> <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"bottom"</span>)</span></code></pre></div></div>
<div class="cell-output-display">
<div id="fig-repairs" class="quarto-float quarto-figure quarto-figure-center anchored" alt="A line chart on warm off-white paper. The horizontal axis is the population sd divided by the measurement error sd on a log scale from about 2 to 150; the vertical axis is the worst relative error on a log scale from 10 to the minus 10 up to 1, with a dashed line at 0.01. A gold line for substitution on the integrand's own scale runs flat near 2 times 10 to the minus 10 across the whole range. A dark green line for substitution on the population scale stays between about 4 times 10 to the minus 11 and 3 times 10 to the minus 8 up to a ratio of 15, then jumps to 1 at a ratio of about 21 and stays there. A red line for finite limits at the population mean plus or minus 8 sd stays below 10 to the minus 6 up to a ratio of about 11 and jumps to 1 at 15.">
<figure class="quarto-float quarto-float-fig figure">
<div aria-describedby="fig-repairs-caption-0ceaefa1-69ba-4598-a22c-09a6ac19f8ca">
<img src="https://tidyecology.com/posts/when-integrate-returns-zero/index_files/figure-html/fig-repairs-1.png" class="img-fluid figure-img" alt="A line chart on warm off-white paper. The horizontal axis is the population sd divided by the measurement error sd on a log scale from about 2 to 150; the vertical axis is the worst relative error on a log scale from 10 to the minus 10 up to 1, with a dashed line at 0.01. A gold line for substitution on the integrand's own scale runs flat near 2 times 10 to the minus 10 across the whole range. A dark green line for substitution on the population scale stays between about 4 times 10 to the minus 11 and 3 times 10 to the minus 8 up to a ratio of 15, then jumps to 1 at a ratio of about 21 and stays there. A red line for finite limits at the population mean plus or minus 8 sd stays below 10 to the minus 6 up to a ratio of about 11 and jumps to 1 at 15." width="672">
</div>
<figcaption class="quarto-float-caption-bottom quarto-float-caption quarto-float-fig" id="fig-repairs-caption-0ceaefa1-69ba-4598-a22c-09a6ac19f8ca">
Figure&nbsp;3: Worst relative error over six recorded lengths for three ways of computing one fish’s likelihood integral, as the measurement error shrinks against a population sd of 15 mm.
</figcaption>
</figure>
</div>
</div>
</div>
</section>
<section id="a-likelihood-the-failure-breaks" class="level2">
<h2 id="a-likelihood-the-failure-breaks-h" class="anchored" data-anchor-id="a-likelihood-the-failure-breaks">A likelihood the failure breaks</h2>
<p>A failure map on its own is a curiosity. The question for an analysis is whether the misses survive into an estimate, and the only fair way to ask it is to fit the same data twice. Two independent sets of simulations, one per route, would bury a difference of this kind under sampling noise; fitting both routes to the same dataset from the same start differences that noise out, so the comparison below is paired throughout.</p>
<p>The model is classical measurement error in body length. True length x is normal with mean mu and sd sx in millimetres, the recorded length is w, x plus normal error with sd su, and maturity follows a logistic regression on centred true length with intercept -0.4 and slope 0.08 per mm, for 180 fish. The likelihood for one fish integrates the logistic probability of its maturity state, times the measurement kernel, times the population density, over true length; the population parameters and su are treated as known so that only the intercept and slope are estimated, which keeps the computation the only thing that differs. The raw route integrates over x in millimetres from minus to plus infinity. The standardised route integrates the same function over z, with x equal to mu plus sx times z. Both are minimised by Nelder-Mead from the start (0, 0) with the same control settings, and a naive logistic regression on the recorded length is carried along as the reference the integral exists to improve on. The regimes and the 25 datasets per regime, with their seeds, were fixed before anything ran.</p>
<div class="cell">
<div class="code-copy-outer-scaffold"><div class="sourceCode cell-code" id="cb10" style="background: #f1f3f5;"><pre class="sourceCode r code-with-copy"><code class="sourceCode r"><span id="cb10-1">n_fish  <span class="ot" style="color: #003B4F;
background-color: null;
font-style: inherit;">&lt;-</span> <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">180</span></span>
<span id="cb10-2">b0_true <span class="ot" style="color: #003B4F;
background-color: null;
font-style: inherit;">&lt;-</span> <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">-</span><span class="fl" style="color: #AD0000;
background-color: null;
font-style: inherit;">0.4</span></span>
<span id="cb10-3">b1_true <span class="ot" style="color: #003B4F;
background-color: null;
font-style: inherit;">&lt;-</span> <span class="fl" style="color: #AD0000;
background-color: null;
font-style: inherit;">0.08</span></span>
<span id="cb10-4">n_rep   <span class="ot" style="color: #003B4F;
background-color: null;
font-style: inherit;">&lt;-</span> <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">25</span></span>
<span id="cb10-5">regimes <span class="ot" style="color: #003B4F;
background-color: null;
font-style: inherit;">&lt;-</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">data.frame</span>(<span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">mu =</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">c</span>(<span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">420</span>, <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">420</span>, <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">250</span>), <span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">sx =</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">c</span>(<span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">15</span>, <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">25</span>, <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">20</span>),</span>
<span id="cb10-6">                      <span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">su =</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">c</span>(<span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">8</span>, <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">10</span>, <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">12</span>))</span>
<span id="cb10-7">regimes<span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">$</span>label <span class="ot" style="color: #003B4F;
background-color: null;
font-style: inherit;">&lt;-</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">sprintf</span>(<span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"mean %g, sd %g, error %g mm"</span>,</span>
<span id="cb10-8">                         regimes<span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">$</span>mu, regimes<span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">$</span>sx, regimes<span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">$</span>su)</span>
<span id="cb10-9">nm_control <span class="ot" style="color: #003B4F;
background-color: null;
font-style: inherit;">&lt;-</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">list</span>(<span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">maxit =</span> <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">220</span>, <span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">reltol =</span> <span class="fl" style="color: #AD0000;
background-color: null;
font-style: inherit;">1e-9</span>)</span>
<span id="cb10-10"></span>
<span id="cb10-11">fit_pair <span class="ot" style="color: #003B4F;
background-color: null;
font-style: inherit;">&lt;-</span> <span class="cf" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">function</span>(seed, mu_x, sx, su, <span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">own_only =</span> <span class="cn" style="color: #8f5902;
background-color: null;
font-style: inherit;">FALSE</span>) {</span>
<span id="cb10-12">  <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">set.seed</span>(seed)</span>
<span id="cb10-13">  x_true <span class="ot" style="color: #003B4F;
background-color: null;
font-style: inherit;">&lt;-</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">rnorm</span>(n_fish, mu_x, sx)</span>
<span id="cb10-14">  w_rec  <span class="ot" style="color: #003B4F;
background-color: null;
font-style: inherit;">&lt;-</span> x_true <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">+</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">rnorm</span>(n_fish, <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">0</span>, su)</span>
<span id="cb10-15">  y_mat  <span class="ot" style="color: #003B4F;
background-color: null;
font-style: inherit;">&lt;-</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">rbinom</span>(n_fish, <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">1</span>, <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">plogis</span>(b0_true <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">+</span> b1_true <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">*</span> (x_true <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">-</span> mu_x)))</span>
<span id="cb10-16">  sgn    <span class="ot" style="color: #003B4F;
background-color: null;
font-style: inherit;">&lt;-</span> <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">2</span> <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">*</span> y_mat <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">-</span> <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">1</span></span>
<span id="cb10-17">  post_sd <span class="ot" style="color: #003B4F;
background-color: null;
font-style: inherit;">&lt;-</span> <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">1</span> <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">/</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">sqrt</span>(<span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">1</span> <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">/</span> sx<span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">^</span><span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">2</span> <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">+</span> <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">1</span> <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">/</span> su<span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">^</span><span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">2</span>)</span>
<span id="cb10-18">  post_mu <span class="ot" style="color: #003B4F;
background-color: null;
font-style: inherit;">&lt;-</span> post_sd<span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">^</span><span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">2</span> <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">*</span> (w_rec <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">/</span> su<span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">^</span><span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">2</span> <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">+</span> mu_x <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">/</span> sx<span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">^</span><span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">2</span>)</span>
<span id="cb10-19"></span>
<span id="cb10-20">  obs_int <span class="ot" style="color: #003B4F;
background-color: null;
font-style: inherit;">&lt;-</span> <span class="cf" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">function</span>(th, i, route, <span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">soe =</span> <span class="cn" style="color: #8f5902;
background-color: null;
font-style: inherit;">TRUE</span>) {</span>
<span id="cb10-21">    kern <span class="ot" style="color: #003B4F;
background-color: null;
font-style: inherit;">&lt;-</span> <span class="cf" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">function</span>(xx) <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">plogis</span>(sgn[i] <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">*</span> (th[<span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">1</span>] <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">+</span> th[<span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">2</span>] <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">*</span> (xx <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">-</span> mu_x))) <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">*</span></span>
<span id="cb10-22">      <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">dnorm</span>(w_rec[i], xx, su) <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">*</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">dnorm</span>(xx, mu_x, sx)</span>
<span id="cb10-23">    <span class="cf" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">if</span> (route <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">==</span> <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"raw"</span>) {</span>
<span id="cb10-24">      <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">integrate</span>(kern, <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">-</span><span class="cn" style="color: #8f5902;
background-color: null;
font-style: inherit;">Inf</span>, <span class="cn" style="color: #8f5902;
background-color: null;
font-style: inherit;">Inf</span>, <span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">stop.on.error =</span> soe)</span>
<span id="cb10-25">    } <span class="cf" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">else</span> <span class="cf" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">if</span> (route <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">==</span> <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"std"</span>) {</span>
<span id="cb10-26">      <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">integrate</span>(<span class="cf" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">function</span>(z) <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">kern</span>(mu_x <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">+</span> sx <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">*</span> z) <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">*</span> sx, <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">-</span><span class="cn" style="color: #8f5902;
background-color: null;
font-style: inherit;">Inf</span>, <span class="cn" style="color: #8f5902;
background-color: null;
font-style: inherit;">Inf</span>,</span>
<span id="cb10-27">                <span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">stop.on.error =</span> soe)</span>
<span id="cb10-28">    } <span class="cf" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">else</span> {</span>
<span id="cb10-29">      <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">integrate</span>(<span class="cf" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">function</span>(z) <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">kern</span>(post_mu[i] <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">+</span> post_sd <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">*</span> z) <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">*</span> post_sd,</span>
<span id="cb10-30">                <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">-</span><span class="cn" style="color: #8f5902;
background-color: null;
font-style: inherit;">Inf</span>, <span class="cn" style="color: #8f5902;
background-color: null;
font-style: inherit;">Inf</span>, <span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">stop.on.error =</span> soe)</span>
<span id="cb10-31">    }</span>
<span id="cb10-32">  }</span>
<span id="cb10-33">  all_int <span class="ot" style="color: #003B4F;
background-color: null;
font-style: inherit;">&lt;-</span> <span class="cf" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">function</span>(th, route) {</span>
<span id="cb10-34">    <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">vapply</span>(<span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">seq_len</span>(n_fish), <span class="cf" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">function</span>(i) <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">obs_int</span>(th, i, route)<span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">$</span>value, <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">0</span>)</span>
<span id="cb10-35">  }</span>
<span id="cb10-36">  <span class="co" style="color: #5E5E5E;
background-color: null;
font-style: inherit;"># value, reported abs.error and message per fish, with failures that the</span></span>
<span id="cb10-37">  <span class="co" style="color: #5E5E5E;
background-color: null;
font-style: inherit;"># routine detects returned as messages instead of errors</span></span>
<span id="cb10-38">  int_detail <span class="ot" style="color: #003B4F;
background-color: null;
font-style: inherit;">&lt;-</span> <span class="cf" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">function</span>(th, route) {</span>
<span id="cb10-39">    <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">t</span>(<span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">vapply</span>(<span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">seq_len</span>(n_fish), <span class="cf" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">function</span>(i) {</span>
<span id="cb10-40">      r <span class="ot" style="color: #003B4F;
background-color: null;
font-style: inherit;">&lt;-</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">obs_int</span>(th, i, route, <span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">soe =</span> <span class="cn" style="color: #8f5902;
background-color: null;
font-style: inherit;">FALSE</span>)</span>
<span id="cb10-41">      <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">c</span>(<span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">value =</span> r<span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">$</span>value, <span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">abs_err =</span> r<span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">$</span>abs.error, <span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">ok =</span> r<span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">$</span>message <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">==</span> <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"OK"</span>)</span>
<span id="cb10-42">    }, <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">numeric</span>(<span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">3</span>)))</span>
<span id="cb10-43">  }</span>
<span id="cb10-44">  err_flag <span class="ot" style="color: #003B4F;
background-color: null;
font-style: inherit;">&lt;-</span> <span class="cf" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">function</span>(d) <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">mean</span>(d[, <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"value"</span>] <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">==</span> <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">0</span> <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">|</span> d[, <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"abs_err"</span>] <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">&gt;</span> <span class="fl" style="color: #AD0000;
background-color: null;
font-style: inherit;">0.01</span> <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">*</span> d[, <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"value"</span>])</span>
<span id="cb10-45">  nll <span class="ot" style="color: #003B4F;
background-color: null;
font-style: inherit;">&lt;-</span> <span class="cf" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">function</span>(th, route) <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">-</span><span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">sum</span>(<span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">log</span>(<span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">pmax</span>(<span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">all_int</span>(th, route), <span class="fl" style="color: #AD0000;
background-color: null;
font-style: inherit;">1e-300</span>)))</span>
<span id="cb10-46"></span>
<span id="cb10-47">  <span class="cf" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">if</span> (own_only) {</span>
<span id="cb10-48">    fit_own <span class="ot" style="color: #003B4F;
background-color: null;
font-style: inherit;">&lt;-</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">optim</span>(<span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">c</span>(<span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">0</span>, <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">0</span>), nll, <span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">route =</span> <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"own"</span>, <span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">method =</span> <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"Nelder-Mead"</span>,</span>
<span id="cb10-49">                     <span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">control =</span> nm_control)</span>
<span id="cb10-50">    <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">return</span>(fit_own<span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">$</span>par[<span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">2</span>])</span>
<span id="cb10-51">  }</span>
<span id="cb10-52">  fit_std <span class="ot" style="color: #003B4F;
background-color: null;
font-style: inherit;">&lt;-</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">optim</span>(<span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">c</span>(<span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">0</span>, <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">0</span>), nll, <span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">route =</span> <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"std"</span>, <span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">method =</span> <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"Nelder-Mead"</span>,</span>
<span id="cb10-53">                   <span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">control =</span> nm_control)</span>
<span id="cb10-54">  fit_raw <span class="ot" style="color: #003B4F;
background-color: null;
font-style: inherit;">&lt;-</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">optim</span>(<span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">c</span>(<span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">0</span>, <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">0</span>), nll, <span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">route =</span> <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"raw"</span>, <span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">method =</span> <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"Nelder-Mead"</span>,</span>
<span id="cb10-55">                   <span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">control =</span> nm_control)</span>
<span id="cb10-56">  naive <span class="ot" style="color: #003B4F;
background-color: null;
font-style: inherit;">&lt;-</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">unname</span>(<span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">coef</span>(<span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">glm</span>(y_mat <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">~</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">I</span>(w_rec <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">-</span> mu_x), <span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">family =</span> binomial))[<span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">2</span>])</span>
<span id="cb10-57"></span>
<span id="cb10-58">  det_raw <span class="ot" style="color: #003B4F;
background-color: null;
font-style: inherit;">&lt;-</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">int_detail</span>(fit_raw<span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">$</span>par, <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"raw"</span>)</span>
<span id="cb10-59">  det_std <span class="ot" style="color: #003B4F;
background-color: null;
font-style: inherit;">&lt;-</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">int_detail</span>(fit_std<span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">$</span>par, <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"std"</span>)</span>
<span id="cb10-60">  int_raw_fit <span class="ot" style="color: #003B4F;
background-color: null;
font-style: inherit;">&lt;-</span> det_raw[, <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"value"</span>]</span>
<span id="cb10-61">  int_own_fit <span class="ot" style="color: #003B4F;
background-color: null;
font-style: inherit;">&lt;-</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">all_int</span>(fit_raw<span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">$</span>par, <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"own"</span>)</span>
<span id="cb10-62">  <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">c</span>(<span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">raw =</span> fit_raw<span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">$</span>par[<span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">2</span>], <span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">std =</span> fit_std<span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">$</span>par[<span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">2</span>], <span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">naive =</span> naive,</span>
<span id="cb10-63">    <span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">conv_raw =</span> fit_raw<span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">$</span>convergence, <span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">conv_std =</span> fit_std<span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">$</span>convergence,</span>
<span id="cb10-64">    <span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">zero_share =</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">mean</span>(int_raw_fit <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">==</span> <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">0</span>),</span>
<span id="cb10-65">    <span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">log10_ratio =</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">median</span>(<span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">log10</span>(<span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">pmax</span>(int_raw_fit, <span class="fl" style="color: #AD0000;
background-color: null;
font-style: inherit;">1e-300</span>) <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">/</span> int_own_fit)),</span>
<span id="cb10-66">    <span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">gap_raw =</span> fit_raw<span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">$</span>value <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">+</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">sum</span>(<span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">log</span>(<span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">pmax</span>(int_own_fit, <span class="fl" style="color: #AD0000;
background-color: null;
font-style: inherit;">1e-300</span>))),</span>
<span id="cb10-67">    <span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">gap_std =</span> fit_std<span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">$</span>value <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">-</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">nll</span>(fit_std<span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">$</span>par, <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"own"</span>),</span>
<span id="cb10-68">    <span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">ok_share =</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">mean</span>(det_raw[, <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"ok"</span>]),</span>
<span id="cb10-69">    <span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">flag_raw =</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">err_flag</span>(det_raw), <span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">flag_std =</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">err_flag</span>(det_std))</span>
<span id="cb10-70">}</span>
<span id="cb10-71"></span>
<span id="cb10-72">pair_res <span class="ot" style="color: #003B4F;
background-color: null;
font-style: inherit;">&lt;-</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">do.call</span>(rbind, <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">lapply</span>(<span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">seq_len</span>(<span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">nrow</span>(regimes)), <span class="cf" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">function</span>(k) {</span>
<span id="cb10-73">  out <span class="ot" style="color: #003B4F;
background-color: null;
font-style: inherit;">&lt;-</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">t</span>(<span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">vapply</span>(<span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">1000</span> <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">*</span> k <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">+</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">seq_len</span>(n_rep), fit_pair, <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">numeric</span>(<span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">12</span>),</span>
<span id="cb10-74">                  <span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">mu_x =</span> regimes<span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">$</span>mu[k], <span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">sx =</span> regimes<span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">$</span>sx[k],</span>
<span id="cb10-75">                  <span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">su =</span> regimes<span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">$</span>su[k]))</span>
<span id="cb10-76">  <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">data.frame</span>(<span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">regime =</span> regimes<span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">$</span>label[k], <span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">dataset =</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">seq_len</span>(n_rep), out)</span>
<span id="cb10-77">}))</span>
<span id="cb10-78">pair_res<span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">$</span>regime <span class="ot" style="color: #003B4F;
background-color: null;
font-style: inherit;">&lt;-</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">factor</span>(pair_res<span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">$</span>regime, <span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">levels =</span> regimes<span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">$</span>label)</span>
<span id="cb10-79">pair_res<span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">$</span>rel_diff <span class="ot" style="color: #003B4F;
background-color: null;
font-style: inherit;">&lt;-</span> (pair_res<span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">$</span>raw <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">-</span> pair_res<span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">$</span>std) <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">/</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">abs</span>(pair_res<span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">$</span>std)</span>
<span id="cb10-80">pair_res<span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">$</span>naive_closer <span class="ot" style="color: #003B4F;
background-color: null;
font-style: inherit;">&lt;-</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">abs</span>(pair_res<span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">$</span>naive <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">-</span> pair_res<span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">$</span>std) <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">&lt;</span></span>
<span id="cb10-81">  <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">abs</span>(pair_res<span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">$</span>raw <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">-</span> pair_res<span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">$</span>std)</span>
<span id="cb10-82"></span>
<span id="cb10-83">by_regime <span class="ot" style="color: #003B4F;
background-color: null;
font-style: inherit;">&lt;-</span> <span class="cf" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">function</span>(v, fun) <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">as.numeric</span>(<span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">tapply</span>(v, pair_res<span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">$</span>regime, fun))</span>
<span id="cb10-84">med_raw   <span class="ot" style="color: #003B4F;
background-color: null;
font-style: inherit;">&lt;-</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">by_regime</span>(pair_res<span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">$</span>raw, median)</span>
<span id="cb10-85">min_raw   <span class="ot" style="color: #003B4F;
background-color: null;
font-style: inherit;">&lt;-</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">by_regime</span>(pair_res<span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">$</span>raw, min)</span>
<span id="cb10-86">max_raw   <span class="ot" style="color: #003B4F;
background-color: null;
font-style: inherit;">&lt;-</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">by_regime</span>(pair_res<span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">$</span>raw, max)</span>
<span id="cb10-87">med_std   <span class="ot" style="color: #003B4F;
background-color: null;
font-style: inherit;">&lt;-</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">by_regime</span>(pair_res<span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">$</span>std, median)</span>
<span id="cb10-88">med_naive <span class="ot" style="color: #003B4F;
background-color: null;
font-style: inherit;">&lt;-</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">by_regime</span>(pair_res<span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">$</span>naive, median)</span>
<span id="cb10-89">med_rel   <span class="ot" style="color: #003B4F;
background-color: null;
font-style: inherit;">&lt;-</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">by_regime</span>(pair_res<span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">$</span>rel_diff, median)</span>
<span id="cb10-90">med_abs_rel <span class="ot" style="color: #003B4F;
background-color: null;
font-style: inherit;">&lt;-</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">by_regime</span>(<span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">abs</span>(pair_res<span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">$</span>rel_diff), median)</span>
<span id="cb10-91">share_big <span class="ot" style="color: #003B4F;
background-color: null;
font-style: inherit;">&lt;-</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">by_regime</span>(<span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">abs</span>(pair_res<span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">$</span>rel_diff) <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">&gt;</span> <span class="fl" style="color: #AD0000;
background-color: null;
font-style: inherit;">0.30</span>, mean)</span>
<span id="cb10-92">n_big     <span class="ot" style="color: #003B4F;
background-color: null;
font-style: inherit;">&lt;-</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">by_regime</span>(<span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">abs</span>(pair_res<span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">$</span>rel_diff) <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">&gt;</span> <span class="fl" style="color: #AD0000;
background-color: null;
font-style: inherit;">0.30</span>, sum)</span>
<span id="cb10-93"><span class="co" style="color: #5E5E5E;
background-color: null;
font-style: inherit;"># exact bootstrap percentile interval for a median of an odd number of</span></span>
<span id="cb10-94"><span class="co" style="color: #5E5E5E;
background-color: null;
font-style: inherit;"># values: the resampled median is at most v[k] when at least (n + 1) / 2 of</span></span>
<span id="cb10-95"><span class="co" style="color: #5E5E5E;
background-color: null;
font-style: inherit;"># the n draws are, a binomial count with probability k / n</span></span>
<span id="cb10-96">boot_ci <span class="ot" style="color: #003B4F;
background-color: null;
font-style: inherit;">&lt;-</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">vapply</span>(<span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">levels</span>(pair_res<span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">$</span>regime), <span class="cf" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">function</span>(r) {</span>
<span id="cb10-97">  v <span class="ot" style="color: #003B4F;
background-color: null;
font-style: inherit;">&lt;-</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">sort</span>(<span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">abs</span>(pair_res<span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">$</span>rel_diff[pair_res<span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">$</span>regime <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">==</span> r]))</span>
<span id="cb10-98">  n <span class="ot" style="color: #003B4F;
background-color: null;
font-style: inherit;">&lt;-</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">length</span>(v)</span>
<span id="cb10-99">  cdf <span class="ot" style="color: #003B4F;
background-color: null;
font-style: inherit;">&lt;-</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">pbinom</span>((n <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">-</span> <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">1</span>) <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">/</span> <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">2</span>, n, <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">seq_len</span>(n) <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">/</span> n, <span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">lower.tail =</span> <span class="cn" style="color: #8f5902;
background-color: null;
font-style: inherit;">FALSE</span>)</span>
<span id="cb10-100">  <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">c</span>(v[<span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">which</span>(cdf <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">&gt;=</span> <span class="fl" style="color: #AD0000;
background-color: null;
font-style: inherit;">0.025</span>)[<span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">1</span>]], v[<span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">which</span>(cdf <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">&gt;=</span> <span class="fl" style="color: #AD0000;
background-color: null;
font-style: inherit;">0.975</span>)[<span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">1</span>]])</span>
<span id="cb10-101">}, <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">numeric</span>(<span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">2</span>))</span>
<span id="cb10-102">conv_raw  <span class="ot" style="color: #003B4F;
background-color: null;
font-style: inherit;">&lt;-</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">by_regime</span>(pair_res<span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">$</span>conv_raw <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">==</span> <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">0</span>, mean)</span>
<span id="cb10-103">n_maxit   <span class="ot" style="color: #003B4F;
background-color: null;
font-style: inherit;">&lt;-</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">by_regime</span>(pair_res<span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">$</span>conv_raw <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">==</span> <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">1</span>, sum)</span>
<span id="cb10-104">flag_raw_med <span class="ot" style="color: #003B4F;
background-color: null;
font-style: inherit;">&lt;-</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">by_regime</span>(pair_res<span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">$</span>flag_raw, median)</span>
<span id="cb10-105">flag_std_med <span class="ot" style="color: #003B4F;
background-color: null;
font-style: inherit;">&lt;-</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">by_regime</span>(pair_res<span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">$</span>flag_std, median)</span>
<span id="cb10-106">flag_std_max <span class="ot" style="color: #003B4F;
background-color: null;
font-style: inherit;">&lt;-</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">max</span>(pair_res<span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">$</span>flag_std)</span>
<span id="cb10-107">conv_std  <span class="ot" style="color: #003B4F;
background-color: null;
font-style: inherit;">&lt;-</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">by_regime</span>(pair_res<span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">$</span>conv_std <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">==</span> <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">0</span>, mean)</span>
<span id="cb10-108">neg_raw   <span class="ot" style="color: #003B4F;
background-color: null;
font-style: inherit;">&lt;-</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">by_regime</span>(pair_res<span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">$</span>raw <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">&lt;</span> <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">0</span>, sum)</span>
<span id="cb10-109">naive_win <span class="ot" style="color: #003B4F;
background-color: null;
font-style: inherit;">&lt;-</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">by_regime</span>(pair_res<span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">$</span>naive_closer, mean)</span>
<span id="cb10-110">zero_med  <span class="ot" style="color: #003B4F;
background-color: null;
font-style: inherit;">&lt;-</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">by_regime</span>(pair_res<span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">$</span>zero_share, median)</span>
<span id="cb10-111">ratio_med <span class="ot" style="color: #003B4F;
background-color: null;
font-style: inherit;">&lt;-</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">by_regime</span>(pair_res<span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">$</span>log10_ratio, median)</span>
<span id="cb10-112">gap_raw_med <span class="ot" style="color: #003B4F;
background-color: null;
font-style: inherit;">&lt;-</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">by_regime</span>(pair_res<span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">$</span>gap_raw, median)</span>
<span id="cb10-113">gap_raw_min <span class="ot" style="color: #003B4F;
background-color: null;
font-style: inherit;">&lt;-</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">min</span>(pair_res<span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">$</span>gap_raw)</span>
<span id="cb10-114">gap_std_max <span class="ot" style="color: #003B4F;
background-color: null;
font-style: inherit;">&lt;-</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">max</span>(<span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">abs</span>(pair_res<span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">$</span>gap_std))</span>
<span id="cb10-115">gap_std_med <span class="ot" style="color: #003B4F;
background-color: null;
font-style: inherit;">&lt;-</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">median</span>(<span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">abs</span>(pair_res<span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">$</span>gap_std))</span>
<span id="cb10-116">gap_fold <span class="ot" style="color: #003B4F;
background-color: null;
font-style: inherit;">&lt;-</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">log10</span>(gap_raw_min <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">/</span> gap_std_max)</span>
<span id="cb10-117">n_big_regimes <span class="ot" style="color: #003B4F;
background-color: null;
font-style: inherit;">&lt;-</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">sum</span>(med_abs_rel <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">&gt;</span> <span class="fl" style="color: #AD0000;
background-color: null;
font-style: inherit;">0.30</span>)</span>
<span id="cb10-118">n_own <span class="ot" style="color: #003B4F;
background-color: null;
font-style: inherit;">&lt;-</span> <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">3</span></span>
<span id="cb10-119"><span class="co" style="color: #5E5E5E;
background-color: null;
font-style: inherit;"># refit the integrand-centred route only; the standardised slopes of the</span></span>
<span id="cb10-120"><span class="co" style="color: #5E5E5E;
background-color: null;
font-style: inherit;"># same datasets are already in pair_res</span></span>
<span id="cb10-121">own_check <span class="ot" style="color: #003B4F;
background-color: null;
font-style: inherit;">&lt;-</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">do.call</span>(rbind, <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">lapply</span>(<span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">seq_len</span>(<span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">nrow</span>(regimes)), <span class="cf" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">function</span>(k) {</span>
<span id="cb10-122">  own <span class="ot" style="color: #003B4F;
background-color: null;
font-style: inherit;">&lt;-</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">vapply</span>(<span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">1000</span> <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">*</span> k <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">+</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">seq_len</span>(n_own), fit_pair, <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">0</span>,</span>
<span id="cb10-123">                <span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">mu_x =</span> regimes<span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">$</span>mu[k], <span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">sx =</span> regimes<span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">$</span>sx[k], <span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">su =</span> regimes<span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">$</span>su[k],</span>
<span id="cb10-124">                <span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">own_only =</span> <span class="cn" style="color: #8f5902;
background-color: null;
font-style: inherit;">TRUE</span>)</span>
<span id="cb10-125">  <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">cbind</span>(<span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">std =</span> pair_res<span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">$</span>std[<span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">as.integer</span>(pair_res<span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">$</span>regime) <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">==</span> k <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">&amp;</span></span>
<span id="cb10-126">                             pair_res<span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">$</span>dataset <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">&lt;=</span> n_own], <span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">own =</span> own)</span>
<span id="cb10-127">}))</span>
<span id="cb10-128">own_rel_max <span class="ot" style="color: #003B4F;
background-color: null;
font-style: inherit;">&lt;-</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">max</span>(<span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">abs</span>(own_check[, <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"std"</span>] <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">-</span> own_check[, <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"own"</span>]) <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">/</span></span>
<span id="cb10-129">                     <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">abs</span>(own_check[, <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"own"</span>]))</span>
<span id="cb10-130">ok_share_min <span class="ot" style="color: #003B4F;
background-color: null;
font-style: inherit;">&lt;-</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">min</span>(pair_res<span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">$</span>ok_share)</span>
<span id="cb10-131">ratio_lo <span class="ot" style="color: #003B4F;
background-color: null;
font-style: inherit;">&lt;-</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">min</span>(regimes<span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">$</span>sx <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">/</span> regimes<span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">$</span>su)</span>
<span id="cb10-132">ratio_hi <span class="ot" style="color: #003B4F;
background-color: null;
font-style: inherit;">&lt;-</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">max</span>(regimes<span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">$</span>sx <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">/</span> regimes<span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">$</span>su)</span>
<span id="cb10-133"></span>
<span id="cb10-134">canary <span class="ot" style="color: #003B4F;
background-color: null;
font-style: inherit;">&lt;-</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">vapply</span>(<span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">seq_len</span>(<span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">nrow</span>(regimes)), <span class="cf" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">function</span>(k)</span>
<span id="cb10-135">  <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">integrate</span>(dnorm, <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">-</span><span class="cn" style="color: #8f5902;
background-color: null;
font-style: inherit;">Inf</span>, <span class="cn" style="color: #8f5902;
background-color: null;
font-style: inherit;">Inf</span>, <span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">mean =</span> regimes<span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">$</span>mu[k], <span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">sd =</span> regimes<span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">$</span>sx[k])<span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">$</span>value, <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">0</span>)</span>
<span id="cb10-136"><span class="co" style="color: #5E5E5E;
background-color: null;
font-style: inherit;"># a canary that passes: fish of about 10 cm, sd 1 cm, measured to 0.3 mm</span></span>
<span id="cb10-137">canary_pass   <span class="ot" style="color: #003B4F;
background-color: null;
font-style: inherit;">&lt;-</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">integrate</span>(dnorm, <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">-</span><span class="cn" style="color: #8f5902;
background-color: null;
font-style: inherit;">Inf</span>, <span class="cn" style="color: #8f5902;
background-color: null;
font-style: inherit;">Inf</span>, <span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">mean =</span> <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">10</span>, <span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">sd =</span> <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">1</span>)<span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">$</span>value</span>
<span id="cb10-138">canary_prod   <span class="ot" style="color: #003B4F;
background-color: null;
font-style: inherit;">&lt;-</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">integrate</span>(<span class="cf" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">function</span>(x) <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">dnorm</span>(<span class="fl" style="color: #AD0000;
background-color: null;
font-style: inherit;">10.5</span>, x, <span class="fl" style="color: #AD0000;
background-color: null;
font-style: inherit;">0.03</span>) <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">*</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">dnorm</span>(x, <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">10</span>, <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">1</span>),</span>
<span id="cb10-139">                           <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">-</span><span class="cn" style="color: #8f5902;
background-color: null;
font-style: inherit;">Inf</span>, <span class="cn" style="color: #8f5902;
background-color: null;
font-style: inherit;">Inf</span>)<span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">$</span>value</span>
<span id="cb10-140">canary_target <span class="ot" style="color: #003B4F;
background-color: null;
font-style: inherit;">&lt;-</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">dnorm</span>(<span class="fl" style="color: #AD0000;
background-color: null;
font-style: inherit;">10.5</span>, <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">10</span>, <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">sqrt</span>(<span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">1</span> <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">+</span> <span class="fl" style="color: #AD0000;
background-color: null;
font-style: inherit;">0.03</span><span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">^</span><span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">2</span>))</span></code></pre></div></div>
</div>
<p>The standardised route recovers median slopes of 0.0806, 0.0821 and 0.0840 per mm in the three regimes, against a true 0.08, and converges with code 0 in 1.00, 1.00 and 1.00 of datasets. That is the fit the student wanted.</p>
<p>The raw route, on the same datasets from the same start, gives median slopes of +0.0332, +0.0010 and +0.0060, with ranges across datasets of -0.1129 to +0.1133, -0.4396 to +0.1627, and +0.0029 to +0.0372. The slope comes out negative in 10, 11 and 0 of the 25 datasets. Paired dataset by dataset, the raw estimate minus the standardised one, as a fraction of the standardised one, has a median of -0.546, -0.992 and -0.930, and a median magnitude of 0.730, 0.998 and 0.930. Resampling the 25 datasets, the exact 95 per cent bootstrap percentile intervals for those medians run from 0.338 to 2.093, 0.930 to 1.321 and 0.919 to 0.938; the first regime, where the raw route lands in very different places, is the one a different set of seeds would move most. The two routes differ by more than 30 per cent of the standardised estimate in 20, 24 and 25 of the 25 datasets.</p>
<p>Little in the output flags it. At the raw fits’ own parameters, recomputed with <code>stop.on.error = FALSE</code>, the smallest share of per-fish integrals returning the message <code>"OK"</code> in any dataset is 1.000: the routine’s own error test passed on every fish. The raw fits converge with code 0 in 1.00, 0.76 and 1.00 of datasets. The only signal is the 6 fits in the second regime that stopped at the iteration limit (code 1), and an iteration limit says nothing about the integrals. And the broken fit is worse than doing nothing: the naive regression on recorded length, which ignores the measurement error altogether and is known to be attenuated, gives median slopes of 0.0588, 0.0633 and 0.0542, and lands closer to the correct estimate than the raw route does in 0.80, 0.96 and 1.00 of datasets.</p>
<div class="cell">
<div class="code-copy-outer-scaffold"><div class="sourceCode cell-code" id="cb11" style="background: #f1f3f5;"><pre class="sourceCode r code-with-copy"><code class="sourceCode r"><span id="cb11-1">pair_res<span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">$</span>rank <span class="ot" style="color: #003B4F;
background-color: null;
font-style: inherit;">&lt;-</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">ave</span>(pair_res<span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">$</span>std, pair_res<span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">$</span>regime,</span>
<span id="cb11-2">                     <span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">FUN =</span> <span class="cf" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">function</span>(v) <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">rank</span>(v, <span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">ties.method =</span> <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"first"</span>))</span>
<span id="cb11-3">pair_long <span class="ot" style="color: #003B4F;
background-color: null;
font-style: inherit;">&lt;-</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">rbind</span>(</span>
<span id="cb11-4">  <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">data.frame</span>(pair_res[, <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">c</span>(<span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"regime"</span>, <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"rank"</span>)], <span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">slope =</span> pair_res<span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">$</span>std,</span>
<span id="cb11-5">             <span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">route =</span> <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"integrated, standardised"</span>),</span>
<span id="cb11-6">  <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">data.frame</span>(pair_res[, <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">c</span>(<span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"regime"</span>, <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"rank"</span>)], <span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">slope =</span> pair_res<span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">$</span>raw,</span>
<span id="cb11-7">             <span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">route =</span> <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"integrated, raw mm scale"</span>),</span>
<span id="cb11-8">  <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">data.frame</span>(pair_res[, <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">c</span>(<span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"regime"</span>, <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"rank"</span>)], <span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">slope =</span> pair_res<span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">$</span>naive,</span>
<span id="cb11-9">             <span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">route =</span> <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"naive glm on recorded length"</span>))</span>
<span id="cb11-10">pair_long<span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">$</span>route <span class="ot" style="color: #003B4F;
background-color: null;
font-style: inherit;">&lt;-</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">factor</span>(pair_long<span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">$</span>route,</span>
<span id="cb11-11">  <span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">levels =</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">c</span>(<span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"integrated, standardised"</span>, <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"integrated, raw mm scale"</span>,</span>
<span id="cb11-12">             <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"naive glm on recorded length"</span>))</span>
<span id="cb11-13"></span>
<span id="cb11-14"><span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">ggplot</span>(pair_long, <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">aes</span>(rank, slope)) <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">+</span></span>
<span id="cb11-15">  <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">geom_hline</span>(<span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">yintercept =</span> b1_true, <span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">linetype =</span> <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"dashed"</span>, <span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">colour =</span> te_body,</span>
<span id="cb11-16">             <span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">linewidth =</span> <span class="fl" style="color: #AD0000;
background-color: null;
font-style: inherit;">0.5</span>) <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">+</span></span>
<span id="cb11-17">  <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">geom_hline</span>(<span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">yintercept =</span> <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">0</span>, <span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">colour =</span> te_line, <span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">linewidth =</span> <span class="fl" style="color: #AD0000;
background-color: null;
font-style: inherit;">0.6</span>) <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">+</span></span>
<span id="cb11-18">  <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">geom_segment</span>(<span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">data =</span> pair_res, <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">aes</span>(<span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">x =</span> rank, <span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">xend =</span> rank, <span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">y =</span> std, <span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">yend =</span> raw),</span>
<span id="cb11-19">               <span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">colour =</span> <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"grey60"</span>, <span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">linewidth =</span> <span class="fl" style="color: #AD0000;
background-color: null;
font-style: inherit;">0.4</span>) <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">+</span></span>
<span id="cb11-20">  <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">geom_point</span>(<span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">aes</span>(<span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">colour =</span> route, <span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">shape =</span> route), <span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">size =</span> <span class="fl" style="color: #AD0000;
background-color: null;
font-style: inherit;">1.9</span>) <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">+</span></span>
<span id="cb11-21">  <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">facet_wrap</span>(<span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">~</span> regime, <span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">ncol =</span> <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">1</span>, <span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">scales =</span> <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"free_y"</span>) <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">+</span></span>
<span id="cb11-22">  <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">scale_colour_manual</span>(<span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">values =</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">c</span>(te_forest, te_rust, te_gold), <span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">name =</span> <span class="cn" style="color: #8f5902;
background-color: null;
font-style: inherit;">NULL</span>) <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">+</span></span>
<span id="cb11-23">  <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">scale_shape_manual</span>(<span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">values =</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">c</span>(<span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">16</span>, <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">17</span>, <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">15</span>), <span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">name =</span> <span class="cn" style="color: #8f5902;
background-color: null;
font-style: inherit;">NULL</span>) <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">+</span></span>
<span id="cb11-24">  <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">guides</span>(<span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">colour =</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">guide_legend</span>(<span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">ncol =</span> <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">1</span>), <span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">shape =</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">guide_legend</span>(<span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">ncol =</span> <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">1</span>)) <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">+</span></span>
<span id="cb11-25">  <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">labs</span>(<span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">x =</span> <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"dataset, ordered by the standardised estimate"</span>,</span>
<span id="cb11-26">       <span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">y =</span> <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"slope per mm"</span>,</span>
<span id="cb11-27">       <span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">title =</span> <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"Same data, same start, different computation"</span>,</span>
<span id="cb11-28">       <span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">subtitle =</span> <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"dashed: the true slope 0.08"</span>) <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">+</span></span>
<span id="cb11-29">  <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">theme_datasheet</span>() <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">+</span></span>
<span id="cb11-30">  <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">theme</span>(<span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">legend.position =</span> <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"bottom"</span>,</span>
<span id="cb11-31">        <span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">strip.text =</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">element_text</span>(<span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">colour =</span> te_ink, <span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">hjust =</span> <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">0</span>))</span></code></pre></div></div>
<div class="cell-output-display">
<div id="fig-paired" class="quarto-float quarto-figure quarto-figure-center anchored" alt="Three stacked panels on warm off-white paper, one per regime, each showing 25 datasets along the horizontal axis ordered by the standardised slope, with a dashed line at the true slope of 0.08 and a pale line at zero. Dark green circles for the standardised route sit near the dashed line in every panel, and gold squares for the naive glm sit a little below them. Red triangles for the raw route are joined to the green circles by grey vertical segments. In the top panel, mean 420, sd 15, error 8 mm, the triangles split between values from about 0.02 to 0.11 and a group of ten near minus 0.1. In the middle panel, mean 420, sd 25, error 10 mm, most triangles sit within a few hundredths of zero; the exceptions are one at minus 0.44, one at minus 0.15 and three between 0.10 and 0.16. In the bottom panel, mean 250, sd 20, error 12 mm, every triangle sits above zero and below 0.04, most of them within 0.01 of zero and two near 0.03 and 0.04.">
<figure class="quarto-float quarto-float-fig figure">
<div aria-describedby="fig-paired-caption-0ceaefa1-69ba-4598-a22c-09a6ac19f8ca">
<img src="https://tidyecology.com/posts/when-integrate-returns-zero/index_files/figure-html/fig-paired-1.png" class="img-fluid figure-img" alt="Three stacked panels on warm off-white paper, one per regime, each showing 25 datasets along the horizontal axis ordered by the standardised slope, with a dashed line at the true slope of 0.08 and a pale line at zero. Dark green circles for the standardised route sit near the dashed line in every panel, and gold squares for the naive glm sit a little below them. Red triangles for the raw route are joined to the green circles by grey vertical segments. In the top panel, mean 420, sd 15, error 8 mm, the triangles split between values from about 0.02 to 0.11 and a group of ten near minus 0.1. In the middle panel, mean 420, sd 25, error 10 mm, most triangles sit within a few hundredths of zero; the exceptions are one at minus 0.44, one at minus 0.15 and three between 0.10 and 0.16. In the bottom panel, mean 250, sd 20, error 12 mm, every triangle sits above zero and below 0.04, most of them within 0.01 of zero and two near 0.03 and 0.04." width="672">
</div>
<figcaption class="quarto-float-caption-bottom quarto-float-caption quarto-float-fig" id="fig-paired-caption-0ceaefa1-69ba-4598-a22c-09a6ac19f8ca">
Figure&nbsp;4: Slope estimates for each simulated dataset, by the standardised route, the raw route and a naive logistic regression. Grey segments join the two integrated-likelihood fits of the same dataset.
</figcaption>
</figure>
</div>
</div>
</div>
</section>
<section id="why-a-check-for-zeros-is-not-enough" class="level2">
<h2 id="why-a-check-for-zeros-is-not-enough-h" class="anchored" data-anchor-id="why-a-check-for-zeros-is-not-enough">Why a check for zeros is not enough</h2>
<p>The obvious diagnostic is to look for integrals that came back as exactly 0 and treat any as a red flag. It does not work well here. At the raw route’s own fitted parameters, the median share of per-fish integrals that are exactly 0 is 0.072, 0.000 and 0.000 in the three regimes. Most of the damage is done by integrals that are not zero but are wrong: against the integrand-centred route at the same parameters, the median per-fish log10 ratio of raw to correct is -9.2, -8.9 and -60.4. The raw integrals are positive numbers many orders of magnitude too small, and the optimiser is doing its honest best on a surface made of them.</p>
<p>The reported absolute error does better, if it is read against the value rather than on its own. A rule that flags a fish whose integral is 0 or whose reported error exceeds 1 per cent of its value flags a median share of 1.00, 0.71 and 0.00 of fish at the raw fits in the three regimes. That catches the first two regimes and misses the third, where the error estimate shrinks along with the wrong value. On the standardised fits the same rule flags a median of 0.04, 0.13 and 0.12 of fish, and up to 0.18 in one dataset, so a flag marks a fish to look at rather than a broken fit. It is cheap and worth running, and it is not the check that clears a fit.</p>
<p>Two checks do catch it here, and both are cheap enough to run after every fit. The first is to recompute the log-likelihood at the fitted parameters by a second route that centres differently, here the integrand-centred one, and compare. For the raw fits the negative log-likelihood reported by <code>optim()</code> exceeds the recomputed one by a median of 12643, 27245 and 24723 log-likelihood units, and by at least 4373 in every dataset. For the standardised fits the median disagreement is <img src="https://latex.codecogs.com/png.latex?5.72%20%5Ctimes%2010%5E%7B-4%7D"> units and the largest is 0.169. That is not zero because the standardised route and the integrand-centred one both run at <code>integrate()</code>’s default tolerance. For integrals as small as these the absolute tolerance of <img src="https://latex.codecogs.com/png.latex?1.22%20%5Ctimes%2010%5E%7B-4%7D"> is the test that binds, which leaves small errors in both; and for a fish whose integrand sits far from the population centre and whose integral is below that tolerance, it lets the standardised route stop with a large relative error, as it let the failing cells of the failure map through. Even so, the smallest raw gap is 4.4 orders of magnitude larger than the largest standardised one. A likelihood that changes when the variable of integration is merely shifted is not being computed. The second check is cruder and needs no second route: integrate the population density on its own, with the same call, and see whether it returns 1. For the three regimes <code>integrate(dnorm, -Inf, Inf, mean = mu, sd = sx)</code> returns <img src="https://latex.codecogs.com/png.latex?3.55%20%5Ctimes%2010%5E%7B-67%7D">, <img src="https://latex.codecogs.com/png.latex?2.06%20%5Ctimes%2010%5E%7B-24%7D"> and <img src="https://latex.codecogs.com/png.latex?1.42%20%5Ctimes%2010%5E%7B-16%7D">. This check is one-sided: a population density that integrates to 1 says nothing about the narrower product integrand, so a pass is no clearance. For fish of about 10 cm with a standard deviation of 1 cm, measured to 0.3 mm, the population density returns 1.000000, and the integrand for a fish recorded at 10.5 cm returns 0 against an exact 0.352.</p>
<div class="cell">
<div class="code-copy-outer-scaffold"><div class="sourceCode cell-code" id="cb12" style="background: #f1f3f5;"><pre class="sourceCode r code-with-copy"><code class="sourceCode r"><span id="cb12-1">diag_df <span class="ot" style="color: #003B4F;
background-color: null;
font-style: inherit;">&lt;-</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">rbind</span>(</span>
<span id="cb12-2">  <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">data.frame</span>(<span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">regime =</span> pair_res<span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">$</span>regime, <span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">gap =</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">abs</span>(pair_res<span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">$</span>gap_std),</span>
<span id="cb12-3">             <span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">route =</span> <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"integrated, standardised"</span>),</span>
<span id="cb12-4">  <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">data.frame</span>(<span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">regime =</span> pair_res<span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">$</span>regime, <span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">gap =</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">abs</span>(pair_res<span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">$</span>gap_raw),</span>
<span id="cb12-5">             <span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">route =</span> <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"integrated, raw mm scale"</span>))</span>
<span id="cb12-6">diag_df<span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">$</span>gap <span class="ot" style="color: #003B4F;
background-color: null;
font-style: inherit;">&lt;-</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">pmax</span>(diag_df<span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">$</span>gap, <span class="fl" style="color: #AD0000;
background-color: null;
font-style: inherit;">1e-12</span>)</span>
<span id="cb12-7">diag_df<span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">$</span>route <span class="ot" style="color: #003B4F;
background-color: null;
font-style: inherit;">&lt;-</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">factor</span>(diag_df<span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">$</span>route, <span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">levels =</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">c</span>(<span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"integrated, standardised"</span>,</span>
<span id="cb12-8">                                                  <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"integrated, raw mm scale"</span>))</span>
<span id="cb12-9"></span>
<span id="cb12-10"><span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">ggplot</span>(diag_df, <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">aes</span>(gap, regime, <span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">colour =</span> route)) <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">+</span></span>
<span id="cb12-11">  <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">geom_point</span>(<span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">position =</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">position_jitter</span>(<span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">height =</span> <span class="fl" style="color: #AD0000;
background-color: null;
font-style: inherit;">0.18</span>, <span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">width =</span> <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">0</span>, <span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">seed =</span> <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">7</span>),</span>
<span id="cb12-12">             <span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">size =</span> <span class="fl" style="color: #AD0000;
background-color: null;
font-style: inherit;">1.8</span>, <span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">alpha =</span> <span class="fl" style="color: #AD0000;
background-color: null;
font-style: inherit;">0.85</span>) <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">+</span></span>
<span id="cb12-13">  <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">scale_x_log10</span>(<span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">breaks =</span> <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">10</span><span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">^</span><span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">c</span>(<span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">-</span><span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">12</span>, <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">-</span><span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">8</span>, <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">-</span><span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">4</span>, <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">0</span>, <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">4</span>),</span>
<span id="cb12-14">                <span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">labels =</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">expression</span>(<span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">10</span><span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">^-</span><span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">12</span>, <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">10</span><span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">^-</span><span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">8</span>, <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">10</span><span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">^-</span><span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">4</span>, <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">1</span>, <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">10</span><span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">^</span><span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">4</span>)) <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">+</span></span>
<span id="cb12-15">  <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">scale_colour_manual</span>(<span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">values =</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">c</span>(te_forest, te_rust), <span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">name =</span> <span class="cn" style="color: #8f5902;
background-color: null;
font-style: inherit;">NULL</span>) <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">+</span></span>
<span id="cb12-16">  <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">labs</span>(<span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">x =</span> <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"absolute gap in negative log-likelihood (log scale)"</span>, <span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">y =</span> <span class="cn" style="color: #8f5902;
background-color: null;
font-style: inherit;">NULL</span>,</span>
<span id="cb12-17">       <span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">title =</span> <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"A shifted variable should not move the likelihood"</span>,</span>
<span id="cb12-18">       <span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">subtitle =</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">expression</span>(<span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"one point per dataset and route; gaps below "</span> <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">*</span> <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">10</span><span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">^-</span><span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">12</span> <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">*</span> <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">" drawn at the floor"</span>)) <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">+</span></span>
<span id="cb12-19">  <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">theme_datasheet</span>() <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">+</span></span>
<span id="cb12-20">  <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">theme</span>(<span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">legend.position =</span> <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"bottom"</span>, <span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">plot.title.position =</span> <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"plot"</span>)</span></code></pre></div></div>
<div class="cell-output-display">
<div id="fig-diagnostic" class="quarto-float quarto-figure quarto-figure-center anchored" alt="A dot plot on warm off-white paper with one row per regime and a horizontal log axis for the absolute gap in negative log-likelihood, from below 10 to the minus 5 to above ten thousand. In every row the dark green points for the standardised route are spread between about 10 to the minus 5 and 0.2, and the red points for the raw route sit in a tight cluster between about four thousand and thirty thousand, far to the right.">
<figure class="quarto-float quarto-float-fig figure">
<div aria-describedby="fig-diagnostic-caption-0ceaefa1-69ba-4598-a22c-09a6ac19f8ca">
<img src="https://tidyecology.com/posts/when-integrate-returns-zero/index_files/figure-html/fig-diagnostic-1.png" class="img-fluid figure-img" alt="A dot plot on warm off-white paper with one row per regime and a horizontal log axis for the absolute gap in negative log-likelihood, from below 10 to the minus 5 to above ten thousand. In every row the dark green points for the standardised route are spread between about 10 to the minus 5 and 0.2, and the red points for the raw route sit in a tight cluster between about four thousand and thirty thousand, far to the right." width="672">
</div>
<figcaption class="quarto-float-caption-bottom quarto-float-caption quarto-float-fig" id="fig-diagnostic-caption-0ceaefa1-69ba-4598-a22c-09a6ac19f8ca">
Figure&nbsp;5: The two integrated-likelihood fits of every dataset, rechecked by a third route that centres on each fish’s own integrand. The horizontal axis is the gap between the negative log-likelihood the fit reported and the recomputed one.
</figcaption>
</figure>
</div>
</div>
</div>
</section>
<section id="what-to-report" class="level2">
<h2 id="what-to-report-h" class="anchored" data-anchor-id="what-to-report">What to report</h2>
<p>State the variable of integration and how it was centred and scaled, in the methods, the way a mesh size or a number of quadrature nodes would be stated. “The likelihood integrates over true length with <code>integrate()</code>” is not a description of the computation; “over the standardised true length, centred on each fish’s conditional mean” is.</p>
<p>Report a check of the integral against something exact. For a measurement-error or random-effects likelihood the population density on its own integrates to 1, and a line of code shows whether the call can see even that; a pass is necessary, not sufficient, and the second-route check below is the one that clears a fit. Where the model has a closed-form special case, such as the Gaussian part here, report the worst relative error of the routine against it over the range of the data.</p>
<p>Report the log-likelihood at the fitted parameters from a second, differently centred route, and the gap between the two. The convergence code and the message describe the routine’s view of its own work: in this post the message was OK on every fish and the code was 0 on most fits that were wrong by most of the estimate. The reported absolute error helps only when it is read against the value, and even then it caught two regimes of three.</p>
<p>If a naive estimate is available, report it next to the corrected one. A correction for measurement error should move the slope away from zero by an amount the reliability ratio makes plausible. A corrected slope that lands nearer zero than the naive one, or on the other side of it, is a computation problem until shown otherwise.</p>
</section>
<section id="honest-limits" class="level2">
<h2 id="honest-limits-h" class="anchored" data-anchor-id="honest-limits">Honest limits</h2>
<p>The failure map uses one integrand, the normal density, and one grid. The share of failing cells is a function of where the grid reaches, as the section defending it says, and a grid confined to means near zero finds failures only at narrow widths: over means from 0.25 to 2 and standard deviations from 0.1 down to 0.003, 7 of 24 cells fail, 5 of them at 0.003 and none at a standard deviation above 0.03. The claim that survives any grid is the qualitative one: the routine’s first probes sit near the origin on the scale of the argument, and a narrow mass far from them can be missed and reported as OK.</p>
<p>The behaviour depends on the QUADPACK implementation in R 4.3.3 and on the default tolerances. A tighter <code>rel.tol</code> or a larger <code>subdivisions</code> should not help when the probes see nothing, since a subinterval on which both rules return zero shows no error to reduce, and the one check made agrees: the fish-length call with <code>rel.tol = 1e-10</code> and <code>subdivisions = 1000</code> returns <img src="https://latex.codecogs.com/png.latex?3.55%20%5Ctimes%2010%5E%7B-67%7D"> with message <code>"OK"</code>. No other settings or R versions were tested.</p>
<p>The downstream model treats the population mean and sd of true length, and the measurement error sd, as known. In a real analysis they are estimated, usually from replicate measurements, and the uncertainty in them adds to the uncertainty in the slope. That changes the size of the standard errors, not the computational point. Stefanski and Carroll’s conditional score avoids the integral altogether for a logistic model with normal measurement error, and Carroll and colleagues give the structural likelihood used here in full; neither is compared with this fit.</p>
<p>Only three regimes were run, with 25 datasets each and population-to-error ratios between 1.67 and 2.50. At those ratios the prior-centred substitution is close to exact, though not exact at the default tolerance, as the next paragraph says. The section on repairs shows it failing once the ratio reaches 21.4, which is the case of a precise instrument on a variable population; a fit in that range would need the integrand-centred route, and none was fitted here.</p>
<p>The paired reference is the standardised route, which the diagnostic above shows is not exact either: its log-likelihood differs from the integrand-centred one by up to 0.169 units. The integrand-centred route was fitted to the first 3 datasets of each regime as a check, and there the standardised slope differs from it by at most 0.0003 of its value, against paired raw gaps of most of the estimate; the other datasets were not refitted, so the standardised slopes stay the reference because that design was fixed before the run, not because they are the best available.</p>
<p>Nelder-Mead from a fixed start is a single optimiser run. A different start or a gradient method might land the raw route elsewhere, and in the first regime it lands in very different places across datasets already. That instability is part of the finding, not a correction to it: a surface made of wrong integrals has no right answer to converge to.</p>
</section>
<section id="references" class="level2">
<h2 id="references-h" class="anchored" data-anchor-id="references">References</h2>
<p>Piessens R, de Doncker-Kapenga E, Ueberhuber CW, Kahaner DK 1983 QUADPACK: A Subroutine Package for Automatic Integration (ISBN 978-3-540-12553-2)</p>
<p>Liu Q, Pierce DA 1994 Biometrika 81(3):624-629 (<a href="https://doi.org/10.1093/biomet/81.3.624">10.1093/biomet/81.3.624</a>)</p>
<p>Stefanski LA, Carroll RJ 1987 Biometrika 74(4):703-716 (<a href="https://doi.org/10.1093/biomet/74.4.703">10.1093/biomet/74.4.703</a>)</p>
<p>Carroll RJ, Ruppert D, Stefanski LA, Crainiceanu CM 2006 Measurement Error in Nonlinear Models, 2nd edition (ISBN 978-1-58488-633-4)</p>
</section>
<section id="related-tutorials" class="level2">
<h2 id="related-tutorials-h" class="anchored" data-anchor-id="related-tutorials">Related tutorials</h2>
<ul>
<li><a href="https://tidyecology.com/posts/the-laplace-approximation/">The Laplace approximation in R</a></li>
<li><a href="https://tidyecology.com/posts/ipm-eviction-and-mesh/">Eviction and mesh size in an IPM</a></li>
<li><a href="https://tidyecology.com/posts/measurement-error-regression-dilution/">Measurement error and regression dilution</a></li>
<li><a href="https://tidyecology.com/posts/coordinate-error-and-habitat-assignment/">Coordinate error and habitat assignment</a></li>
</ul>
<details class="te-repro" data-pagefind-ignore="">
<summary>Reproducibility</summary>
<ul>
<li>Code last run: 2026-10-15</li>
<li>R version 4.5.3 (2026-03-11), aarch64-apple-darwin20</li>
<li>Packages: ggplot2 4.0.3</li>
</ul>
</details>


<!-- -->

</section>

 ]]></description>
  <category>R</category>
  <category>numerical methods</category>
  <category>measurement error</category>
  <category>likelihood</category>
  <category>reproducibility</category>
  <category>ecology tutorial</category>
  <guid isPermaLink="false">https://tidyecology.com/posts/when-integrate-returns-zero/</guid>
  <pubDate>Mon, 28 Sep 2026 10:00:00 GMT</pubDate>
  <media:content url="https://tidyecology.com/posts/when-integrate-returns-zero/thumbnail.png" medium="image" type="image/png" height="104" width="144"/>
</item>
<item>
  <title>Parameter scale decides what optim() finds</title>
  <dc:creator>Tidy Ecology</dc:creator>
  <link>https://tidyecology.com/posts/parameter-scale-and-what-optim-finds/</link>
  <description><![CDATA[ 





<p><em>Corrected 15 October 2026: the L-BFGS-B section said two methods each called with their defaults differ by a stated factor in how often they miss, but the factor came from L-BFGS-B called with box bounds; it now comes from L-BFGS-B without a box, the call with all its defaults, and is smaller.</em></p>
<p><em>Corrected 30 September 2026: the post called the R copy of <code>vmmin</code> an exact reproduction of <code>optim()</code> while its own printed share of matching K values was far below one; it now reports the shares of matching convergence codes and K values without calling the copy exact.</em></p>
<p>Thirty summers of counts from a seabird colony, a few hundred pairs at the start and several thousand by the end. The model is the Ricker (Ricker 1954), the one every population course teaches: next year’s log growth is a maximum rate r, pulled down in proportion to how close this year’s count is to a carrying capacity K, plus process noise. The analyst writes the negative log-likelihood in r, K and the log of the noise standard deviation, picks a start, and calls <code>optim(start, nll, method = "BFGS")</code>, which is how the function is called in the help page and in a large share of the posts on this site. The call returns a carrying capacity more than a third too small. A third of the time it also returns convergence code 0; the rest of the time it returns code 1, and raising <code>maxit</code> turns many of those into a 0, about half of them with K still more than a tenth out.</p>
<p>Nothing about this is new. Gradient methods are not scale invariant: a parameter whose natural size is thousands, sitting next to parameters whose natural size is about one, gets moved by the search as if it were the same size as the others. Nash and Varadhan 2011 discuss scaling diagnostics for <code>optim()</code> and its relatives, and the remedy, the <code>parscale</code> element of the control list, is documented accurately on the help page. What this post measures is how large the damage is on an ordinary ecological fit, why the one warning a reader gets disappears under the obvious fix, and which of the other fitters in base R share the problem. The mechanism is traced step by step, down to one line of R’s C source, because the two tempting explanations both turn out to be wrong.</p>
<p>The nearest posts on the site are about fitting too, and the difference matters. <a href="https://tidyecology.com/posts/starting-values-and-identifiability/">Starting values and identifiability in nls</a> reparameterises a decay curve by shifting its time origin, which removes a correlation between parameters while “the rate estimate is unchanged”; there the new spelling makes the fit cleaner and moves no answer. <a href="https://tidyecology.com/posts/checking-a-mixture-model/">Checking a mixture model</a> asks which of several optima a run found. Here there is one optimum, every fitter starts at the same point, and two algebraically identical spellings of the same model disagree about the carrying capacity by more than a third. <a href="https://tidyecology.com/posts/theta-logistic-model/">The theta-logistic model in R</a> calls BFGS with <code>maxit = 2000</code>, the reflex this post puts a number on, but fits K on the log scale, <code>log(max(N) * 1.05)</code>, which is the repair applied without comment. <a href="https://tidyecology.com/posts/when-integrate-returns-zero/">When integrate() in R returns zero and says OK</a> is the sibling case: an undeclared default inside a base R function that fails while reporting success.</p>
<p>There is also a reason this particular fit should never have gone wrong, and it is part of the lesson. Written with b = r / K instead of K, the Ricker on the log scale is a straight line in this year’s count, so <code>lm()</code> returns the exact maximum likelihood estimate with no search at all. That exact answer is the benchmark throughout. Nothing below is compared with the true K or with the best of the fitters; every error is measured against the exact maximum of the same likelihood, on the same series.</p>
<div class="cell">
<div class="code-copy-outer-scaffold"><div class="sourceCode cell-code" id="cb1" style="background: #f1f3f5;"><pre class="sourceCode r code-with-copy"><code class="sourceCode r"><span id="cb1-1"><span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">library</span>(ggplot2)</span>
<span id="cb1-2"><span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">library</span>(patchwork)</span>
<span id="cb1-3"></span>
<span id="cb1-4">te_paper  <span class="ot" style="color: #003B4F;
background-color: null;
font-style: inherit;">&lt;-</span> <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"#f5f4ee"</span></span>
<span id="cb1-5">te_ink    <span class="ot" style="color: #003B4F;
background-color: null;
font-style: inherit;">&lt;-</span> <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"#16241d"</span></span>
<span id="cb1-6">te_body   <span class="ot" style="color: #003B4F;
background-color: null;
font-style: inherit;">&lt;-</span> <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"#2c3a31"</span></span>
<span id="cb1-7">te_forest <span class="ot" style="color: #003B4F;
background-color: null;
font-style: inherit;">&lt;-</span> <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"#275139"</span></span>
<span id="cb1-8">te_rust   <span class="ot" style="color: #003B4F;
background-color: null;
font-style: inherit;">&lt;-</span> <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"#b5534e"</span></span>
<span id="cb1-9">te_gold   <span class="ot" style="color: #003B4F;
background-color: null;
font-style: inherit;">&lt;-</span> <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"#c9b458"</span></span>
<span id="cb1-10">te_line   <span class="ot" style="color: #003B4F;
background-color: null;
font-style: inherit;">&lt;-</span> <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"#dad9ca"</span></span>
<span id="cb1-11"></span>
<span id="cb1-12">theme_datasheet <span class="ot" style="color: #003B4F;
background-color: null;
font-style: inherit;">&lt;-</span> <span class="cf" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">function</span>() {</span>
<span id="cb1-13">  <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">theme_minimal</span>(<span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">base_size =</span> <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">12</span>) <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">+</span></span>
<span id="cb1-14">    <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">theme</span>(<span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">plot.background  =</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">element_rect</span>(<span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">fill =</span> te_paper, <span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">colour =</span> <span class="cn" style="color: #8f5902;
background-color: null;
font-style: inherit;">NA</span>),</span>
<span id="cb1-15">          <span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">panel.background =</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">element_rect</span>(<span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">fill =</span> te_paper, <span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">colour =</span> <span class="cn" style="color: #8f5902;
background-color: null;
font-style: inherit;">NA</span>),</span>
<span id="cb1-16">          <span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">panel.grid.major =</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">element_line</span>(<span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">colour =</span> te_line, <span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">linewidth =</span> <span class="fl" style="color: #AD0000;
background-color: null;
font-style: inherit;">0.3</span>),</span>
<span id="cb1-17">          <span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">panel.grid.minor =</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">element_blank</span>(),</span>
<span id="cb1-18">          <span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">text             =</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">element_text</span>(<span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">colour =</span> te_body),</span>
<span id="cb1-19">          <span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">plot.title       =</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">element_text</span>(<span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">colour =</span> te_ink, <span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">face =</span> <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"bold"</span>),</span>
<span id="cb1-20">          <span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">plot.subtitle    =</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">element_text</span>(<span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">colour =</span> te_body),</span>
<span id="cb1-21">          <span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">axis.text        =</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">element_text</span>(<span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">colour =</span> te_body))</span>
<span id="cb1-22">}</span></code></pre></div></div>
</div>
<section id="one-model-two-spellings" class="level2">
<h2 id="one-model-two-spellings-h" class="anchored" data-anchor-id="one-model-two-spellings">One model, two spellings</h2>
<p>The generating model is the stochastic Ricker on the log scale, with a maximum growth rate of 0.45, a carrying capacity of 5000, a process standard deviation of 0.25 and a first count of 800. Every series is thirty years long. The likelihood is the normal density of the one-step log growth, with the log of sigma as the third parameter so that no parameter has a bound.</p>
<div class="cell">
<div class="code-copy-outer-scaffold"><div class="sourceCode cell-code" id="cb2" style="background: #f1f3f5;"><pre class="sourceCode r code-with-copy"><code class="sourceCode r"><span id="cb2-1">r_true   <span class="ot" style="color: #003B4F;
background-color: null;
font-style: inherit;">&lt;-</span> <span class="fl" style="color: #AD0000;
background-color: null;
font-style: inherit;">0.45</span>     <span class="co" style="color: #5E5E5E;
background-color: null;
font-style: inherit;"># maximum per capita log growth</span></span>
<span id="cb2-2">K_true   <span class="ot" style="color: #003B4F;
background-color: null;
font-style: inherit;">&lt;-</span> <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">5000</span>     <span class="co" style="color: #5E5E5E;
background-color: null;
font-style: inherit;"># carrying capacity</span></span>
<span id="cb2-3">sd_proc  <span class="ot" style="color: #003B4F;
background-color: null;
font-style: inherit;">&lt;-</span> <span class="fl" style="color: #AD0000;
background-color: null;
font-style: inherit;">0.25</span>     <span class="co" style="color: #5E5E5E;
background-color: null;
font-style: inherit;"># process noise on the log scale</span></span>
<span id="cb2-4">N_first  <span class="ot" style="color: #003B4F;
background-color: null;
font-style: inherit;">&lt;-</span> <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">800</span>      <span class="co" style="color: #5E5E5E;
background-color: null;
font-style: inherit;"># first count</span></span>
<span id="cb2-5">n_yr     <span class="ot" style="color: #003B4F;
background-color: null;
font-style: inherit;">&lt;-</span> <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">30</span>       <span class="co" style="color: #5E5E5E;
background-color: null;
font-style: inherit;"># years per series</span></span>
<span id="cb2-6">start_far <span class="ot" style="color: #003B4F;
background-color: null;
font-style: inherit;">&lt;-</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">c</span>(<span class="fl" style="color: #AD0000;
background-color: null;
font-style: inherit;">0.30</span>, <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">3000</span>, <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">log</span>(<span class="fl" style="color: #AD0000;
background-color: null;
font-style: inherit;">0.3</span>))   <span class="co" style="color: #5E5E5E;
background-color: null;
font-style: inherit;"># r, K, log sigma: fixed before any fit was run</span></span>
<span id="cb2-7">box_lo <span class="ot" style="color: #003B4F;
background-color: null;
font-style: inherit;">&lt;-</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">c</span>(<span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">-</span><span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">2</span>, <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">10</span>, <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">-</span><span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">5</span>); box_hi <span class="ot" style="color: #003B4F;
background-color: null;
font-style: inherit;">&lt;-</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">c</span>(<span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">5</span>, <span class="fl" style="color: #AD0000;
background-color: null;
font-style: inherit;">1e6</span>, <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">5</span>)</span>
<span id="cb2-8"></span>
<span id="cb2-9">sim_ricker <span class="ot" style="color: #003B4F;
background-color: null;
font-style: inherit;">&lt;-</span> <span class="cf" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">function</span>() {</span>
<span id="cb2-10">  N <span class="ot" style="color: #003B4F;
background-color: null;
font-style: inherit;">&lt;-</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">numeric</span>(n_yr); N[<span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">1</span>] <span class="ot" style="color: #003B4F;
background-color: null;
font-style: inherit;">&lt;-</span> N_first</span>
<span id="cb2-11">  <span class="cf" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">for</span> (i <span class="cf" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">in</span> <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">2</span><span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">:</span>n_yr)</span>
<span id="cb2-12">    N[i] <span class="ot" style="color: #003B4F;
background-color: null;
font-style: inherit;">&lt;-</span> N[i <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">-</span> <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">1</span>] <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">*</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">exp</span>(r_true <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">*</span> (<span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">1</span> <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">-</span> N[i <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">-</span> <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">1</span>] <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">/</span> K_true) <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">+</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">rnorm</span>(<span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">1</span>, <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">0</span>, sd_proc))</span>
<span id="cb2-13">  N</span>
<span id="cb2-14">}</span>
<span id="cb2-15"></span>
<span id="cb2-16">make_fit <span class="ot" style="color: #003B4F;
background-color: null;
font-style: inherit;">&lt;-</span> <span class="cf" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">function</span>(N) {</span>
<span id="cb2-17">  y <span class="ot" style="color: #003B4F;
background-color: null;
font-style: inherit;">&lt;-</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">diff</span>(<span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">log</span>(N)); x <span class="ot" style="color: #003B4F;
background-color: null;
font-style: inherit;">&lt;-</span> N[<span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">-</span><span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">length</span>(N)]</span>
<span id="cb2-18">  cf <span class="ot" style="color: #003B4F;
background-color: null;
font-style: inherit;">&lt;-</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">coef</span>(<span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">lm</span>(y <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">~</span> x))</span>
<span id="cb2-19">  r_ex <span class="ot" style="color: #003B4F;
background-color: null;
font-style: inherit;">&lt;-</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">unname</span>(cf[<span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">1</span>]); b_ex <span class="ot" style="color: #003B4F;
background-color: null;
font-style: inherit;">&lt;-</span> <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">-</span><span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">unname</span>(cf[<span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">2</span>])</span>
<span id="cb2-20">  s_ex <span class="ot" style="color: #003B4F;
background-color: null;
font-style: inherit;">&lt;-</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">sqrt</span>(<span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">mean</span>((y <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">-</span> (r_ex <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">-</span> b_ex <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">*</span> x))<span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">^</span><span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">2</span>))      <span class="co" style="color: #5E5E5E;
background-color: null;
font-style: inherit;"># the MLE of sigma divides by n</span></span>
<span id="cb2-21">  nll_K <span class="ot" style="color: #003B4F;
background-color: null;
font-style: inherit;">&lt;-</span> <span class="cf" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">function</span>(th) {</span>
<span id="cb2-22">    <span class="cf" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">if</span> (th[<span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">2</span>] <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">&lt;=</span> <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">1</span>) <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">return</span>(<span class="fl" style="color: #AD0000;
background-color: null;
font-style: inherit;">1e12</span>)</span>
<span id="cb2-23">    <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">-</span><span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">sum</span>(<span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">dnorm</span>(y <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">-</span> th[<span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">1</span>] <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">*</span> (<span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">1</span> <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">-</span> x <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">/</span> th[<span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">2</span>]), <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">0</span>, <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">exp</span>(th[<span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">3</span>]), <span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">log =</span> <span class="cn" style="color: #8f5902;
background-color: null;
font-style: inherit;">TRUE</span>))</span>
<span id="cb2-24">  }</span>
<span id="cb2-25">  nll_b <span class="ot" style="color: #003B4F;
background-color: null;
font-style: inherit;">&lt;-</span> <span class="cf" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">function</span>(th) <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">-</span><span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">sum</span>(<span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">dnorm</span>(y <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">-</span> (th[<span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">1</span>] <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">-</span> th[<span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">2</span>] <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">*</span> x), <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">0</span>, <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">exp</span>(th[<span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">3</span>]), <span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">log =</span> <span class="cn" style="color: #8f5902;
background-color: null;
font-style: inherit;">TRUE</span>))</span>
<span id="cb2-26">  <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">list</span>(<span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">y =</span> y, <span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">x =</span> x, <span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">r_ex =</span> r_ex, <span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">b_ex =</span> b_ex, <span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">K_ex =</span> r_ex <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">/</span> b_ex, <span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">ls_ex =</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">log</span>(s_ex),</span>
<span id="cb2-27">       <span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">nll_K =</span> nll_K, <span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">nll_b =</span> nll_b, <span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">nll_ex =</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">nll_b</span>(<span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">c</span>(r_ex, b_ex, <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">log</span>(s_ex))))</span>
<span id="cb2-28">}</span></code></pre></div></div>
</div>
<p>The two negative log-likelihoods are the same function of the data. One takes (r, K, log sigma); the other takes (r, b, log sigma) with b = r / K. Before anything is fitted it is worth checking that they agree and that the <code>lm()</code> point really is the maximum.</p>
<div class="cell">
<div class="code-copy-outer-scaffold"><div class="sourceCode cell-code" id="cb3" style="background: #f1f3f5;"><pre class="sourceCode r code-with-copy"><code class="sourceCode r"><span id="cb3-1"><span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">set.seed</span>(<span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">77</span>)</span>
<span id="cb3-2">N_one  <span class="ot" style="color: #003B4F;
background-color: null;
font-style: inherit;">&lt;-</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">sim_ricker</span>()</span>
<span id="cb3-3">fm_one <span class="ot" style="color: #003B4F;
background-color: null;
font-style: inherit;">&lt;-</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">make_fit</span>(N_one)</span>
<span id="cb3-4">th_K <span class="ot" style="color: #003B4F;
background-color: null;
font-style: inherit;">&lt;-</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">c</span>(fm_one<span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">$</span>r_ex, fm_one<span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">$</span>K_ex, fm_one<span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">$</span>ls_ex)</span>
<span id="cb3-5">th_b <span class="ot" style="color: #003B4F;
background-color: null;
font-style: inherit;">&lt;-</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">c</span>(fm_one<span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">$</span>r_ex, fm_one<span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">$</span>b_ex, fm_one<span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">$</span>ls_ex)</span>
<span id="cb3-6">same_gap <span class="ot" style="color: #003B4F;
background-color: null;
font-style: inherit;">&lt;-</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">abs</span>(fm_one<span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">$</span><span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">nll_K</span>(th_K) <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">-</span> fm_one<span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">$</span><span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">nll_b</span>(th_b))</span>
<span id="cb3-7">polish   <span class="ot" style="color: #003B4F;
background-color: null;
font-style: inherit;">&lt;-</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">nlminb</span>(th_K, fm_one<span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">$</span>nll_K)</span>
<span id="cb3-8">polish_gain <span class="ot" style="color: #003B4F;
background-color: null;
font-style: inherit;">&lt;-</span> fm_one<span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">$</span>nll_ex <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">-</span> polish<span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">$</span>objective</span>
<span id="cb3-9">polish_move <span class="ot" style="color: #003B4F;
background-color: null;
font-style: inherit;">&lt;-</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">abs</span>(polish<span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">$</span>par[<span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">2</span>] <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">-</span> fm_one<span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">$</span>K_ex) <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">/</span> fm_one<span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">$</span>K_ex</span></code></pre></div></div>
</div>
<p>On one simulated series the two spellings differ in the negative log-likelihood by less than one in a billion at the <code>lm()</code> point. Handing that point to <code>nlminb()</code> as a start changes the negative log-likelihood by less than one in a billion and K by a fraction of exactly zero: the linear regression is the maximum, and the search has nowhere better to go. The exact carrying capacity for this series is 5509 and the exact r is 0.560.</p>
</section>
<section id="ten-calls-from-one-start" class="level2">
<h2 id="ten-calls-from-one-start-h" class="anchored" data-anchor-id="ten-calls-from-one-start">Ten calls from one start</h2>
<p>Ten ways of maximising the same likelihood, all from the same start of r = 0.30, K = 3000 and sigma = 0.3, expressed identically in both spellings. The start is a plausible guess by someone who knows the colony is in the low thousands; it is fixed in the code above, and a second, more careful start is tried later. Four of the calls are BFGS in (r, K): the default call, the same call with <code>maxit = 5000</code>, the same call with the finite-difference step <code>ndeps</code> shrunk to <img src="https://latex.codecogs.com/png.latex?10%5E%7B-6%7D">, and the same call with <code>parscale = c(1, 3000, 1)</code>, which tells <code>optim()</code> that K is about three thousand times larger than the other two parameters. The fifth is BFGS in (r, b). Then come Nelder-Mead (Nelder and Mead 1965), which uses no gradient and is given <code>maxit = 2000</code> and a <code>reltol</code> of <img src="https://latex.codecogs.com/png.latex?10%5E%7B-11%7D">, and L-BFGS-B and <code>nlminb()</code>, each run with and without box bounds, since the bounded versions are how most people call them.</p>
<div class="cell">
<div class="code-copy-outer-scaffold"><div class="sourceCode cell-code" id="cb4" style="background: #f1f3f5;"><pre class="sourceCode r code-with-copy"><code class="sourceCode r"><span id="cb4-1">fit_lab <span class="ot" style="color: #003B4F;
background-color: null;
font-style: inherit;">&lt;-</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">c</span>(<span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">def  =</span> <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"BFGS, default"</span>,       <span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">maxit =</span> <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"BFGS, maxit = 5000"</span>,</span>
<span id="cb4-2">             <span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">nd6  =</span> <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"BFGS, ndeps = 1e-6"</span>,  <span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">pars  =</span> <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"BFGS, parscale"</span>,</span>
<span id="cb4-3">             <span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">rb   =</span> <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"BFGS in (r, b)"</span>,      <span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">nm    =</span> <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"Nelder-Mead"</span>,</span>
<span id="cb4-4">             <span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">lb   =</span> <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"L-BFGS-B, box"</span>,       <span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">lbn   =</span> <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"L-BFGS-B, no box"</span>,</span>
<span id="cb4-5">             <span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">nlb  =</span> <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"nlminb, box"</span>,         <span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">nlbn  =</span> <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"nlminb, no box"</span>)</span>
<span id="cb4-6"></span>
<span id="cb4-7">one_row <span class="ot" style="color: #003B4F;
background-color: null;
font-style: inherit;">&lt;-</span> <span class="cf" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">function</span>(o, <span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">form =</span> <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"K"</span>)</span>
<span id="cb4-8">  <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">c</span>(<span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">K =</span> <span class="cf" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">if</span> (form <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">==</span> <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"K"</span>) o<span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">$</span>par[<span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">2</span>] <span class="cf" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">else</span> o<span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">$</span>par[<span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">1</span>] <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">/</span> o<span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">$</span>par[<span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">2</span>],</span>
<span id="cb4-9">    <span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">nll =</span> o<span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">$</span>value, <span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">code =</span> o<span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">$</span>convergence)</span>
<span id="cb4-10">nlm_row <span class="ot" style="color: #003B4F;
background-color: null;
font-style: inherit;">&lt;-</span> <span class="cf" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">function</span>(o) <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">c</span>(<span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">K =</span> o<span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">$</span>par[<span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">2</span>], <span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">nll =</span> o<span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">$</span>objective, <span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">code =</span> o<span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">$</span>convergence)</span>
<span id="cb4-11"></span>
<span id="cb4-12">run_fitters <span class="ot" style="color: #003B4F;
background-color: null;
font-style: inherit;">&lt;-</span> <span class="cf" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">function</span>(fm, st, <span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">which =</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">names</span>(fit_lab)) {</span>
<span id="cb4-13">  sb <span class="ot" style="color: #003B4F;
background-color: null;
font-style: inherit;">&lt;-</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">c</span>(st[<span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">1</span>], st[<span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">1</span>] <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">/</span> st[<span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">2</span>], st[<span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">3</span>]); ps <span class="ot" style="color: #003B4F;
background-color: null;
font-style: inherit;">&lt;-</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">c</span>(<span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">1</span>, st[<span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">2</span>], <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">1</span>)</span>
<span id="cb4-14">  calls <span class="ot" style="color: #003B4F;
background-color: null;
font-style: inherit;">&lt;-</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">list</span>(</span>
<span id="cb4-15">    <span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">def   =</span> <span class="cf" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">function</span>() <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">one_row</span>(<span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">optim</span>(st, fm<span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">$</span>nll_K, <span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">method =</span> <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"BFGS"</span>)),</span>
<span id="cb4-16">    <span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">maxit =</span> <span class="cf" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">function</span>() <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">one_row</span>(<span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">optim</span>(st, fm<span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">$</span>nll_K, <span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">method =</span> <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"BFGS"</span>,</span>
<span id="cb4-17">                                     <span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">control =</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">list</span>(<span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">maxit =</span> <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">5000</span>))),</span>
<span id="cb4-18">    <span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">nd6   =</span> <span class="cf" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">function</span>() <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">one_row</span>(<span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">optim</span>(st, fm<span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">$</span>nll_K, <span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">method =</span> <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"BFGS"</span>,</span>
<span id="cb4-19">                                     <span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">control =</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">list</span>(<span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">ndeps =</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">rep</span>(<span class="fl" style="color: #AD0000;
background-color: null;
font-style: inherit;">1e-6</span>, <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">3</span>)))),</span>
<span id="cb4-20">    <span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">pars  =</span> <span class="cf" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">function</span>() <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">one_row</span>(<span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">optim</span>(st, fm<span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">$</span>nll_K, <span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">method =</span> <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"BFGS"</span>,</span>
<span id="cb4-21">                                     <span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">control =</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">list</span>(<span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">parscale =</span> ps))),</span>
<span id="cb4-22">    <span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">rb    =</span> <span class="cf" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">function</span>() <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">one_row</span>(<span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">optim</span>(sb, fm<span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">$</span>nll_b, <span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">method =</span> <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"BFGS"</span>), <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"b"</span>),</span>
<span id="cb4-23">    <span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">nm    =</span> <span class="cf" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">function</span>() <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">one_row</span>(<span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">optim</span>(st, fm<span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">$</span>nll_K, <span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">method =</span> <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"Nelder-Mead"</span>,</span>
<span id="cb4-24">                                     <span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">control =</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">list</span>(<span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">maxit =</span> <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">2000</span>, <span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">reltol =</span> <span class="fl" style="color: #AD0000;
background-color: null;
font-style: inherit;">1e-11</span>))),</span>
<span id="cb4-25">    <span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">lb    =</span> <span class="cf" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">function</span>() <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">one_row</span>(<span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">optim</span>(st, fm<span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">$</span>nll_K, <span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">method =</span> <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"L-BFGS-B"</span>,</span>
<span id="cb4-26">                                     <span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">lower =</span> box_lo, <span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">upper =</span> box_hi)),</span>
<span id="cb4-27">    <span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">lbn   =</span> <span class="cf" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">function</span>() <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">one_row</span>(<span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">optim</span>(st, fm<span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">$</span>nll_K, <span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">method =</span> <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"L-BFGS-B"</span>)),</span>
<span id="cb4-28">    <span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">nlb   =</span> <span class="cf" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">function</span>() <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">nlm_row</span>(<span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">nlminb</span>(st, fm<span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">$</span>nll_K, <span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">lower =</span> box_lo, <span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">upper =</span> box_hi)),</span>
<span id="cb4-29">    <span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">nlbn  =</span> <span class="cf" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">function</span>() <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">nlm_row</span>(<span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">nlminb</span>(st, fm<span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">$</span>nll_K)))</span>
<span id="cb4-30">  <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">vapply</span>(calls[which], <span class="cf" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">function</span>(f) <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">f</span>(), <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">numeric</span>(<span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">3</span>))</span>
<span id="cb4-31">}</span>
<span id="cb4-32"></span>
<span id="cb4-33">n_blk <span class="ot" style="color: #003B4F;
background-color: null;
font-style: inherit;">&lt;-</span> <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">5</span>; n_ser <span class="ot" style="color: #003B4F;
background-color: null;
font-style: inherit;">&lt;-</span> <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">100</span>          <span class="co" style="color: #5E5E5E;
background-color: null;
font-style: inherit;"># fixed before any rate was inspected</span></span>
<span id="cb4-34">series <span class="ot" style="color: #003B4F;
background-color: null;
font-style: inherit;">&lt;-</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">unlist</span>(<span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">lapply</span>(<span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">seq_len</span>(n_blk), <span class="cf" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">function</span>(bl) {</span>
<span id="cb4-35">  <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">set.seed</span>(<span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">1000</span> <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">+</span> bl)</span>
<span id="cb4-36">  <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">lapply</span>(<span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">seq_len</span>(n_ser), <span class="cf" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">function</span>(i) <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">sim_ricker</span>())</span>
<span id="cb4-37">}), <span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">recursive =</span> <span class="cn" style="color: #8f5902;
background-color: null;
font-style: inherit;">FALSE</span>)</span>
<span id="cb4-38">blk <span class="ot" style="color: #003B4F;
background-color: null;
font-style: inherit;">&lt;-</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">rep</span>(<span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">seq_len</span>(n_blk), <span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">each =</span> n_ser)</span>
<span id="cb4-39">fms <span class="ot" style="color: #003B4F;
background-color: null;
font-style: inherit;">&lt;-</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">lapply</span>(series, make_fit)</span>
<span id="cb4-40">K_ex  <span class="ot" style="color: #003B4F;
background-color: null;
font-style: inherit;">&lt;-</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">vapply</span>(fms, <span class="cf" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">function</span>(f) f<span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">$</span>K_ex, <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">0</span>)</span>
<span id="cb4-41">nll_ex <span class="ot" style="color: #003B4F;
background-color: null;
font-style: inherit;">&lt;-</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">vapply</span>(fms, <span class="cf" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">function</span>(f) f<span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">$</span>nll_ex, <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">0</span>)</span>
<span id="cb4-42">t_main <span class="ot" style="color: #003B4F;
background-color: null;
font-style: inherit;">&lt;-</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">system.time</span>(</span>
<span id="cb4-43">  res_far <span class="ot" style="color: #003B4F;
background-color: null;
font-style: inherit;">&lt;-</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">vapply</span>(fms, run_fitters, <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">matrix</span>(<span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">0</span>, <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">3</span>, <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">length</span>(fit_lab)), <span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">st =</span> start_far)</span>
<span id="cb4-44">)[[<span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"user.self"</span>]]</span>
<span id="cb4-45"><span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">dimnames</span>(res_far)[[<span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">2</span>]] <span class="ot" style="color: #003B4F;
background-color: null;
font-style: inherit;">&lt;-</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">names</span>(fit_lab)</span></code></pre></div></div>
</div>
<div class="cell">
<div class="code-copy-outer-scaffold"><div class="sourceCode cell-code" id="cb5" style="background: #f1f3f5;"><pre class="sourceCode r code-with-copy"><code class="sourceCode r"><span id="cb5-1">rel_err <span class="ot" style="color: #003B4F;
background-color: null;
font-style: inherit;">&lt;-</span> <span class="cf" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">function</span>(res, f) (res[<span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"K"</span>, f, ] <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">-</span> K_ex) <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">/</span> K_ex</span>
<span id="cb5-2">summ <span class="ot" style="color: #003B4F;
background-color: null;
font-style: inherit;">&lt;-</span> <span class="cf" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">function</span>(res, f, st_K) {</span>
<span id="cb5-3">  re <span class="ot" style="color: #003B4F;
background-color: null;
font-style: inherit;">&lt;-</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">rel_err</span>(res, f)</span>
<span id="cb5-4">  <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">data.frame</span>(<span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">fitter =</span> f,</span>
<span id="cb5-5">             <span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">block =</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">seq_len</span>(n_blk),</span>
<span id="cb5-6">             <span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">med_rel =</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">tapply</span>(<span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">abs</span>(re), blk, median),</span>
<span id="cb5-7">             <span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">off10   =</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">tapply</span>(<span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">abs</span>(re) <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">&gt;</span> <span class="fl" style="color: #AD0000;
background-color: null;
font-style: inherit;">0.10</span>, blk, mean),</span>
<span id="cb5-8">             <span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">code0   =</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">tapply</span>(res[<span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"code"</span>, f, ] <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">==</span> <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">0</span>, blk, mean),</span>
<span id="cb5-9">             <span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">deficit =</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">tapply</span>(res[<span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"nll"</span>, f, ] <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">-</span> nll_ex, blk, median),</span>
<span id="cb5-10">             <span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">below   =</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">tapply</span>(re <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">&lt;</span> <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">0</span>, blk, mean))</span>
<span id="cb5-11">}</span>
<span id="cb5-12">tab_far <span class="ot" style="color: #003B4F;
background-color: null;
font-style: inherit;">&lt;-</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">do.call</span>(rbind, <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">lapply</span>(<span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">names</span>(fit_lab), <span class="cf" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">function</span>(f) <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">summ</span>(res_far, f)))</span>
<span id="cb5-13">rng <span class="ot" style="color: #003B4F;
background-color: null;
font-style: inherit;">&lt;-</span> <span class="cf" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">function</span>(f, col, <span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">d =</span> <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">3</span>, <span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">tab =</span> tab_far, <span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">as_pct =</span> <span class="cn" style="color: #8f5902;
background-color: null;
font-style: inherit;">FALSE</span>) {</span>
<span id="cb5-14">  v <span class="ot" style="color: #003B4F;
background-color: null;
font-style: inherit;">&lt;-</span> tab[tab<span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">$</span>fitter <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">==</span> f, col]</span>
<span id="cb5-15">  <span class="cf" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">if</span> (as_pct) v <span class="ot" style="color: #003B4F;
background-color: null;
font-style: inherit;">&lt;-</span> <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">100</span> <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">*</span> v</span>
<span id="cb5-16">  <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">paste</span>(<span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">sprintf</span>(<span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">paste0</span>(<span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"%."</span>, d, <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"f"</span>), <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">range</span>(v)), <span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">collapse =</span> <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">" to "</span>)</span>
<span id="cb5-17">}</span>
<span id="cb5-18">pool <span class="ot" style="color: #003B4F;
background-color: null;
font-style: inherit;">&lt;-</span> <span class="cf" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">function</span>(f, fun, <span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">res =</span> res_far) <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">fun</span>(res, f)</span>
<span id="cb5-19">share_code0 <span class="ot" style="color: #003B4F;
background-color: null;
font-style: inherit;">&lt;-</span> <span class="cf" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">function</span>(res, f) <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">mean</span>(res[<span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"code"</span>, f, ] <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">==</span> <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">0</span>)</span>
<span id="cb5-20">share_off   <span class="ot" style="color: #003B4F;
background-color: null;
font-style: inherit;">&lt;-</span> <span class="cf" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">function</span>(res, f) <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">mean</span>(<span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">abs</span>(<span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">rel_err</span>(res, f)) <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">&gt;</span> <span class="fl" style="color: #AD0000;
background-color: null;
font-style: inherit;">0.10</span>)</span>
<span id="cb5-21">med_abs     <span class="ot" style="color: #003B4F;
background-color: null;
font-style: inherit;">&lt;-</span> <span class="cf" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">function</span>(res, f) <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">median</span>(<span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">abs</span>(<span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">rel_err</span>(res, f)))</span>
<span id="cb5-22">n_all <span class="ot" style="color: #003B4F;
background-color: null;
font-style: inherit;">&lt;-</span> n_blk <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">*</span> n_ser</span>
<span id="cb5-23">mcse_share <span class="ot" style="color: #003B4F;
background-color: null;
font-style: inherit;">&lt;-</span> <span class="cf" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">function</span>(p) <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">sqrt</span>(p <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">*</span> (<span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">1</span> <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">-</span> p) <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">/</span> n_all)</span>
<span id="cb5-24">exact_set <span class="ot" style="color: #003B4F;
background-color: null;
font-style: inherit;">&lt;-</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">c</span>(<span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"pars"</span>, <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"rb"</span>, <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"nm"</span>, <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"nlb"</span>, <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"nlbn"</span>)</span>
<span id="cb5-25">worst_exact <span class="ot" style="color: #003B4F;
background-color: null;
font-style: inherit;">&lt;-</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">max</span>(<span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">vapply</span>(exact_set, <span class="cf" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">function</span>(f) <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">max</span>(<span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">abs</span>(<span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">rel_err</span>(res_far, f))), <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">0</span>))</span>
<span id="cb5-26">chi_half <span class="ot" style="color: #003B4F;
background-color: null;
font-style: inherit;">&lt;-</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">qchisq</span>(<span class="fl" style="color: #AD0000;
background-color: null;
font-style: inherit;">0.95</span>, <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">1</span>) <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">/</span> <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">2</span>     <span class="co" style="color: #5E5E5E;
background-color: null;
font-style: inherit;"># profile-likelihood cut-off for a 95 per cent interval</span></span></code></pre></div></div>
</div>
<p>The default BFGS call in (r, K) lands a median 35.7 to 39.9 per cent away from the exact carrying capacity, per block of 100 series, and it errs downwards, towards the start: in 99.4 per cent of all 500 series the fitted K is below the exact one. The share more than ten per cent off is 0.97 to 0.99 per block, and the median shortfall in log-likelihood against the exact maximum is 4.62 to 4.99 units, which is not a rounding difference: a 95 per cent profile-likelihood interval for one parameter reaches only 1.92 units below the maximum. The fit reports convergence code 0 in 0.27 to 0.39 of the series in a block.</p>
<p>Five of the ten calls find the exact maximum every time, to within the tolerance of the search. BFGS with <code>parscale</code>, BFGS in (r, b), Nelder-Mead and <code>nlminb()</code> with and without bounds all return the <code>lm()</code> answer, and the largest relative error in K among them over all 500 series is 0.000082. Those five report code 0 in every series. The two L-BFGS-B calls are exact in median but not every time, and they get their own section below.</p>
<div class="cell">
<div class="code-copy-outer-scaffold"><div class="sourceCode cell-code" id="cb6" style="background: #f1f3f5;"><pre class="sourceCode r code-with-copy"><code class="sourceCode r"><span id="cb6-1">pct <span class="ot" style="color: #003B4F;
background-color: null;
font-style: inherit;">&lt;-</span> <span class="cf" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">function</span>(v) <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">ifelse</span>(<span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">abs</span>(v) <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">&lt;</span> <span class="fl" style="color: #AD0000;
background-color: null;
font-style: inherit;">1e-9</span>, <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"0%"</span>, <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">sprintf</span>(<span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"%+.0f%%"</span>, <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">100</span> <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">*</span> v))</span>
<span id="cb6-2">sci_lab <span class="ot" style="color: #003B4F;
background-color: null;
font-style: inherit;">&lt;-</span> <span class="cf" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">function</span>(x) <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">as.expression</span>(<span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">lapply</span>(<span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">as.character</span>(x), <span class="cf" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">function</span>(s)   <span class="co" style="color: #5E5E5E;
background-color: null;
font-style: inherit;"># 1e-6 as a power of ten</span></span>
<span id="cb6-3">  <span class="cf" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">if</span> (<span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">grepl</span>(<span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"1e-6"</span>, s, <span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">fixed =</span> <span class="cn" style="color: #8f5902;
background-color: null;
font-style: inherit;">TRUE</span>)) <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">bquote</span>(.(<span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">sub</span>(<span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"1e-6"</span>, <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">""</span>, s, <span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">fixed =</span> <span class="cn" style="color: #8f5902;
background-color: null;
font-style: inherit;">TRUE</span>)) <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">*</span> <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">10</span><span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">^-</span><span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">6</span>) <span class="cf" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">else</span> s))</span>
<span id="cb6-4">err_long <span class="ot" style="color: #003B4F;
background-color: null;
font-style: inherit;">&lt;-</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">do.call</span>(rbind, <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">lapply</span>(<span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">names</span>(fit_lab), <span class="cf" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">function</span>(f)</span>
<span id="cb6-5">  <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">data.frame</span>(<span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">fitter =</span> fit_lab[[f]], <span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">err =</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">rel_err</span>(res_far, f),</span>
<span id="cb6-6">             <span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">code0 =</span> res_far[<span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"code"</span>, f, ] <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">==</span> <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">0</span>)))</span>
<span id="cb6-7">err_long<span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">$</span>fitter <span class="ot" style="color: #003B4F;
background-color: null;
font-style: inherit;">&lt;-</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">factor</span>(err_long<span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">$</span>fitter, <span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">levels =</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">rev</span>(fit_lab))</span>
<span id="cb6-8">err_long<span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">$</span>status <span class="ot" style="color: #003B4F;
background-color: null;
font-style: inherit;">&lt;-</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">ifelse</span>(err_long<span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">$</span>code0, <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"reports code 0"</span>, <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"reports code 1"</span>)</span>
<span id="cb6-9">share_df <span class="ot" style="color: #003B4F;
background-color: null;
font-style: inherit;">&lt;-</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">data.frame</span>(<span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">fitter =</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">factor</span>(fit_lab, <span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">levels =</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">rev</span>(fit_lab)),</span>
<span id="cb6-10">                       <span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">code0 =</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">vapply</span>(<span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">names</span>(fit_lab), <span class="cf" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">function</span>(f) <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">share_code0</span>(res_far, f), <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">0</span>),</span>
<span id="cb6-11">                       <span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">off10 =</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">vapply</span>(<span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">names</span>(fit_lab), <span class="cf" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">function</span>(f) <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">share_off</span>(res_far, f), <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">0</span>))</span>
<span id="cb6-12"><span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">set.seed</span>(<span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">5</span>)</span>
<span id="cb6-13">p_err <span class="ot" style="color: #003B4F;
background-color: null;
font-style: inherit;">&lt;-</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">ggplot</span>(err_long, <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">aes</span>(err, fitter, <span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">colour =</span> status)) <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">+</span></span>
<span id="cb6-14">  <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">geom_vline</span>(<span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">xintercept =</span> <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">0</span>, <span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">colour =</span> te_ink, <span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">linewidth =</span> <span class="fl" style="color: #AD0000;
background-color: null;
font-style: inherit;">0.4</span>) <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">+</span></span>
<span id="cb6-15">  <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">geom_jitter</span>(<span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">height =</span> <span class="fl" style="color: #AD0000;
background-color: null;
font-style: inherit;">0.22</span>, <span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">width =</span> <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">0</span>, <span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">size =</span> <span class="fl" style="color: #AD0000;
background-color: null;
font-style: inherit;">0.8</span>, <span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">alpha =</span> <span class="fl" style="color: #AD0000;
background-color: null;
font-style: inherit;">0.55</span>) <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">+</span></span>
<span id="cb6-16">  <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">scale_colour_manual</span>(<span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">values =</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">c</span>(te_forest, te_rust), <span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">name =</span> <span class="cn" style="color: #8f5902;
background-color: null;
font-style: inherit;">NULL</span>) <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">+</span></span>
<span id="cb6-17">  <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">scale_x_continuous</span>(<span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">labels =</span> pct) <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">+</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">scale_y_discrete</span>(<span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">labels =</span> sci_lab) <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">+</span></span>
<span id="cb6-18">  <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">labs</span>(<span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">x =</span> <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"fitted K relative to the exact MLE"</span>, <span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">y =</span> <span class="cn" style="color: #8f5902;
background-color: null;
font-style: inherit;">NULL</span>,</span>
<span id="cb6-19">       <span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">title =</span> <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"Where each call leaves K"</span>, <span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">subtitle =</span> <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"one point per series, same start"</span>) <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">+</span></span>
<span id="cb6-20">  <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">guides</span>(<span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">colour =</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">guide_legend</span>(<span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">nrow =</span> <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">2</span>, <span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">override.aes =</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">list</span>(<span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">size =</span> <span class="fl" style="color: #AD0000;
background-color: null;
font-style: inherit;">2.5</span>, <span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">alpha =</span> <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">1</span>))) <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">+</span></span>
<span id="cb6-21">  <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">theme_datasheet</span>() <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">+</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">theme</span>(<span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">legend.position =</span> <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"bottom"</span>)</span>
<span id="cb6-22">share_long <span class="ot" style="color: #003B4F;
background-color: null;
font-style: inherit;">&lt;-</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">rbind</span>(<span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">data.frame</span>(<span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">fitter =</span> share_df<span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">$</span>fitter, <span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">share =</span> share_df<span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">$</span>code0,</span>
<span id="cb6-23">                               <span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">what =</span> <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"reports code 0"</span>),</span>
<span id="cb6-24">                    <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">data.frame</span>(<span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">fitter =</span> share_df<span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">$</span>fitter, <span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">share =</span> share_df<span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">$</span>off10,</span>
<span id="cb6-25">                               <span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">what =</span> <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"more than 10% off"</span>))</span>
<span id="cb6-26">p_share <span class="ot" style="color: #003B4F;
background-color: null;
font-style: inherit;">&lt;-</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">ggplot</span>(share_long, <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">aes</span>(share, fitter, <span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">colour =</span> what, <span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">shape =</span> what)) <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">+</span></span>
<span id="cb6-27">  <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">geom_point</span>(<span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">size =</span> <span class="fl" style="color: #AD0000;
background-color: null;
font-style: inherit;">2.6</span>, <span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">stroke =</span> <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">1</span>) <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">+</span></span>
<span id="cb6-28">  <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">scale_colour_manual</span>(<span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">values =</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">c</span>(te_rust, te_forest), <span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">name =</span> <span class="cn" style="color: #8f5902;
background-color: null;
font-style: inherit;">NULL</span>) <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">+</span></span>
<span id="cb6-29">  <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">scale_shape_manual</span>(<span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">values =</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">c</span>(<span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">17</span>, <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">16</span>), <span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">name =</span> <span class="cn" style="color: #8f5902;
background-color: null;
font-style: inherit;">NULL</span>) <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">+</span></span>
<span id="cb6-30">  <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">scale_x_continuous</span>(<span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">limits =</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">c</span>(<span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">0</span>, <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">1</span>), <span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">breaks =</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">c</span>(<span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">0</span>, <span class="fl" style="color: #AD0000;
background-color: null;
font-style: inherit;">0.5</span>, <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">1</span>)) <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">+</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">scale_y_discrete</span>(<span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">labels =</span> sci_lab) <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">+</span></span>
<span id="cb6-31">  <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">guides</span>(<span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">colour =</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">guide_legend</span>(<span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">nrow =</span> <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">2</span>), <span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">shape =</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">guide_legend</span>(<span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">nrow =</span> <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">2</span>)) <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">+</span></span>
<span id="cb6-32">  <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">labs</span>(<span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">x =</span> <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"share of 500 series"</span>, <span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">y =</span> <span class="cn" style="color: #8f5902;
background-color: null;
font-style: inherit;">NULL</span>, <span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">title =</span> <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"What the call says"</span>,</span>
<span id="cb6-33">       <span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">subtitle =</span> <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"and how often it is wrong"</span>) <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">+</span></span>
<span id="cb6-34">  <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">theme_datasheet</span>() <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">+</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">theme</span>(<span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">legend.position =</span> <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"bottom"</span>, <span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">axis.text.y =</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">element_blank</span>())</span>
<span id="cb6-35">p_err <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">+</span> p_share <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">+</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">plot_layout</span>(<span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">widths =</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">c</span>(<span class="fl" style="color: #AD0000;
background-color: null;
font-style: inherit;">1.6</span>, <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">1</span>)) <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">+</span></span>
<span id="cb6-36">  <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">plot_annotation</span>(<span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">theme =</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">theme_datasheet</span>())</span></code></pre></div></div>
<div class="cell-output-display">
<div id="fig-fitters" class="quarto-float quarto-figure quarto-figure-center anchored" alt="Two panels. Left: one strip of points per fitting call, one point per series, showing fitted K relative to the exact maximum likelihood estimate on an axis from about minus 55 to plus 15 per cent. The three unscaled BFGS rows (default, maxit = 5000, ndeps = 10 to the minus 6) spread from about minus 55 to minus 20 per cent with a few stragglers up to plus 15; the default and ndeps rows are mostly red for code 1 with a dark green cluster near minus 45 per cent, and the maxit row is mostly green and stretches right to zero. The parscale, (r, b), Nelder-Mead and both nlminb rows are single green columns at zero. The two L-BFGS-B rows sit at zero with a small green cluster between minus 55 and minus 40 per cent. Right: for each call a green circle for the share reporting code 0 and a red triangle for the share more than ten per cent off. Default and ndeps have circles near 0.33 and triangles near 1, maxit a circle near 0.6 and a triangle near 0.75; every other row has its circle at 1 and its triangle at or near 0, the L-BFGS-B triangles at about 0.06 and 0.11.">
<figure class="quarto-float quarto-float-fig figure">
<div aria-describedby="fig-fitters-caption-0ceaefa1-69ba-4598-a22c-09a6ac19f8ca">
<img src="https://tidyecology.com/posts/parameter-scale-and-what-optim-finds/index_files/figure-html/fig-fitters-1.png" class="img-fluid figure-img" alt="Two panels. Left: one strip of points per fitting call, one point per series, showing fitted K relative to the exact maximum likelihood estimate on an axis from about minus 55 to plus 15 per cent. The three unscaled BFGS rows (default, maxit = 5000, ndeps = 10 to the minus 6) spread from about minus 55 to minus 20 per cent with a few stragglers up to plus 15; the default and ndeps rows are mostly red for code 1 with a dark green cluster near minus 45 per cent, and the maxit row is mostly green and stretches right to zero. The parscale, (r, b), Nelder-Mead and both nlminb rows are single green columns at zero. The two L-BFGS-B rows sit at zero with a small green cluster between minus 55 and minus 40 per cent. Right: for each call a green circle for the share reporting code 0 and a red triangle for the share more than ten per cent off. Default and ndeps have circles near 0.33 and triangles near 1, maxit a circle near 0.6 and a triangle near 0.75; every other row has its circle at 1 and its triangle at or near 0, the L-BFGS-B triangles at about 0.06 and 0.11." width="672">
</div>
<figcaption class="quarto-float-caption-bottom quarto-float-caption quarto-float-fig" id="fig-fitters-caption-0ceaefa1-69ba-4598-a22c-09a6ac19f8ca">
Figure&nbsp;1: Signed relative error in K against the exact maximum likelihood estimate, for ten calls from the same start over 500 simulated series, and for each call the share of series reporting convergence code 0 (circles) and the share more than ten per cent off (triangles).
</figcaption>
</figure>
</div>
</div>
</div>
</section>
<section id="raising-maxit-buys-the-warning-away" class="level2">
<h2 id="raising-maxit-buys-the-warning-away-h" class="anchored" data-anchor-id="raising-maxit-buys-the-warning-away">Raising maxit buys the warning away</h2>
<p>The default BFGS call stops after 100 iterations, and when it does it returns code 1, which the help page describes as the iteration limit having been reached. A reader who checks the code sees a 1, raises <code>maxit</code>, reruns, and gets a 0. That is the repair everyone reaches for, and it is exactly what the site’s own fits do when they pass <code>control = list(maxit = 2000)</code>.</p>
<div class="cell">
<div class="code-copy-outer-scaffold"><div class="sourceCode cell-code" id="cb7" style="background: #f1f3f5;"><pre class="sourceCode r code-with-copy"><code class="sourceCode r"><span id="cb7-1">code0_def <span class="ot" style="color: #003B4F;
background-color: null;
font-style: inherit;">&lt;-</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">share_code0</span>(res_far, <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"def"</span>); code0_mx <span class="ot" style="color: #003B4F;
background-color: null;
font-style: inherit;">&lt;-</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">share_code0</span>(res_far, <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"maxit"</span>)</span>
<span id="cb7-2">off_def <span class="ot" style="color: #003B4F;
background-color: null;
font-style: inherit;">&lt;-</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">share_off</span>(res_far, <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"def"</span>);     off_mx <span class="ot" style="color: #003B4F;
background-color: null;
font-style: inherit;">&lt;-</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">share_off</span>(res_far, <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"maxit"</span>)</span>
<span id="cb7-3">re_mx <span class="ot" style="color: #003B4F;
background-color: null;
font-style: inherit;">&lt;-</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">rel_err</span>(res_far, <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"maxit"</span>)</span>
<span id="cb7-4">clean_mx <span class="ot" style="color: #003B4F;
background-color: null;
font-style: inherit;">&lt;-</span> res_far[<span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"code"</span>, <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"maxit"</span>, ] <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">==</span> <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">0</span></span>
<span id="cb7-5">off_clean_mx <span class="ot" style="color: #003B4F;
background-color: null;
font-style: inherit;">&lt;-</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">mean</span>(<span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">abs</span>(re_mx[clean_mx]) <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">&gt;</span> <span class="fl" style="color: #AD0000;
background-color: null;
font-style: inherit;">0.10</span>)</span>
<span id="cb7-6">n_clean_off  <span class="ot" style="color: #003B4F;
background-color: null;
font-style: inherit;">&lt;-</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">sum</span>(<span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">abs</span>(re_mx[clean_mx]) <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">&gt;</span> <span class="fl" style="color: #AD0000;
background-color: null;
font-style: inherit;">0.10</span>)</span>
<span id="cb7-7">limit_mx <span class="ot" style="color: #003B4F;
background-color: null;
font-style: inherit;">&lt;-</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">mean</span>(res_far[<span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"code"</span>, <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"maxit"</span>, ] <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">==</span> <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">1</span>)</span>
<span id="cb7-8">flip <span class="ot" style="color: #003B4F;
background-color: null;
font-style: inherit;">&lt;-</span> res_far[<span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"code"</span>, <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"def"</span>, ] <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">==</span> <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">1</span> <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">&amp;</span> clean_mx</span>
<span id="cb7-9">n_flip <span class="ot" style="color: #003B4F;
background-color: null;
font-style: inherit;">&lt;-</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">sum</span>(flip); n_flip_off <span class="ot" style="color: #003B4F;
background-color: null;
font-style: inherit;">&lt;-</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">sum</span>(<span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">abs</span>(re_mx[flip]) <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">&gt;</span> <span class="fl" style="color: #AD0000;
background-color: null;
font-style: inherit;">0.10</span>)</span>
<span id="cb7-10">med_def_clean <span class="ot" style="color: #003B4F;
background-color: null;
font-style: inherit;">&lt;-</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">median</span>(<span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">abs</span>(<span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">rel_err</span>(res_far, <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"def"</span>)[res_far[<span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"code"</span>, <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"def"</span>, ] <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">==</span> <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">0</span>]))</span>
<span id="cb7-11">code1_def <span class="ot" style="color: #003B4F;
background-color: null;
font-style: inherit;">&lt;-</span> res_far[<span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"code"</span>, <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"def"</span>, ] <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">==</span> <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">1</span></span>
<span id="cb7-12">flip_share  <span class="ot" style="color: #003B4F;
background-color: null;
font-style: inherit;">&lt;-</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">mean</span>(res_far[<span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"code"</span>, <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"maxit"</span>, code1_def] <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">==</span> <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">0</span>)   <span class="co" style="color: #5E5E5E;
background-color: null;
font-style: inherit;"># warnings removed</span></span>
<span id="cb7-13">off_def_set <span class="ot" style="color: #003B4F;
background-color: null;
font-style: inherit;">&lt;-</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">abs</span>(<span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">rel_err</span>(res_far, <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"def"</span>)) <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">&gt;</span> <span class="fl" style="color: #AD0000;
background-color: null;
font-style: inherit;">0.10</span></span>
<span id="cb7-14">fixed_share <span class="ot" style="color: #003B4F;
background-color: null;
font-style: inherit;">&lt;-</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">mean</span>(<span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">abs</span>(re_mx[off_def_set]) <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">&lt;=</span> <span class="fl" style="color: #AD0000;
background-color: null;
font-style: inherit;">0.10</span>)             <span class="co" style="color: #5E5E5E;
background-color: null;
font-style: inherit;"># errors removed</span></span>
<span id="cb7-15"><span class="co" style="color: #5E5E5E;
background-color: null;
font-style: inherit;"># the other lever: a tighter tolerance at the default iteration limit</span></span>
<span id="cb7-16">res_tol <span class="ot" style="color: #003B4F;
background-color: null;
font-style: inherit;">&lt;-</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">vapply</span>(fms, <span class="cf" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">function</span>(fm) <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">one_row</span>(<span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">optim</span>(start_far, fm<span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">$</span>nll_K, <span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">method =</span> <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"BFGS"</span>,</span>
<span id="cb7-17">                                           <span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">control =</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">list</span>(<span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">reltol =</span> <span class="fl" style="color: #AD0000;
background-color: null;
font-style: inherit;">1e-12</span>))), <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">numeric</span>(<span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">3</span>))</span>
<span id="cb7-18">code0_tol <span class="ot" style="color: #003B4F;
background-color: null;
font-style: inherit;">&lt;-</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">mean</span>(res_tol[<span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"code"</span>, ] <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">==</span> <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">0</span>)</span>
<span id="cb7-19">med_tol   <span class="ot" style="color: #003B4F;
background-color: null;
font-style: inherit;">&lt;-</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">median</span>(<span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">abs</span>(res_tol[<span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"K"</span>, ] <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">-</span> K_ex) <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">/</span> K_ex)</span></code></pre></div></div>
</div>
<p>With <code>maxit = 5000</code> the median relative error in K falls to 15.4 to 32.8 per cent per block, and the share of series more than ten per cent off falls to 0.67 to 0.83. Better, but still a fit that misses the carrying capacity by more than a tenth in most series. The median log-likelihood shortfall is 1.78 to 3.24 units. What changes most is the message: pooled over all 500 series, the share reporting convergence code 0 rises from 0.33 to 0.61, with a Monte Carlo standard error of at most 0.02 on each. Of the 306 series in which the raised limit reports clean convergence, 235 (77 per cent) are still more than ten per cent off, and 0.39 of all fits hit even the raised limit of 5000 iterations.</p>
<p>The code 0 from the default call is no safer. Among the default fits that report code 0, the median error in K is 44 per cent. The only warning the reader ever gets is a code 1, and the obvious fix removes the warning more reliably than it removes the error: of the default fits that returned code 1, 0.42 return code 0 under the raised limit, while of the default fits more than ten per cent off, only 0.23 are brought within ten per cent. Of the 141 series in which the default call said 1 and the raised limit said 0, 71 (50 per cent) are still more than ten per cent off.</p>
<p>The other setting a careful reader might reach for is the tolerance. Tighten <code>reltol</code> from its default of about <img src="https://latex.codecogs.com/png.latex?1.5%20%5Ctimes%2010%5E%7B-8%7D"> to <img src="https://latex.codecogs.com/png.latex?10%5E%7B-12%7D">, leave <code>maxit</code> at 100, and the call reports code 0 in 0.000 of the series, with the median error in K at 37 per cent. The code 0 in the default call is the tolerance test firing, not a sign that the search got anywhere; why it fires is the subject of the next section.</p>
<div class="cell">
<div class="code-copy-outer-scaffold"><div class="sourceCode cell-code" id="cb8" style="background: #f1f3f5;"><pre class="sourceCode r code-with-copy"><code class="sourceCode r"><span id="cb8-1">mx_df <span class="ot" style="color: #003B4F;
background-color: null;
font-style: inherit;">&lt;-</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">rbind</span>(</span>
<span id="cb8-2">  <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">data.frame</span>(<span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">call =</span> <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"BFGS, default"</span>, <span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">err =</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">rel_err</span>(res_far, <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"def"</span>),</span>
<span id="cb8-3">             <span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">deficit =</span> res_far[<span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"nll"</span>, <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"def"</span>, ] <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">-</span> nll_ex, <span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">code =</span> res_far[<span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"code"</span>, <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"def"</span>, ]),</span>
<span id="cb8-4">  <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">data.frame</span>(<span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">call =</span> <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"BFGS, maxit = 5000"</span>, <span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">err =</span> re_mx,</span>
<span id="cb8-5">             <span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">deficit =</span> res_far[<span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"nll"</span>, <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"maxit"</span>, ] <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">-</span> nll_ex, <span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">code =</span> res_far[<span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"code"</span>, <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"maxit"</span>, ]))</span>
<span id="cb8-6">mx_df<span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">$</span>status <span class="ot" style="color: #003B4F;
background-color: null;
font-style: inherit;">&lt;-</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">ifelse</span>(mx_df<span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">$</span>code <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">==</span> <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">0</span>, <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"reports code 0"</span>, <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"reports code 1"</span>)</span>
<span id="cb8-7">mx_df<span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">$</span>call <span class="ot" style="color: #003B4F;
background-color: null;
font-style: inherit;">&lt;-</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">factor</span>(mx_df<span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">$</span>call, <span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">levels =</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">c</span>(<span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"BFGS, default"</span>, <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"BFGS, maxit = 5000"</span>))</span>
<span id="cb8-8"><span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">ggplot</span>(mx_df, <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">aes</span>(err, deficit, <span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">colour =</span> status)) <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">+</span></span>
<span id="cb8-9">  <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">geom_vline</span>(<span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">xintercept =</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">c</span>(<span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">-</span><span class="fl" style="color: #AD0000;
background-color: null;
font-style: inherit;">0.1</span>, <span class="fl" style="color: #AD0000;
background-color: null;
font-style: inherit;">0.1</span>), <span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">colour =</span> te_body, <span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">linetype =</span> <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"dashed"</span>, <span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">linewidth =</span> <span class="fl" style="color: #AD0000;
background-color: null;
font-style: inherit;">0.4</span>) <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">+</span></span>
<span id="cb8-10">  <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">geom_point</span>(<span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">size =</span> <span class="fl" style="color: #AD0000;
background-color: null;
font-style: inherit;">1.3</span>, <span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">alpha =</span> <span class="fl" style="color: #AD0000;
background-color: null;
font-style: inherit;">0.7</span>) <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">+</span></span>
<span id="cb8-11">  <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">facet_wrap</span>(<span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">~</span> call) <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">+</span></span>
<span id="cb8-12">  <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">scale_colour_manual</span>(<span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">values =</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">c</span>(te_forest, te_rust), <span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">name =</span> <span class="cn" style="color: #8f5902;
background-color: null;
font-style: inherit;">NULL</span>) <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">+</span></span>
<span id="cb8-13">  <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">scale_x_continuous</span>(<span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">labels =</span> pct) <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">+</span></span>
<span id="cb8-14">  <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">labs</span>(<span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">x =</span> <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"fitted K relative to the exact MLE"</span>, <span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">y =</span> <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"log-likelihood below the exact maximum"</span>,</span>
<span id="cb8-15">       <span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">title =</span> <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"A clean convergence code on a wrong fit"</span>,</span>
<span id="cb8-16">       <span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">subtitle =</span> <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"dashed lines: ten per cent either side of the exact K"</span>) <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">+</span></span>
<span id="cb8-17">  <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">theme_datasheet</span>() <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">+</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">theme</span>(<span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">legend.position =</span> <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"bottom"</span>,</span>
<span id="cb8-18">                            <span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">strip.text =</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">element_text</span>(<span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">colour =</span> te_ink, <span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">face =</span> <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"bold"</span>))</span></code></pre></div></div>
<div class="cell-output-display">
<div id="fig-maxit" class="quarto-float quarto-figure quarto-figure-center anchored" alt="Two scatter panels, default BFGS on the left and BFGS with maxit = 5000 on the right, one point per series. The horizontal axis is fitted K relative to the exact MLE, from about minus 55 to plus 15 per cent; the vertical axis is the log-likelihood below the exact maximum, from 0 to about 14. Dashed vertical lines mark minus and plus ten per cent. In the default panel the points form a cloud between minus 55 and minus 15 per cent at shortfalls of 1 to 14, mostly red for code 1 with many dark green code 0 points on the far left. In the maxit panel the cloud stretches right into a tail that reaches zero shortfall near zero error, but a dense dark green cluster of code 0 fits stays at minus 50 to minus 35 per cent with shortfalls of 2 to 14, far outside the dashed lines.">
<figure class="quarto-float quarto-float-fig figure">
<div aria-describedby="fig-maxit-caption-0ceaefa1-69ba-4598-a22c-09a6ac19f8ca">
<img src="https://tidyecology.com/posts/parameter-scale-and-what-optim-finds/index_files/figure-html/fig-maxit-1.png" class="img-fluid figure-img" alt="Two scatter panels, default BFGS on the left and BFGS with maxit = 5000 on the right, one point per series. The horizontal axis is fitted K relative to the exact MLE, from about minus 55 to plus 15 per cent; the vertical axis is the log-likelihood below the exact maximum, from 0 to about 14. Dashed vertical lines mark minus and plus ten per cent. In the default panel the points form a cloud between minus 55 and minus 15 per cent at shortfalls of 1 to 14, mostly red for code 1 with many dark green code 0 points on the far left. In the maxit panel the cloud stretches right into a tail that reaches zero shortfall near zero error, but a dense dark green cluster of code 0 fits stays at minus 50 to minus 35 per cent with shortfalls of 2 to 14, far outside the dashed lines." width="672">
</div>
<figcaption class="quarto-float-caption-bottom quarto-float-caption quarto-float-fig" id="fig-maxit-caption-0ceaefa1-69ba-4598-a22c-09a6ac19f8ca">
Figure&nbsp;2: Each series as a point: relative error in K against the log-likelihood shortfall from the exact maximum, for the default BFGS call and the same call with maxit = 5000, coloured by the convergence code the call returned.
</figcaption>
</figure>
</div>
</div>
</div>
</section>
<section id="not-the-gradient-step-the-restart" class="level2">
<h2 id="not-the-gradient-step-the-restart-h" class="anchored" data-anchor-id="not-the-gradient-step-the-restart">Not the gradient step: the restart</h2>
<p>The tempting explanation is the finite-difference gradient. <code>optim()</code> computes the gradient by central differences with a step of <code>ndeps = 1e-3</code> on each parameter, and a step of one thousandth is tiny for a parameter of size three thousand, so the gradient in K might be mostly rounding noise. That explanation is testable, and the test is already in the ten calls above: the <code>ndeps = 1e-6</code> call.</p>
<div class="cell">
<div class="code-copy-outer-scaffold"><div class="sourceCode cell-code" id="cb9" style="background: #f1f3f5;"><pre class="sourceCode r code-with-copy"><code class="sourceCode r"><span id="cb9-1">nd_gap <span class="ot" style="color: #003B4F;
background-color: null;
font-style: inherit;">&lt;-</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">median</span>(<span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">abs</span>(res_far[<span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"K"</span>, <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"nd6"</span>, ] <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">-</span> res_far[<span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"K"</span>, <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"def"</span>, ]) <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">/</span> K_ex)</span></code></pre></div></div>
</div>
<p>Shrinking the step a thousandfold changes nothing that matters. The median relative error in K is 35.9 to 39.9 per cent per block against 35.7 to 39.9 per cent for the default, and the median difference between the two fitted values of K, per series, is 0.0000 of the exact K. The gradient is fine. What goes wrong is in how the search uses it.</p>
<p>The series simulated earlier shows it. Here is the gradient at the start, computed the way <code>optim()</code> computes it, and the path the default call takes, recorded by passing a gradient function that does the same central differences and logs every point at which it is called. The recorded call returns the same answer as the plain one, to the last digit.</p>
<div class="cell">
<div class="code-copy-outer-scaffold"><div class="sourceCode cell-code" id="cb10" style="background: #f1f3f5;"><pre class="sourceCode r code-with-copy"><code class="sourceCode r"><span id="cb10-1">num_grad <span class="ot" style="color: #003B4F;
background-color: null;
font-style: inherit;">&lt;-</span> <span class="cf" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">function</span>(f, <span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">ps =</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">c</span>(<span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">1</span>, <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">1</span>, <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">1</span>), <span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">nd =</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">rep</span>(<span class="fl" style="color: #AD0000;
background-color: null;
font-style: inherit;">1e-3</span>, <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">3</span>)) <span class="cf" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">function</span>(th) {</span>
<span id="cb10-2">  h <span class="ot" style="color: #003B4F;
background-color: null;
font-style: inherit;">&lt;-</span> nd <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">*</span> ps</span>
<span id="cb10-3">  <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">vapply</span>(<span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">1</span><span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">:</span><span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">3</span>, <span class="cf" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">function</span>(i) { e <span class="ot" style="color: #003B4F;
background-color: null;
font-style: inherit;">&lt;-</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">numeric</span>(<span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">3</span>); e[i] <span class="ot" style="color: #003B4F;
background-color: null;
font-style: inherit;">&lt;-</span> h[i]</span>
<span id="cb10-4">    (<span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">f</span>(th <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">+</span> e) <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">-</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">f</span>(th <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">-</span> e)) <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">/</span> (<span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">2</span> <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">*</span> h[i]) }, <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">0</span>)</span>
<span id="cb10-5">}</span>
<span id="cb10-6">tracked <span class="ot" style="color: #003B4F;
background-color: null;
font-style: inherit;">&lt;-</span> <span class="cf" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">function</span>(f, <span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">ctrl =</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">list</span>(), <span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">ps =</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">c</span>(<span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">1</span>, <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">1</span>, <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">1</span>), <span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">nd =</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">rep</span>(<span class="fl" style="color: #AD0000;
background-color: null;
font-style: inherit;">1e-3</span>, <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">3</span>)) {</span>
<span id="cb10-7">  path <span class="ot" style="color: #003B4F;
background-color: null;
font-style: inherit;">&lt;-</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">list</span>(); g0 <span class="ot" style="color: #003B4F;
background-color: null;
font-style: inherit;">&lt;-</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">num_grad</span>(f, ps, nd)</span>
<span id="cb10-8">  gr <span class="ot" style="color: #003B4F;
background-color: null;
font-style: inherit;">&lt;-</span> <span class="cf" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">function</span>(th) { path[[<span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">length</span>(path) <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">+</span> <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">1</span>]] <span class="ot" style="color: #003B4F;
background-color: null;
font-style: inherit;">&lt;&lt;-</span> th; <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">g0</span>(th) }</span>
<span id="cb10-9">  o <span class="ot" style="color: #003B4F;
background-color: null;
font-style: inherit;">&lt;-</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">optim</span>(start_far, f, gr, <span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">method =</span> <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"BFGS"</span>, <span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">control =</span> ctrl)</span>
<span id="cb10-10">  <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">list</span>(<span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">o =</span> o, <span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">path =</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">do.call</span>(rbind, path))</span>
<span id="cb10-11">}</span>
<span id="cb10-12">g_start <span class="ot" style="color: #003B4F;
background-color: null;
font-style: inherit;">&lt;-</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">num_grad</span>(fm_one<span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">$</span>nll_K)(start_far)</span>
<span id="cb10-13">plain   <span class="ot" style="color: #003B4F;
background-color: null;
font-style: inherit;">&lt;-</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">optim</span>(start_far, fm_one<span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">$</span>nll_K, <span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">method =</span> <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"BFGS"</span>)</span>
<span id="cb10-14">tr_def  <span class="ot" style="color: #003B4F;
background-color: null;
font-style: inherit;">&lt;-</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">tracked</span>(fm_one<span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">$</span>nll_K)</span>
<span id="cb10-15">tr_mx   <span class="ot" style="color: #003B4F;
background-color: null;
font-style: inherit;">&lt;-</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">tracked</span>(fm_one<span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">$</span>nll_K, <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">list</span>(<span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">maxit =</span> <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">5000</span>))</span>
<span id="cb10-16">tr_nd   <span class="ot" style="color: #003B4F;
background-color: null;
font-style: inherit;">&lt;-</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">tracked</span>(fm_one<span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">$</span>nll_K, <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">list</span>(<span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">ndeps =</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">rep</span>(<span class="fl" style="color: #AD0000;
background-color: null;
font-style: inherit;">1e-6</span>, <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">3</span>)), <span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">nd =</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">rep</span>(<span class="fl" style="color: #AD0000;
background-color: null;
font-style: inherit;">1e-6</span>, <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">3</span>))</span>
<span id="cb10-17">tr_ps   <span class="ot" style="color: #003B4F;
background-color: null;
font-style: inherit;">&lt;-</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">tracked</span>(fm_one<span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">$</span>nll_K, <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">list</span>(<span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">parscale =</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">c</span>(<span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">1</span>, start_far[<span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">2</span>], <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">1</span>)),</span>
<span id="cb10-18">                   <span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">ps =</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">c</span>(<span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">1</span>, start_far[<span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">2</span>], <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">1</span>))</span>
<span id="cb10-19">track_gap <span class="ot" style="color: #003B4F;
background-color: null;
font-style: inherit;">&lt;-</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">max</span>(<span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">abs</span>(plain<span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">$</span>par <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">-</span> tr_def<span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">$</span>o<span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">$</span>par))</span>
<span id="cb10-20">dist_K <span class="ot" style="color: #003B4F;
background-color: null;
font-style: inherit;">&lt;-</span> fm_one<span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">$</span>K_ex <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">-</span> start_far[<span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">2</span>]</span>
<span id="cb10-21">K_moved <span class="ot" style="color: #003B4F;
background-color: null;
font-style: inherit;">&lt;-</span> tr_def<span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">$</span>o<span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">$</span>par[<span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">2</span>] <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">-</span> start_far[<span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">2</span>]</span>
<span id="cb10-22">g_end <span class="ot" style="color: #003B4F;
background-color: null;
font-style: inherit;">&lt;-</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">num_grad</span>(fm_one<span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">$</span>nll_K)(plain<span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">$</span>par)</span></code></pre></div></div>
</div>
<p>At the start the gradient is (49.24, -0.0130, -16.32) in (r, K, log sigma). The recorded path matches the plain call exactly.</p>
<p>The BFGS routine inside <code>optim()</code> is the function <code>vmmin</code> in R’s source, after Nash’s variable metric code. It starts from the identity matrix, so its first direction is the raw negative gradient, and it tries a step of length 1 along that direction, shortening it by a factor of 0.2 until the function falls by enough. On that first step K can move by at most 0.0130, while the exact K for this series is 2509 pairs away. That is the second tempting explanation, the step length, and it does not hold either: a short first step is not fatal on its own. After every step the BFGS update rescales the matrix from the change in the gradient, and that is how a quasi-Newton method learns that K needs far longer steps than r. Two more lines of <code>vmmin</code> decide whether it gets the chance. It resets the matrix to the identity whenever more than twice as many gradients as there are parameters have been evaluated since the last reset, which here means after every seventh. And it declares convergence when a step taken straight after a reset lowers the function by less than <code>reltol</code> times its value.</p>
<p>To see which of these decides the outcome, here is <code>vmmin</code> transcribed into R line by line, with one switch added: <code>restart = FALSE</code> deletes the periodic-restart line and changes nothing else.</p>
<div class="cell">
<div class="code-copy-outer-scaffold"><div class="sourceCode cell-code" id="cb11" style="background: #f1f3f5;"><pre class="sourceCode r code-with-copy"><code class="sourceCode r"><span id="cb11-1"><span class="co" style="color: #5E5E5E;
background-color: null;
font-style: inherit;"># BFGS as optim() runs it: a line-by-line R copy of vmmin in R's src/appl/optim.c</span></span>
<span id="cb11-2"><span class="co" style="color: #5E5E5E;
background-color: null;
font-style: inherit;"># restart = FALSE deletes the one periodic-restart line and changes nothing else</span></span>
<span id="cb11-3">vmmin_r <span class="ot" style="color: #003B4F;
background-color: null;
font-style: inherit;">&lt;-</span> <span class="cf" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">function</span>(b, fn, gr, <span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">maxit =</span> <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">100</span>, <span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">reltol =</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">sqrt</span>(.Machine<span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">$</span>double.eps),</span>
<span id="cb11-4">                    <span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">restart =</span> <span class="cn" style="color: #8f5902;
background-color: null;
font-style: inherit;">TRUE</span>, <span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">trace =</span> <span class="cn" style="color: #8f5902;
background-color: null;
font-style: inherit;">FALSE</span>) {</span>
<span id="cb11-5">  n <span class="ot" style="color: #003B4F;
background-color: null;
font-style: inherit;">&lt;-</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">length</span>(b); f <span class="ot" style="color: #003B4F;
background-color: null;
font-style: inherit;">&lt;-</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">fn</span>(b); Fmin <span class="ot" style="color: #003B4F;
background-color: null;
font-style: inherit;">&lt;-</span> f; g <span class="ot" style="color: #003B4F;
background-color: null;
font-style: inherit;">&lt;-</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">gr</span>(b)</span>
<span id="cb11-6">  gradcount <span class="ot" style="color: #003B4F;
background-color: null;
font-style: inherit;">&lt;-</span> <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">1</span>; iter <span class="ot" style="color: #003B4F;
background-color: null;
font-style: inherit;">&lt;-</span> <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">1</span>; ilast <span class="ot" style="color: #003B4F;
background-color: null;
font-style: inherit;">&lt;-</span> <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">1</span></span>
<span id="cb11-7">  B <span class="ot" style="color: #003B4F;
background-color: null;
font-style: inherit;">&lt;-</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">diag</span>(n); tt <span class="ot" style="color: #003B4F;
background-color: null;
font-style: inherit;">&lt;-</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">numeric</span>(n); steps <span class="ot" style="color: #003B4F;
background-color: null;
font-style: inherit;">&lt;-</span> <span class="cn" style="color: #8f5902;
background-color: null;
font-style: inherit;">NULL</span></span>
<span id="cb11-8">  <span class="cf" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">repeat</span> {</span>
<span id="cb11-9">    <span class="cf" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">if</span> (ilast <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">==</span> gradcount) B <span class="ot" style="color: #003B4F;
background-color: null;
font-style: inherit;">&lt;-</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">diag</span>(n)</span>
<span id="cb11-10">    X <span class="ot" style="color: #003B4F;
background-color: null;
font-style: inherit;">&lt;-</span> b; cc <span class="ot" style="color: #003B4F;
background-color: null;
font-style: inherit;">&lt;-</span> g; gradproj <span class="ot" style="color: #003B4F;
background-color: null;
font-style: inherit;">&lt;-</span> <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">0</span></span>
<span id="cb11-11">    <span class="cf" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">for</span> (i <span class="cf" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">in</span> <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">1</span><span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">:</span>n) {</span>
<span id="cb11-12">      s <span class="ot" style="color: #003B4F;
background-color: null;
font-style: inherit;">&lt;-</span> <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">0</span></span>
<span id="cb11-13">      <span class="cf" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">for</span> (j <span class="cf" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">in</span> <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">1</span><span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">:</span>i) s <span class="ot" style="color: #003B4F;
background-color: null;
font-style: inherit;">&lt;-</span> s <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">-</span> B[i, j] <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">*</span> g[j]</span>
<span id="cb11-14">      <span class="cf" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">if</span> (i <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">&lt;</span> n) <span class="cf" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">for</span> (j <span class="cf" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">in</span> (i <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">+</span> <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">1</span>)<span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">:</span>n) s <span class="ot" style="color: #003B4F;
background-color: null;
font-style: inherit;">&lt;-</span> s <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">-</span> B[j, i] <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">*</span> g[j]</span>
<span id="cb11-15">      tt[i] <span class="ot" style="color: #003B4F;
background-color: null;
font-style: inherit;">&lt;-</span> s; gradproj <span class="ot" style="color: #003B4F;
background-color: null;
font-style: inherit;">&lt;-</span> gradproj <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">+</span> s <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">*</span> g[i]</span>
<span id="cb11-16">    }</span>
<span id="cb11-17">    <span class="cf" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">if</span> (gradproj <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">&lt;</span> <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">0</span>) {</span>
<span id="cb11-18">      steplength <span class="ot" style="color: #003B4F;
background-color: null;
font-style: inherit;">&lt;-</span> <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">1</span>; accpoint <span class="ot" style="color: #003B4F;
background-color: null;
font-style: inherit;">&lt;-</span> <span class="cn" style="color: #8f5902;
background-color: null;
font-style: inherit;">FALSE</span></span>
<span id="cb11-19">      <span class="cf" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">repeat</span> {</span>
<span id="cb11-20">        b <span class="ot" style="color: #003B4F;
background-color: null;
font-style: inherit;">&lt;-</span> X <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">+</span> steplength <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">*</span> tt; count <span class="ot" style="color: #003B4F;
background-color: null;
font-style: inherit;">&lt;-</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">sum</span>(<span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">10</span> <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">+</span> X <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">==</span> <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">10</span> <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">+</span> b)</span>
<span id="cb11-21">        <span class="cf" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">if</span> (count <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">&lt;</span> n) {</span>
<span id="cb11-22">          f <span class="ot" style="color: #003B4F;
background-color: null;
font-style: inherit;">&lt;-</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">fn</span>(b)</span>
<span id="cb11-23">          accpoint <span class="ot" style="color: #003B4F;
background-color: null;
font-style: inherit;">&lt;-</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">is.finite</span>(f) <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">&amp;&amp;</span> f <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">&lt;=</span> Fmin <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">+</span> gradproj <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">*</span> steplength <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">*</span> <span class="fl" style="color: #AD0000;
background-color: null;
font-style: inherit;">1e-4</span></span>
<span id="cb11-24">          <span class="cf" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">if</span> (<span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">!</span>accpoint) steplength <span class="ot" style="color: #003B4F;
background-color: null;
font-style: inherit;">&lt;-</span> steplength <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">*</span> <span class="fl" style="color: #AD0000;
background-color: null;
font-style: inherit;">0.2</span></span>
<span id="cb11-25">        }</span>
<span id="cb11-26">        <span class="cf" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">if</span> (count <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">==</span> n <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">||</span> accpoint) <span class="cf" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">break</span></span>
<span id="cb11-27">      }</span>
<span id="cb11-28">      enough <span class="ot" style="color: #003B4F;
background-color: null;
font-style: inherit;">&lt;-</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">abs</span>(f <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">-</span> Fmin) <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">&gt;</span> reltol <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">*</span> (<span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">abs</span>(Fmin) <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">+</span> reltol)</span>
<span id="cb11-29">      <span class="cf" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">if</span> (trace) steps <span class="ot" style="color: #003B4F;
background-color: null;
font-style: inherit;">&lt;-</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">rbind</span>(steps, <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">c</span>(<span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">grad =</span> gradcount, <span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">reset =</span> ilast <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">==</span> gradcount,</span>
<span id="cb11-30">        <span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">p1 =</span> b[<span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">1</span>], <span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">p2 =</span> b[<span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">2</span>], <span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">step =</span> steplength, <span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">drop =</span> Fmin <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">-</span> f,</span>
<span id="cb11-31">        <span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">tol =</span> reltol <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">*</span> (<span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">abs</span>(Fmin) <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">+</span> reltol), <span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">B22 =</span> B[<span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">2</span>, <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">2</span>]))</span>
<span id="cb11-32">      <span class="cf" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">if</span> (<span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">!</span>enough) { count <span class="ot" style="color: #003B4F;
background-color: null;
font-style: inherit;">&lt;-</span> n; Fmin <span class="ot" style="color: #003B4F;
background-color: null;
font-style: inherit;">&lt;-</span> f }</span>
<span id="cb11-33">      <span class="cf" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">if</span> (count <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">&lt;</span> n) {</span>
<span id="cb11-34">        Fmin <span class="ot" style="color: #003B4F;
background-color: null;
font-style: inherit;">&lt;-</span> f; g <span class="ot" style="color: #003B4F;
background-color: null;
font-style: inherit;">&lt;-</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">gr</span>(b); gradcount <span class="ot" style="color: #003B4F;
background-color: null;
font-style: inherit;">&lt;-</span> gradcount <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">+</span> <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">1</span>; iter <span class="ot" style="color: #003B4F;
background-color: null;
font-style: inherit;">&lt;-</span> iter <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">+</span> <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">1</span></span>
<span id="cb11-35">        D1 <span class="ot" style="color: #003B4F;
background-color: null;
font-style: inherit;">&lt;-</span> <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">0</span></span>
<span id="cb11-36">        <span class="cf" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">for</span> (i <span class="cf" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">in</span> <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">1</span><span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">:</span>n) { tt[i] <span class="ot" style="color: #003B4F;
background-color: null;
font-style: inherit;">&lt;-</span> steplength <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">*</span> tt[i]; cc[i] <span class="ot" style="color: #003B4F;
background-color: null;
font-style: inherit;">&lt;-</span> g[i] <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">-</span> cc[i]</span>
<span id="cb11-37">                         D1 <span class="ot" style="color: #003B4F;
background-color: null;
font-style: inherit;">&lt;-</span> D1 <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">+</span> tt[i] <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">*</span> cc[i] }</span>
<span id="cb11-38">        <span class="cf" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">if</span> (D1 <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">&gt;</span> <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">0</span>) {</span>
<span id="cb11-39">          D2 <span class="ot" style="color: #003B4F;
background-color: null;
font-style: inherit;">&lt;-</span> <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">0</span>; Xv <span class="ot" style="color: #003B4F;
background-color: null;
font-style: inherit;">&lt;-</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">numeric</span>(n)</span>
<span id="cb11-40">          <span class="cf" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">for</span> (i <span class="cf" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">in</span> <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">1</span><span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">:</span>n) {</span>
<span id="cb11-41">            s <span class="ot" style="color: #003B4F;
background-color: null;
font-style: inherit;">&lt;-</span> <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">0</span></span>
<span id="cb11-42">            <span class="cf" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">for</span> (j <span class="cf" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">in</span> <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">1</span><span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">:</span>i) s <span class="ot" style="color: #003B4F;
background-color: null;
font-style: inherit;">&lt;-</span> s <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">+</span> B[i, j] <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">*</span> cc[j]</span>
<span id="cb11-43">            <span class="cf" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">if</span> (i <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">&lt;</span> n) <span class="cf" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">for</span> (j <span class="cf" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">in</span> (i <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">+</span> <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">1</span>)<span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">:</span>n) s <span class="ot" style="color: #003B4F;
background-color: null;
font-style: inherit;">&lt;-</span> s <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">+</span> B[j, i] <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">*</span> cc[j]</span>
<span id="cb11-44">            Xv[i] <span class="ot" style="color: #003B4F;
background-color: null;
font-style: inherit;">&lt;-</span> s; D2 <span class="ot" style="color: #003B4F;
background-color: null;
font-style: inherit;">&lt;-</span> D2 <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">+</span> s <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">*</span> cc[i]</span>
<span id="cb11-45">          }</span>
<span id="cb11-46">          D2 <span class="ot" style="color: #003B4F;
background-color: null;
font-style: inherit;">&lt;-</span> <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">1</span> <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">+</span> D2 <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">/</span> D1</span>
<span id="cb11-47">          <span class="cf" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">for</span> (i <span class="cf" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">in</span> <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">1</span><span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">:</span>n) <span class="cf" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">for</span> (j <span class="cf" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">in</span> <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">1</span><span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">:</span>i)</span>
<span id="cb11-48">            B[i, j] <span class="ot" style="color: #003B4F;
background-color: null;
font-style: inherit;">&lt;-</span> B[i, j] <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">+</span> (D2 <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">*</span> tt[i] <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">*</span> tt[j] <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">-</span> Xv[i] <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">*</span> tt[j] <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">-</span> tt[i] <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">*</span> Xv[j]) <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">/</span> D1</span>
<span id="cb11-49">        } <span class="cf" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">else</span> ilast <span class="ot" style="color: #003B4F;
background-color: null;
font-style: inherit;">&lt;-</span> gradcount</span>
<span id="cb11-50">      } <span class="cf" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">else</span> <span class="cf" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">if</span> (ilast <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">&lt;</span> gradcount) { count <span class="ot" style="color: #003B4F;
background-color: null;
font-style: inherit;">&lt;-</span> <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">0</span>; ilast <span class="ot" style="color: #003B4F;
background-color: null;
font-style: inherit;">&lt;-</span> gradcount }</span>
<span id="cb11-51">    } <span class="cf" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">else</span> { count <span class="ot" style="color: #003B4F;
background-color: null;
font-style: inherit;">&lt;-</span> <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">0</span>; <span class="cf" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">if</span> (ilast <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">==</span> gradcount) count <span class="ot" style="color: #003B4F;
background-color: null;
font-style: inherit;">&lt;-</span> n <span class="cf" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">else</span> ilast <span class="ot" style="color: #003B4F;
background-color: null;
font-style: inherit;">&lt;-</span> gradcount }</span>
<span id="cb11-52">    <span class="cf" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">if</span> (iter <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">&gt;=</span> maxit) <span class="cf" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">break</span></span>
<span id="cb11-53">    <span class="cf" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">if</span> (restart <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">&amp;&amp;</span> gradcount <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">-</span> ilast <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">&gt;</span> <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">2</span> <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">*</span> n) ilast <span class="ot" style="color: #003B4F;
background-color: null;
font-style: inherit;">&lt;-</span> gradcount   <span class="co" style="color: #5E5E5E;
background-color: null;
font-style: inherit;"># the periodic restart</span></span>
<span id="cb11-54">    <span class="cf" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">if</span> (count <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">==</span> n <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">&amp;&amp;</span> ilast <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">==</span> gradcount) <span class="cf" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">break</span></span>
<span id="cb11-55">  }</span>
<span id="cb11-56">  <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">list</span>(<span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">par =</span> b, <span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">value =</span> Fmin, <span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">convergence =</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">as.integer</span>(iter <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">&gt;=</span> maxit),</span>
<span id="cb11-57">       <span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">grads =</span> gradcount, <span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">steps =</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">as.data.frame</span>(steps))</span>
<span id="cb11-58">}</span>
<span id="cb11-59">port_all <span class="ot" style="color: #003B4F;
background-color: null;
font-style: inherit;">&lt;-</span> <span class="cf" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">function</span>(restart) <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">vapply</span>(<span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">seq_along</span>(fms), <span class="cf" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">function</span>(i) {</span>
<span id="cb11-60">  v <span class="ot" style="color: #003B4F;
background-color: null;
font-style: inherit;">&lt;-</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">vmmin_r</span>(start_far, fms[[i]]<span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">$</span>nll_K, <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">num_grad</span>(fms[[i]]<span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">$</span>nll_K), <span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">restart =</span> restart)</span>
<span id="cb11-61">  <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">c</span>(<span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">K =</span> v<span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">$</span>par[<span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">2</span>], <span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">nll =</span> v<span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">$</span>value, <span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">code =</span> v<span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">$</span>convergence, <span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">grads =</span> v<span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">$</span>grads)</span>
<span id="cb11-62">}, <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">numeric</span>(<span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">4</span>))</span>
<span id="cb11-63">port_rs <span class="ot" style="color: #003B4F;
background-color: null;
font-style: inherit;">&lt;-</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">port_all</span>(<span class="cn" style="color: #8f5902;
background-color: null;
font-style: inherit;">TRUE</span>)</span>
<span id="cb11-64">port_nr <span class="ot" style="color: #003B4F;
background-color: null;
font-style: inherit;">&lt;-</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">port_all</span>(<span class="cn" style="color: #8f5902;
background-color: null;
font-style: inherit;">FALSE</span>)</span>
<span id="cb11-65">same_K    <span class="ot" style="color: #003B4F;
background-color: null;
font-style: inherit;">&lt;-</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">mean</span>(port_rs[<span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"K"</span>, ] <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">==</span> res_far[<span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"K"</span>, <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"def"</span>, ])</span>
<span id="cb11-66">same_code <span class="ot" style="color: #003B4F;
background-color: null;
font-style: inherit;">&lt;-</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">mean</span>(port_rs[<span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"code"</span>, ] <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">==</span> res_far[<span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"code"</span>, <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"def"</span>, ])</span>
<span id="cb11-67">err_nr  <span class="ot" style="color: #003B4F;
background-color: null;
font-style: inherit;">&lt;-</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">abs</span>(port_nr[<span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"K"</span>, ] <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">-</span> K_ex) <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">/</span> K_ex</span>
<span id="cb11-68">code0_nr <span class="ot" style="color: #003B4F;
background-color: null;
font-style: inherit;">&lt;-</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">mean</span>(port_nr[<span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"code"</span>, ] <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">==</span> <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">0</span>)</span>
<span id="cb11-69">def_nr  <span class="ot" style="color: #003B4F;
background-color: null;
font-style: inherit;">&lt;-</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">max</span>(port_nr[<span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"nll"</span>, ] <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">-</span> nll_ex)</span>
<span id="cb11-70"><span class="co" style="color: #5E5E5E;
background-color: null;
font-style: inherit;"># series 77, with and without the restart</span></span>
<span id="cb11-71">g77 <span class="ot" style="color: #003B4F;
background-color: null;
font-style: inherit;">&lt;-</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">num_grad</span>(fm_one<span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">$</span>nll_K)</span>
<span id="cb11-72">v_rs <span class="ot" style="color: #003B4F;
background-color: null;
font-style: inherit;">&lt;-</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">vmmin_r</span>(start_far, fm_one<span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">$</span>nll_K, g77, <span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">trace =</span> <span class="cn" style="color: #8f5902;
background-color: null;
font-style: inherit;">TRUE</span>)</span>
<span id="cb11-73">v_nr <span class="ot" style="color: #003B4F;
background-color: null;
font-style: inherit;">&lt;-</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">vmmin_r</span>(start_far, fm_one<span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">$</span>nll_K, g77, <span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">restart =</span> <span class="cn" style="color: #8f5902;
background-color: null;
font-style: inherit;">FALSE</span>, <span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">trace =</span> <span class="cn" style="color: #8f5902;
background-color: null;
font-style: inherit;">TRUE</span>)</span>
<span id="cb11-74">last_rs <span class="ot" style="color: #003B4F;
background-color: null;
font-style: inherit;">&lt;-</span> v_rs<span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">$</span>steps[<span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">nrow</span>(v_rs<span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">$</span>steps), ]</span>
<span id="cb11-75">BKK_lost <span class="ot" style="color: #003B4F;
background-color: null;
font-style: inherit;">&lt;-</span> v_nr<span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">$</span>steps<span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">$</span>B22[v_nr<span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">$</span>steps<span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">$</span>grad <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">==</span> last_rs<span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">$</span>grad][<span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">1</span>]</span>
<span id="cb11-76">inv_H_KK <span class="ot" style="color: #003B4F;
background-color: null;
font-style: inherit;">&lt;-</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">solve</span>(<span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">optimHess</span>(th_K, fm_one<span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">$</span>nll_K))[<span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">2</span>, <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">2</span>]</span>
<span id="cb11-77"><span class="co" style="color: #5E5E5E;
background-color: null;
font-style: inherit;"># a series that ends with code 1: the first of the first block</span></span>
<span id="cb11-78">v_c1 <span class="ot" style="color: #003B4F;
background-color: null;
font-style: inherit;">&lt;-</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">vmmin_r</span>(start_far, fms[[<span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">1</span>]]<span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">$</span>nll_K, <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">num_grad</span>(fms[[<span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">1</span>]]<span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">$</span>nll_K), <span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">trace =</span> <span class="cn" style="color: #8f5902;
background-color: null;
font-style: inherit;">TRUE</span>)</span>
<span id="cb11-79">cyc  <span class="ot" style="color: #003B4F;
background-color: null;
font-style: inherit;">&lt;-</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">cumsum</span>(v_c1<span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">$</span>steps<span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">$</span>reset)</span>
<span id="cb11-80">cyc_B <span class="ot" style="color: #003B4F;
background-color: null;
font-style: inherit;">&lt;-</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">tapply</span>(v_c1<span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">$</span>steps<span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">$</span>B22, cyc, max)</span>
<span id="cb11-81"><span class="co" style="color: #5E5E5E;
background-color: null;
font-style: inherit;"># the same search in (r, b)</span></span>
<span id="cb11-82">start_b <span class="ot" style="color: #003B4F;
background-color: null;
font-style: inherit;">&lt;-</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">c</span>(start_far[<span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">1</span>], start_far[<span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">1</span>] <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">/</span> start_far[<span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">2</span>], start_far[<span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">3</span>])</span>
<span id="cb11-83">v_b <span class="ot" style="color: #003B4F;
background-color: null;
font-style: inherit;">&lt;-</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">vmmin_r</span>(start_b, fm_one<span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">$</span>nll_b, <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">num_grad</span>(fm_one<span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">$</span>nll_b), <span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">trace =</span> <span class="cn" style="color: #8f5902;
background-color: null;
font-style: inherit;">TRUE</span>)</span>
<span id="cb11-84">stuck <span class="ot" style="color: #003B4F;
background-color: null;
font-style: inherit;">&lt;-</span> <span class="cf" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">function</span>(res, f, <span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">K0 =</span> start_far[<span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">2</span>]) <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">abs</span>(res[<span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"K"</span>, f, ] <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">/</span> K0 <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">-</span> <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">1</span>) <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">&lt;</span> <span class="fl" style="color: #AD0000;
background-color: null;
font-style: inherit;">1e-3</span></span>
<span id="cb11-85">code0_d <span class="ot" style="color: #003B4F;
background-color: null;
font-style: inherit;">&lt;-</span> res_far[<span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"code"</span>, <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"def"</span>, ] <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">==</span> <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">0</span>; stuck_d <span class="ot" style="color: #003B4F;
background-color: null;
font-style: inherit;">&lt;-</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">stuck</span>(res_far, <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"def"</span>)</span>
<span id="cb11-86">g_peak  <span class="ot" style="color: #003B4F;
background-color: null;
font-style: inherit;">&lt;-</span> v_nr<span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">$</span>steps<span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">$</span>grad[<span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">which.max</span>(v_nr<span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">$</span>steps<span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">$</span>B22)]</span>
<span id="cb11-87">growth  <span class="ot" style="color: #003B4F;
background-color: null;
font-style: inherit;">&lt;-</span> (<span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">max</span>(v_nr<span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">$</span>steps<span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">$</span>B22) <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">/</span> BKK_lost)<span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">^</span>(<span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">1</span> <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">/</span> (g_peak <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">-</span> last_rs<span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">$</span>grad))</span>
<span id="cb11-88">nback_b <span class="ot" style="color: #003B4F;
background-color: null;
font-style: inherit;">&lt;-</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">round</span>(<span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">log</span>(v_b<span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">$</span>steps<span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">$</span>step[<span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">1</span>]) <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">/</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">log</span>(<span class="fl" style="color: #AD0000;
background-color: null;
font-style: inherit;">0.2</span>))</span></code></pre></div></div>
</div>
<p>Run with the restart on all 500 series, the copy returns the same convergence code as <code>optim()</code> in a share of 0.998 of them and the same K to the last digit in a share of 0.036.</p>
<p>On the series from before, the first five updates go almost entirely to r and sigma, which are the right size for a gradient of this magnitude. Only then does the K element of the matrix start to grow, and by the eighth gradient it has reached 3.86. At that point the restart returns it to 1. The steepest-descent step that follows has to be shortened to 0.008, lowers the negative log-likelihood by 0.000000052 against a threshold of 0.00000015, and the call stops with code 0 and K at 3000.006. With the restart deleted, the same search on the same series keeps growing the K element, about 2.8-fold per update, to a peak of 3,200,000 (the K element of the inverse Hessian at the maximum is 280,000), and reaches the exact K of 5509.4 in 33 gradient evaluations.</p>
<p>Over all 500 series, the copy without the restart is exact every time: the largest relative error in K is 0.000015, the largest shortfall in log-likelihood is 0.0000000056, it reports code 0 in 1.000 of series, and it needs a median of 30 gradient evaluations (at most 62), well inside the default limit. The line search, the tolerance, the gradient and the start are all unchanged. The one line that throws the learned scale away is the whole failure.</p>
<p>It produces two patterns. Of the 165 default fits that report code 0, 162 ended with K within a tenth of a per cent of the starting 3000: those are the pattern above, where the first restart comes before K has moved. The other 335 report code 1, and 319 of them did move K a little. In those the matrix learns part of the scale within each cycle of seven gradients and loses it at the next restart. On the first series of the first block, the largest K element reached in each cycle ranges from 7.5 to 4974, and after 14 full cycles the call hits its limit of 100 iterations with K at 3024 against an exact 4962. Raising <code>maxit</code> buys more of these cycles. Some fits creep a long way in them; others stop when a step after one of the restarts falls under the tolerance, and that is the only way this code reports 0.</p>
<div class="cell">
<div class="code-copy-outer-scaffold"><div class="sourceCode cell-code" id="cb12" style="background: #f1f3f5;"><pre class="sourceCode r code-with-copy"><code class="sourceCode r"><span id="cb12-1">H_K <span class="ot" style="color: #003B4F;
background-color: null;
font-style: inherit;">&lt;-</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">optimHess</span>(th_K, fm_one<span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">$</span>nll_K)</span>
<span id="cb12-2">H_b <span class="ot" style="color: #003B4F;
background-color: null;
font-style: inherit;">&lt;-</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">optimHess</span>(th_b, fm_one<span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">$</span>nll_b)</span>
<span id="cb12-3">P   <span class="ot" style="color: #003B4F;
background-color: null;
font-style: inherit;">&lt;-</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">diag</span>(<span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">c</span>(<span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">1</span>, start_far[<span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">2</span>], <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">1</span>))</span>
<span id="cb12-4">kap_K  <span class="ot" style="color: #003B4F;
background-color: null;
font-style: inherit;">&lt;-</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">kappa</span>(H_K, <span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">exact =</span> <span class="cn" style="color: #8f5902;
background-color: null;
font-style: inherit;">TRUE</span>)</span>
<span id="cb12-5">kap_b  <span class="ot" style="color: #003B4F;
background-color: null;
font-style: inherit;">&lt;-</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">kappa</span>(H_b, <span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">exact =</span> <span class="cn" style="color: #8f5902;
background-color: null;
font-style: inherit;">TRUE</span>)</span>
<span id="cb12-6">kap_ps <span class="ot" style="color: #003B4F;
background-color: null;
font-style: inherit;">&lt;-</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">kappa</span>(P <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">%*%</span> H_K <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">%*%</span> P, <span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">exact =</span> <span class="cn" style="color: #8f5902;
background-color: null;
font-style: inherit;">TRUE</span>)</span>
<span id="cb12-7">ps_K <span class="ot" style="color: #003B4F;
background-color: null;
font-style: inherit;">&lt;-</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">c</span>(<span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">1</span>, start_far[<span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">2</span>], <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">1</span>)</span>
<span id="cb12-8">g_ps <span class="ot" style="color: #003B4F;
background-color: null;
font-style: inherit;">&lt;-</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">num_grad</span>(fm_one<span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">$</span>nll_K, <span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">ps =</span> ps_K)(start_far) <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">*</span> ps_K   <span class="co" style="color: #5E5E5E;
background-color: null;
font-style: inherit;"># gradient in (r, K / 3000, log sigma)</span></span></code></pre></div></div>
</div>
<p><code>parscale</code> does not change the function or the line search. It changes the coordinates the search works in, and with them the gradient the search sees: <code>optim()</code> divides each parameter by its <code>parscale</code> value, so K is searched as K / 3000, a number near one. At the start the gradient in K / 3000 is -39.1, against 49.24 in r, so the identity matrix that every restart returns to is already about the right shape. The condition number of the Hessian at the maximum, which measures how unequal the curvature is in different directions, is 17,800,000 in (r, K) and 2.04 after that rescaling. The rescaled search reaches the exact K for this series in 14 gradient evaluations.</p>
<p>It would be easy to stop there and blame conditioning, but the (r, b) spelling has a condition number of 183,000,000, worse than (r, K), and it fits perfectly every time. Conditioning measured at the answer is not the lever, and the copy of <code>vmmin</code> shows what is. In (r, b) the first step starves r the way the first step in (r, K) starves K: the gradient in b is so large that the step is shortened 14 times, to less than one in a billion, and r moves by 0.000000013. But the single update that follows shrinks the b element of the matrix from 1 to 0.00000003, and after the seventh step, still inside the first cycle, r is at 0.5609 against an exact 0.5605. The whole (r, b) search takes 13 gradient evaluations. In (r, K) the matrix has to grow by orders of magnitude in K, a few-fold per update, and the restart comes first.</p>
<div class="cell">
<div class="code-copy-outer-scaffold"><div class="sourceCode cell-code" id="cb13" style="background: #f1f3f5;"><pre class="sourceCode r code-with-copy"><code class="sourceCode r"><span id="cb13-1">prof_nll <span class="ot" style="color: #003B4F;
background-color: null;
font-style: inherit;">&lt;-</span> <span class="cf" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">function</span>(r, K) {</span>
<span id="cb13-2">  res <span class="ot" style="color: #003B4F;
background-color: null;
font-style: inherit;">&lt;-</span> fm_one<span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">$</span>y <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">-</span> r <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">*</span> (<span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">1</span> <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">-</span> fm_one<span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">$</span>x <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">/</span> K)</span>
<span id="cb13-3">  n <span class="ot" style="color: #003B4F;
background-color: null;
font-style: inherit;">&lt;-</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">length</span>(res); <span class="fl" style="color: #AD0000;
background-color: null;
font-style: inherit;">0.5</span> <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">*</span> n <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">*</span> (<span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">log</span>(<span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">2</span> <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">*</span> pi <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">*</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">mean</span>(res<span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">^</span><span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">2</span>)) <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">+</span> <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">1</span>)</span>
<span id="cb13-4">}</span>
<span id="cb13-5">r_seq <span class="ot" style="color: #003B4F;
background-color: null;
font-style: inherit;">&lt;-</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">seq</span>(<span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">0</span>, <span class="fl" style="color: #AD0000;
background-color: null;
font-style: inherit;">0.9</span>, <span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">length.out =</span> <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">121</span>); K_seq <span class="ot" style="color: #003B4F;
background-color: null;
font-style: inherit;">&lt;-</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">seq</span>(<span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">2500</span>, <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">7500</span>, <span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">length.out =</span> <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">121</span>)</span>
<span id="cb13-6">surf <span class="ot" style="color: #003B4F;
background-color: null;
font-style: inherit;">&lt;-</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">expand.grid</span>(<span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">r =</span> r_seq, <span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">K =</span> K_seq)</span>
<span id="cb13-7">surf<span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">$</span>deficit <span class="ot" style="color: #003B4F;
background-color: null;
font-style: inherit;">&lt;-</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">mapply</span>(prof_nll, surf<span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">$</span>r, surf<span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">$</span>K) <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">-</span> fm_one<span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">$</span>nll_ex</span>
<span id="cb13-8">path_nr <span class="ot" style="color: #003B4F;
background-color: null;
font-style: inherit;">&lt;-</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">list</span>()</span>
<span id="cb13-9">g_rec <span class="ot" style="color: #003B4F;
background-color: null;
font-style: inherit;">&lt;-</span> <span class="cf" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">function</span>(th) { path_nr[[<span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">length</span>(path_nr) <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">+</span> <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">1</span>]] <span class="ot" style="color: #003B4F;
background-color: null;
font-style: inherit;">&lt;&lt;-</span> th; <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">g77</span>(th) }</span>
<span id="cb13-10"><span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">invisible</span>(<span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">vmmin_r</span>(start_far, fm_one<span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">$</span>nll_K, g_rec, <span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">restart =</span> <span class="cn" style="color: #8f5902;
background-color: null;
font-style: inherit;">FALSE</span>))</span>
<span id="cb13-11">path_nr <span class="ot" style="color: #003B4F;
background-color: null;
font-style: inherit;">&lt;-</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">do.call</span>(rbind, path_nr)</span>
<span id="cb13-12">path_df <span class="ot" style="color: #003B4F;
background-color: null;
font-style: inherit;">&lt;-</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">rbind</span>(<span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">data.frame</span>(<span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">call =</span> <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"BFGS, default"</span>, <span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">r =</span> tr_def<span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">$</span>path[, <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">1</span>], <span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">K =</span> tr_def<span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">$</span>path[, <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">2</span>]),</span>
<span id="cb13-13">                 <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">data.frame</span>(<span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">call =</span> <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"BFGS, parscale"</span>, <span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">r =</span> tr_ps<span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">$</span>path[, <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">1</span>], <span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">K =</span> tr_ps<span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">$</span>path[, <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">2</span>]),</span>
<span id="cb13-14">                 <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">data.frame</span>(<span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">call =</span> <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"copy, no restart"</span>, <span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">r =</span> path_nr[, <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">1</span>], <span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">K =</span> path_nr[, <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">2</span>]))</span>
<span id="cb13-15">path_df<span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">$</span>call <span class="ot" style="color: #003B4F;
background-color: null;
font-style: inherit;">&lt;-</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">factor</span>(path_df<span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">$</span>call, <span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">levels =</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">c</span>(<span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"BFGS, default"</span>, <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"BFGS, parscale"</span>, <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"copy, no restart"</span>))</span>
<span id="cb13-16">p_surf <span class="ot" style="color: #003B4F;
background-color: null;
font-style: inherit;">&lt;-</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">ggplot</span>(surf, <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">aes</span>(r, K)) <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">+</span></span>
<span id="cb13-17">  <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">geom_contour</span>(<span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">aes</span>(<span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">z =</span> deficit), <span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">breaks =</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">c</span>(<span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">1</span>, <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">2</span>, <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">5</span>, <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">10</span>, <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">20</span>, <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">40</span>),</span>
<span id="cb13-18">               <span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">colour =</span> te_body, <span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">linewidth =</span> <span class="fl" style="color: #AD0000;
background-color: null;
font-style: inherit;">0.35</span>) <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">+</span></span>
<span id="cb13-19">  <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">geom_path</span>(<span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">data =</span> path_df, <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">aes</span>(<span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">colour =</span> call), <span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">linewidth =</span> <span class="fl" style="color: #AD0000;
background-color: null;
font-style: inherit;">0.8</span>) <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">+</span></span>
<span id="cb13-20">  <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">geom_point</span>(<span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">data =</span> path_df, <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">aes</span>(<span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">colour =</span> call), <span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">size =</span> <span class="fl" style="color: #AD0000;
background-color: null;
font-style: inherit;">1.6</span>) <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">+</span></span>
<span id="cb13-21">  <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">geom_path</span>(<span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">data =</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">subset</span>(path_df, call <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">==</span> <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"BFGS, default"</span>), <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">aes</span>(<span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">colour =</span> call), <span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">linewidth =</span> <span class="fl" style="color: #AD0000;
background-color: null;
font-style: inherit;">1.2</span>) <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">+</span></span>
<span id="cb13-22">  <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">geom_point</span>(<span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">data =</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">subset</span>(path_df, call <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">==</span> <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"BFGS, default"</span>), <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">aes</span>(<span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">colour =</span> call), <span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">size =</span> <span class="fl" style="color: #AD0000;
background-color: null;
font-style: inherit;">2.2</span>) <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">+</span></span>
<span id="cb13-23">  <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">annotate</span>(<span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"point"</span>, <span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">x =</span> fm_one<span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">$</span>r_ex, <span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">y =</span> fm_one<span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">$</span>K_ex, <span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">shape =</span> <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">4</span>, <span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">size =</span> <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">4</span>,</span>
<span id="cb13-24">           <span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">stroke =</span> <span class="fl" style="color: #AD0000;
background-color: null;
font-style: inherit;">1.3</span>, <span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">colour =</span> te_ink) <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">+</span></span>
<span id="cb13-25">  <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">annotate</span>(<span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"point"</span>, <span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">x =</span> start_far[<span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">1</span>], <span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">y =</span> start_far[<span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">2</span>], <span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">shape =</span> <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">21</span>, <span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">size =</span> <span class="fl" style="color: #AD0000;
background-color: null;
font-style: inherit;">3.5</span>,</span>
<span id="cb13-26">           <span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">stroke =</span> <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">1</span>, <span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">colour =</span> te_ink, <span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">fill =</span> te_gold) <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">+</span></span>
<span id="cb13-27">  <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">scale_colour_manual</span>(<span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">values =</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">c</span>(te_rust, te_forest, te_gold), <span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">name =</span> <span class="cn" style="color: #8f5902;
background-color: null;
font-style: inherit;">NULL</span>) <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">+</span></span>
<span id="cb13-28">  <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">guides</span>(<span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">colour =</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">guide_legend</span>(<span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">nrow =</span> <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">2</span>)) <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">+</span></span>
<span id="cb13-29">  <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">labs</span>(<span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">x =</span> <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"r"</span>, <span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">y =</span> <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"K"</span>, <span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">title =</span> <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"One optimum, three paths"</span>,</span>
<span id="cb13-30">       <span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">subtitle =</span> <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"contours 1 to 40 below the max"</span>) <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">+</span></span>
<span id="cb13-31">  <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">theme_datasheet</span>() <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">+</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">theme</span>(<span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">legend.position =</span> <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"bottom"</span>)</span>
<span id="cb13-32">iter_df <span class="ot" style="color: #003B4F;
background-color: null;
font-style: inherit;">&lt;-</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">rbind</span>(</span>
<span id="cb13-33">  <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">data.frame</span>(<span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">call =</span> <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"default"</span>, <span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">step =</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">seq_len</span>(<span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">nrow</span>(tr_def<span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">$</span>path)), <span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">K =</span> tr_def<span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">$</span>path[, <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">2</span>]),</span>
<span id="cb13-34">  <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">data.frame</span>(<span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">call =</span> <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"ndeps = 1e-6"</span>, <span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">step =</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">seq_len</span>(<span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">nrow</span>(tr_nd<span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">$</span>path)), <span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">K =</span> tr_nd<span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">$</span>path[, <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">2</span>]),</span>
<span id="cb13-35">  <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">data.frame</span>(<span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">call =</span> <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"maxit = 5000"</span>, <span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">step =</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">seq_len</span>(<span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">nrow</span>(tr_mx<span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">$</span>path)), <span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">K =</span> tr_mx<span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">$</span>path[, <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">2</span>]),</span>
<span id="cb13-36">  <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">data.frame</span>(<span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">call =</span> <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"parscale"</span>, <span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">step =</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">seq_len</span>(<span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">nrow</span>(tr_ps<span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">$</span>path)), <span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">K =</span> tr_ps<span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">$</span>path[, <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">2</span>]),</span>
<span id="cb13-37">  <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">data.frame</span>(<span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">call =</span> <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"no restart"</span>, <span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">step =</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">seq_len</span>(<span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">nrow</span>(path_nr)), <span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">K =</span> path_nr[, <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">2</span>]))</span>
<span id="cb13-38">iter_df<span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">$</span>call <span class="ot" style="color: #003B4F;
background-color: null;
font-style: inherit;">&lt;-</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">factor</span>(iter_df<span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">$</span>call, <span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">levels =</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">c</span>(<span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"default"</span>, <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"ndeps = 1e-6"</span>, <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"maxit = 5000"</span>,</span>
<span id="cb13-39">                                                <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"parscale"</span>, <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"no restart"</span>))</span>
<span id="cb13-40">p_iter <span class="ot" style="color: #003B4F;
background-color: null;
font-style: inherit;">&lt;-</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">ggplot</span>(iter_df, <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">aes</span>(step, K, <span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">colour =</span> call, <span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">linetype =</span> call)) <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">+</span></span>
<span id="cb13-41">  <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">geom_hline</span>(<span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">yintercept =</span> fm_one<span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">$</span>K_ex, <span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">colour =</span> te_ink, <span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">linewidth =</span> <span class="fl" style="color: #AD0000;
background-color: null;
font-style: inherit;">0.3</span>) <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">+</span></span>
<span id="cb13-42">  <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">annotate</span>(<span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"text"</span>, <span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">x =</span> <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">1</span>, <span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">y =</span> fm_one<span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">$</span>K_ex, <span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">label =</span> <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"exact K"</span>, <span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">hjust =</span> <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">0</span>, <span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">vjust =</span> <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">-</span><span class="fl" style="color: #AD0000;
background-color: null;
font-style: inherit;">0.5</span>,</span>
<span id="cb13-43">           <span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">size =</span> <span class="fl" style="color: #AD0000;
background-color: null;
font-style: inherit;">3.3</span>, <span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">colour =</span> te_ink) <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">+</span></span>
<span id="cb13-44">  <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">geom_line</span>(<span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">aes</span>(<span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">linewidth =</span> call)) <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">+</span></span>
<span id="cb13-45">  <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">scale_colour_manual</span>(<span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">values =</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">c</span>(te_rust, te_ink, te_body, te_forest, te_gold), <span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">name =</span> <span class="cn" style="color: #8f5902;
background-color: null;
font-style: inherit;">NULL</span>,</span>
<span id="cb13-46">                      <span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">labels =</span> sci_lab) <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">+</span></span>
<span id="cb13-47">  <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">scale_linetype_manual</span>(<span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">values =</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">c</span>(<span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"solid"</span>, <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"dotted"</span>, <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"dashed"</span>, <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"solid"</span>, <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"solid"</span>), <span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">name =</span> <span class="cn" style="color: #8f5902;
background-color: null;
font-style: inherit;">NULL</span>,</span>
<span id="cb13-48">                        <span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">labels =</span> sci_lab) <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">+</span></span>
<span id="cb13-49">  <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">scale_linewidth_manual</span>(<span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">values =</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">c</span>(<span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">3</span>, <span class="fl" style="color: #AD0000;
background-color: null;
font-style: inherit;">1.1</span>, <span class="fl" style="color: #AD0000;
background-color: null;
font-style: inherit;">0.9</span>, <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">1</span>, <span class="fl" style="color: #AD0000;
background-color: null;
font-style: inherit;">1.1</span>), <span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">name =</span> <span class="cn" style="color: #8f5902;
background-color: null;
font-style: inherit;">NULL</span>, <span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">labels =</span> sci_lab) <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">+</span></span>
<span id="cb13-50">  <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">scale_x_log10</span>() <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">+</span></span>
<span id="cb13-51">  <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">guides</span>(<span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">colour =</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">guide_legend</span>(<span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">nrow =</span> <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">3</span>)) <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">+</span></span>
<span id="cb13-52">  <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">labs</span>(<span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">x =</span> <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"gradient evaluation (log scale)"</span>, <span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">y =</span> <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"K"</span>, <span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">title =</span> <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"K along the search"</span>,</span>
<span id="cb13-53">       <span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">subtitle =</span> <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"one series, five searches"</span>) <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">+</span></span>
<span id="cb13-54">  <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">theme_datasheet</span>() <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">+</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">theme</span>(<span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">legend.position =</span> <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"bottom"</span>, <span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">legend.text =</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">element_text</span>(<span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">hjust =</span> <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">0</span>))</span>
<span id="cb13-55">p_surf <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">+</span> p_iter <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">+</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">plot_annotation</span>(<span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">theme =</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">theme_datasheet</span>())</span></code></pre></div></div>
<div class="cell-output-display">
<div id="fig-path" class="quarto-float quarto-figure quarto-figure-center anchored" alt="Two panels for one series. Left: contour lines of the log-likelihood over r from about 0.1 to 0.9 and K from 2500 to 7500, closing around a black cross at r 0.56 and K 5509. A gold circle marks the start at r 0.30 and K 3000. The thick red default BFGS path runs straight left from the start to r about 0.13 and never leaves K = 3000. The green parscale path steps to r 0.22, climbs diagonally past K 4850 to r 0.77 and K 5250, then turns back to the cross. The gold path of the copy without the restart first follows the red one left along K = 3000, then climbs steeply to K 7000 at r 0.28, drops to about K 5500 at r 0.35 and runs right to the cross. Right: K against gradient evaluation on a logarithmic axis, with a thin line labelled exact K at about 5500. The thick red default line stops at evaluation 8 at K = 3000, with the ndeps and maxit lines hidden beneath it. The green parscale line rises from 3000 to the exact K by evaluation 14. The gold no-restart line stays at 3000 until about evaluation 18, shoots up to 7000 near evaluation 23, and settles on the exact K by about evaluation 30.">
<figure class="quarto-float quarto-float-fig figure">
<div aria-describedby="fig-path-caption-0ceaefa1-69ba-4598-a22c-09a6ac19f8ca">
<img src="https://tidyecology.com/posts/parameter-scale-and-what-optim-finds/index_files/figure-html/fig-path-1.png" class="img-fluid figure-img" alt="Two panels for one series. Left: contour lines of the log-likelihood over r from about 0.1 to 0.9 and K from 2500 to 7500, closing around a black cross at r 0.56 and K 5509. A gold circle marks the start at r 0.30 and K 3000. The thick red default BFGS path runs straight left from the start to r about 0.13 and never leaves K = 3000. The green parscale path steps to r 0.22, climbs diagonally past K 4850 to r 0.77 and K 5250, then turns back to the cross. The gold path of the copy without the restart first follows the red one left along K = 3000, then climbs steeply to K 7000 at r 0.28, drops to about K 5500 at r 0.35 and runs right to the cross. Right: K against gradient evaluation on a logarithmic axis, with a thin line labelled exact K at about 5500. The thick red default line stops at evaluation 8 at K = 3000, with the ndeps and maxit lines hidden beneath it. The green parscale line rises from 3000 to the exact K by evaluation 14. The gold no-restart line stays at 3000 until about evaluation 18, shoots up to 7000 near evaluation 23, and settles on the exact K by about evaluation 30." width="672">
</div>
<figcaption class="quarto-float-caption-bottom quarto-float-caption quarto-float-fig" id="fig-path-caption-0ceaefa1-69ba-4598-a22c-09a6ac19f8ca">
Figure&nbsp;3: The search on one series. Left: the log-likelihood surface over r and K, with sigma set to its best value at each point, and the points at which the default BFGS call, the parscale call and the R copy of vmmin with the restart deleted evaluated a gradient. Right: K at each gradient evaluation for four BFGS calls and the copy without the restart.
</figcaption>
</figure>
</div>
</div>
</div>
</section>
<section id="what-l-bfgs-b-and-nlminb-do-differently" class="level2">
<h2 id="what-l-bfgs-b-and-nlminb-do-differently-h" class="anchored" data-anchor-id="what-l-bfgs-b-and-nlminb-do-differently">What L-BFGS-B and nlminb do differently</h2>
<p>L-BFGS-B also works from a finite-difference gradient with the same <code>ndeps</code>, so if the gradient were the problem it would fail too. It mostly does not. Its design is described by Byrd and colleagues 1995, and it differs from <code>optim()</code>’s BFGS in two ways that can be measured from outside. It keeps its last five pairs of steps and gradient changes (<code>lmm = 5</code>) and rebuilds its matrix from them at each iteration, instead of discarding what it has learned on a schedule. And its default stopping rule, <code>factr = 1e7</code>, asks for a relative reduction of about <img src="https://latex.codecogs.com/png.latex?2.2%20%5Ctimes%2010%5E%7B-9%7D"> per iteration, which is about seven times tighter than the <code>reltol</code> of about <img src="https://latex.codecogs.com/png.latex?1.5%20%5Ctimes%2010%5E%7B-8%7D"> that BFGS uses. The question a numerical analyst would ask first is whether the box bounds help, since a box can rescale the problem as a side effect. The no-box calls answer that, and one more call, L-BFGS-B without a box and with <code>factr = 1e8</code>, puts its tolerance within a factor of two of BFGS’s.</p>
<div class="cell">
<div class="code-copy-outer-scaffold"><div class="sourceCode cell-code" id="cb14" style="background: #f1f3f5;"><pre class="sourceCode r code-with-copy"><code class="sourceCode r"><span id="cb14-1">stuck_lb  <span class="ot" style="color: #003B4F;
background-color: null;
font-style: inherit;">&lt;-</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">mean</span>(<span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">stuck</span>(res_far, <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"lb"</span>));  stuck_lbn <span class="ot" style="color: #003B4F;
background-color: null;
font-style: inherit;">&lt;-</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">mean</span>(<span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">stuck</span>(res_far, <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"lbn"</span>))</span>
<span id="cb14-2">off_def <span class="ot" style="color: #003B4F;
background-color: null;
font-style: inherit;">&lt;-</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">share_off</span>(res_far, <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"def"</span>)</span>
<span id="cb14-3">off_lb  <span class="ot" style="color: #003B4F;
background-color: null;
font-style: inherit;">&lt;-</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">share_off</span>(res_far, <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"lb"</span>);      off_lbn <span class="ot" style="color: #003B4F;
background-color: null;
font-style: inherit;">&lt;-</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">share_off</span>(res_far, <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"lbn"</span>)</span>
<span id="cb14-4">code0_stuck_all <span class="ot" style="color: #003B4F;
background-color: null;
font-style: inherit;">&lt;-</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">mean</span>(<span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">c</span>(res_far[<span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"code"</span>, <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"lb"</span>, <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">stuck</span>(res_far, <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"lb"</span>)],</span>
<span id="cb14-5">                          res_far[<span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"code"</span>, <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"lbn"</span>, <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">stuck</span>(res_far, <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"lbn"</span>)]) <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">==</span> <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">0</span>)</span>
<span id="cb14-6">off_is_stuck <span class="ot" style="color: #003B4F;
background-color: null;
font-style: inherit;">&lt;-</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">mean</span>(<span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">stuck</span>(res_far, <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"lbn"</span>)[<span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">abs</span>(<span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">rel_err</span>(res_far, <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"lbn"</span>)) <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">&gt;</span> <span class="fl" style="color: #AD0000;
background-color: null;
font-style: inherit;">0.10</span>])</span>
<span id="cb14-7">stuck_def <span class="ot" style="color: #003B4F;
background-color: null;
font-style: inherit;">&lt;-</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">mean</span>(<span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">stuck</span>(res_far, <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"def"</span>))</span>
<span id="cb14-8">tol_lb  <span class="ot" style="color: #003B4F;
background-color: null;
font-style: inherit;">&lt;-</span> <span class="fl" style="color: #AD0000;
background-color: null;
font-style: inherit;">1e7</span> <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">*</span> .Machine<span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">$</span>double.eps <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">/</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">sqrt</span>(.Machine<span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">$</span>double.eps)   <span class="co" style="color: #5E5E5E;
background-color: null;
font-style: inherit;"># factr tolerance over reltol</span></span>
<span id="cb14-9">res_lb8 <span class="ot" style="color: #003B4F;
background-color: null;
font-style: inherit;">&lt;-</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">vapply</span>(fms, <span class="cf" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">function</span>(fm) <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">one_row</span>(<span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">optim</span>(start_far, fm<span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">$</span>nll_K, <span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">method =</span> <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"L-BFGS-B"</span>,</span>
<span id="cb14-10">                                           <span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">control =</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">list</span>(<span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">factr =</span> <span class="fl" style="color: #AD0000;
background-color: null;
font-style: inherit;">1e8</span>))), <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">numeric</span>(<span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">3</span>))</span>
<span id="cb14-11">err_lb8   <span class="ot" style="color: #003B4F;
background-color: null;
font-style: inherit;">&lt;-</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">abs</span>(res_lb8[<span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"K"</span>, ] <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">-</span> K_ex) <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">/</span> K_ex</span>
<span id="cb14-12">off_lb8   <span class="ot" style="color: #003B4F;
background-color: null;
font-style: inherit;">&lt;-</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">mean</span>(err_lb8 <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">&gt;</span> <span class="fl" style="color: #AD0000;
background-color: null;
font-style: inherit;">0.10</span>)</span>
<span id="cb14-13">code0_lb8 <span class="ot" style="color: #003B4F;
background-color: null;
font-style: inherit;">&lt;-</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">mean</span>(res_lb8[<span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"code"</span>, err_lb8 <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">&gt;</span> <span class="fl" style="color: #AD0000;
background-color: null;
font-style: inherit;">0.10</span>] <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">==</span> <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">0</span>)</span></code></pre></div></div>
</div>
<p>With the box, L-BFGS-B leaves 0.058 of the series more than ten per cent off; without it, 0.108. So the box helps a little and is not what makes the method work. The misses are not near misses either. A fit counts as stuck here if its K ended within a tenth of a per cent of the starting 3000, and 0.058 of the boxed fits and 0.108 of the unboxed ones are stuck; every unboxed fit more than ten per cent off is a stuck one (share 1.00). The stuck fits report code 0 in 1.00 of cases. When L-BFGS-B fails, it fails the way BFGS fails, only less often: it settles r and sigma for the starting K and stops with a clean code. For comparison, 0.356 of the default BFGS fits are stuck by the same definition.</p>
<p>The tolerance is a large part of the rest. The default <code>factr</code> is 6.71 times tighter than BFGS’s <code>reltol</code>; loosen it tenfold, to <code>factr = 1e8</code>, and 0.548 of the unboxed fits are more than ten per cent off, 1.00 of those with code 0. What remains of L-BFGS-B’s advantage at a comparable tolerance is consistent with its not restarting, but its source was not stepped through here, so that part is an inference from the design and not a measurement.</p>
<p><code>nlminb()</code>, which calls the PORT library, is exact in all 500 series with and without bounds. That is a measurement on this model, not a property to rely on: the practical lesson from L-BFGS-B is that two methods of the same family, each called with its own defaults, can differ 9-fold in how often they miss by more than a tenth, so no rule of thumb about “gradient methods” settles it for a given fit.</p>
</section>
<section id="a-careful-start-shrinks-the-error-not-the-problem" class="level2">
<h2 id="a-careful-start-shrinks-the-error-not-the-problem-h" class="anchored" data-anchor-id="a-careful-start-shrinks-the-error-not-the-problem">A careful start shrinks the error, not the problem</h2>
<p>The size of the failure depends on the start. A start of K = 3000 when the answer is near 5000 is a plausible guess, but a careful analyst would start from the data. Here is a moment-based start, written before it was run: K from the mean of the second half of the series, when the colony should be fluctuating around its ceiling, and r from the mean log growth over the first five years divided by one minus the mean relative density over those years, kept between 0.05 and 1.5. Sigma starts at 0.3 as before.</p>
<div class="cell">
<div class="code-copy-outer-scaffold"><div class="sourceCode cell-code" id="cb15" style="background: #f1f3f5;"><pre class="sourceCode r code-with-copy"><code class="sourceCode r"><span id="cb15-1">moment_start <span class="ot" style="color: #003B4F;
background-color: null;
font-style: inherit;">&lt;-</span> <span class="cf" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">function</span>(N) {</span>
<span id="cb15-2">  K0 <span class="ot" style="color: #003B4F;
background-color: null;
font-style: inherit;">&lt;-</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">mean</span>(N[(n_yr <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">/</span> <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">2</span> <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">+</span> <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">1</span>)<span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">:</span>n_yr])</span>
<span id="cb15-3">  g5 <span class="ot" style="color: #003B4F;
background-color: null;
font-style: inherit;">&lt;-</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">diff</span>(<span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">log</span>(N))[<span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">1</span><span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">:</span><span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">5</span>]</span>
<span id="cb15-4">  r0 <span class="ot" style="color: #003B4F;
background-color: null;
font-style: inherit;">&lt;-</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">mean</span>(g5) <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">/</span> (<span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">1</span> <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">-</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">mean</span>(N[<span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">1</span><span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">:</span><span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">5</span>]) <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">/</span> K0)</span>
<span id="cb15-5">  <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">c</span>(<span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">min</span>(<span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">max</span>(r0, <span class="fl" style="color: #AD0000;
background-color: null;
font-style: inherit;">0.05</span>), <span class="fl" style="color: #AD0000;
background-color: null;
font-style: inherit;">1.5</span>), K0, <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">log</span>(<span class="fl" style="color: #AD0000;
background-color: null;
font-style: inherit;">0.3</span>))</span>
<span id="cb15-6">}</span>
<span id="cb15-7">starts_m <span class="ot" style="color: #003B4F;
background-color: null;
font-style: inherit;">&lt;-</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">lapply</span>(series, moment_start)</span>
<span id="cb15-8">K_start_m <span class="ot" style="color: #003B4F;
background-color: null;
font-style: inherit;">&lt;-</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">vapply</span>(starts_m, <span class="cf" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">function</span>(s) s[<span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">2</span>], <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">0</span>)</span>
<span id="cb15-9">res_mom <span class="ot" style="color: #003B4F;
background-color: null;
font-style: inherit;">&lt;-</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">vapply</span>(<span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">seq_along</span>(fms), <span class="cf" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">function</span>(i)</span>
<span id="cb15-10">  <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">run_fitters</span>(fms[[i]], starts_m[[i]], <span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">which =</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">c</span>(<span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"def"</span>, <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"maxit"</span>, <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"pars"</span>)),</span>
<span id="cb15-11">  <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">matrix</span>(<span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">0</span>, <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">3</span>, <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">3</span>))</span>
<span id="cb15-12"><span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">dimnames</span>(res_mom)[[<span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">2</span>]] <span class="ot" style="color: #003B4F;
background-color: null;
font-style: inherit;">&lt;-</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">c</span>(<span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"def"</span>, <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"maxit"</span>, <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"pars"</span>)</span>
<span id="cb15-13">tab_mom <span class="ot" style="color: #003B4F;
background-color: null;
font-style: inherit;">&lt;-</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">do.call</span>(rbind, <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">lapply</span>(<span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">c</span>(<span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"def"</span>, <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"maxit"</span>, <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"pars"</span>), <span class="cf" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">function</span>(f) <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">summ</span>(res_mom, f)))</span>
<span id="cb15-14">start_err_m <span class="ot" style="color: #003B4F;
background-color: null;
font-style: inherit;">&lt;-</span> (K_start_m <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">-</span> K_ex) <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">/</span> K_ex</span>
<span id="cb15-15">travel <span class="ot" style="color: #003B4F;
background-color: null;
font-style: inherit;">&lt;-</span> <span class="cf" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">function</span>(res, f, K0) (res[<span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"K"</span>, f, ] <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">-</span> K0) <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">/</span> (K_ex <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">-</span> K0)</span>
<span id="cb15-16">trav_far <span class="ot" style="color: #003B4F;
background-color: null;
font-style: inherit;">&lt;-</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">median</span>(<span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">travel</span>(res_far, <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"def"</span>, start_far[<span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">2</span>]))</span>
<span id="cb15-17">trav_mom <span class="ot" style="color: #003B4F;
background-color: null;
font-style: inherit;">&lt;-</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">median</span>(<span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">travel</span>(res_mom, <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"def"</span>, K_start_m))</span>
<span id="cb15-18">trav_mom_mx <span class="ot" style="color: #003B4F;
background-color: null;
font-style: inherit;">&lt;-</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">median</span>(<span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">travel</span>(res_mom, <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"maxit"</span>, K_start_m))</span>
<span id="cb15-19">code0_mom <span class="ot" style="color: #003B4F;
background-color: null;
font-style: inherit;">&lt;-</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">share_code0</span>(res_mom, <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"def"</span>); code0_mom_mx <span class="ot" style="color: #003B4F;
background-color: null;
font-style: inherit;">&lt;-</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">share_code0</span>(res_mom, <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"maxit"</span>)</span></code></pre></div></div>
</div>
<p>From the moment start the default BFGS call is a median 4.3 to 5.9 per cent from the exact K per block, and 0.15 of all series are more than ten per cent off. The moment start itself is a median 5.4 per cent from the exact K. That is the number to read next to the fit’s error: the fit is barely better than its own start. The fraction of the distance from the starting K to the exact K that the default call covers is a median 0.011 from the far start and 0.004 from the moment start; with <code>maxit = 5000</code> from the moment start it is 0.022. Code 0 is reported in 0.51 of the default fits and 0.82 with the raised limit. <code>parscale</code> from the moment start is exact again: its largest error in K over all 500 series is 0.00017.</p>
<p>So the careful start makes the headline smaller and the problem no smaller: BFGS in (r, K) returns something close to the K it was given. A good start hides that, because the answer looks sensible; it does not make the search find anything.</p>
<div class="cell">
<div class="code-copy-outer-scaffold"><div class="sourceCode cell-code" id="cb16" style="background: #f1f3f5;"><pre class="sourceCode r code-with-copy"><code class="sourceCode r"><span id="cb16-1">st_df <span class="ot" style="color: #003B4F;
background-color: null;
font-style: inherit;">&lt;-</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">rbind</span>(</span>
<span id="cb16-2">  <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">data.frame</span>(<span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">start =</span> <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"far start, K = 3000"</span>, <span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">call =</span> <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"BFGS, default"</span>,</span>
<span id="cb16-3">             <span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">x =</span> (start_far[<span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">2</span>] <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">-</span> K_ex) <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">/</span> K_ex, <span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">y =</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">rel_err</span>(res_far, <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"def"</span>)),</span>
<span id="cb16-4">  <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">data.frame</span>(<span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">start =</span> <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"moment start"</span>, <span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">call =</span> <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"BFGS, default"</span>,</span>
<span id="cb16-5">             <span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">x =</span> start_err_m, <span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">y =</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">rel_err</span>(res_mom, <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"def"</span>)),</span>
<span id="cb16-6">  <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">data.frame</span>(<span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">start =</span> <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"far start, K = 3000"</span>, <span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">call =</span> <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"BFGS, parscale"</span>,</span>
<span id="cb16-7">             <span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">x =</span> (start_far[<span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">2</span>] <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">-</span> K_ex) <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">/</span> K_ex, <span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">y =</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">rel_err</span>(res_far, <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"pars"</span>)),</span>
<span id="cb16-8">  <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">data.frame</span>(<span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">start =</span> <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"moment start"</span>, <span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">call =</span> <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"BFGS, parscale"</span>,</span>
<span id="cb16-9">             <span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">x =</span> start_err_m, <span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">y =</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">rel_err</span>(res_mom, <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"pars"</span>)))</span>
<span id="cb16-10"><span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">ggplot</span>(st_df, <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">aes</span>(x, y, <span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">colour =</span> call)) <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">+</span></span>
<span id="cb16-11">  <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">geom_abline</span>(<span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">slope =</span> <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">1</span>, <span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">intercept =</span> <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">0</span>, <span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">colour =</span> te_body, <span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">linetype =</span> <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"dashed"</span>, <span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">linewidth =</span> <span class="fl" style="color: #AD0000;
background-color: null;
font-style: inherit;">0.5</span>) <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">+</span></span>
<span id="cb16-12">  <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">geom_hline</span>(<span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">yintercept =</span> <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">0</span>, <span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">colour =</span> te_ink, <span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">linewidth =</span> <span class="fl" style="color: #AD0000;
background-color: null;
font-style: inherit;">0.4</span>) <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">+</span></span>
<span id="cb16-13">  <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">geom_point</span>(<span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">size =</span> <span class="fl" style="color: #AD0000;
background-color: null;
font-style: inherit;">1.1</span>, <span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">alpha =</span> <span class="fl" style="color: #AD0000;
background-color: null;
font-style: inherit;">0.6</span>) <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">+</span></span>
<span id="cb16-14">  <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">facet_wrap</span>(<span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">~</span> start, <span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">scales =</span> <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"free_x"</span>) <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">+</span></span>
<span id="cb16-15">  <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">scale_colour_manual</span>(<span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">values =</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">c</span>(te_rust, te_forest), <span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">name =</span> <span class="cn" style="color: #8f5902;
background-color: null;
font-style: inherit;">NULL</span>) <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">+</span></span>
<span id="cb16-16">  <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">scale_x_continuous</span>(<span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">labels =</span> pct) <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">+</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">scale_y_continuous</span>(<span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">labels =</span> pct) <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">+</span></span>
<span id="cb16-17">  <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">labs</span>(<span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">x =</span> <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"starting K relative to the exact MLE"</span>, <span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">y =</span> <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"fitted K relative to the exact MLE"</span>,</span>
<span id="cb16-18">       <span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">title =</span> <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"BFGS in (r, K) hands back its starting K"</span>,</span>
<span id="cb16-19">       <span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">subtitle =</span> <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"dashed diagonal: the fit returned its start"</span>) <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">+</span></span>
<span id="cb16-20">  <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">theme_datasheet</span>() <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">+</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">theme</span>(<span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">legend.position =</span> <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"bottom"</span>,</span>
<span id="cb16-21">                            <span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">strip.text =</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">element_text</span>(<span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">colour =</span> te_ink, <span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">face =</span> <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"bold"</span>))</span></code></pre></div></div>
<div class="cell-output-display">
<div id="fig-start" class="quarto-float quarto-figure quarto-figure-center anchored" alt="Two scatter panels, far start at K = 3000 on the left and the moment start on the right, one point per series. The horizontal axis is the starting K relative to the exact MLE and the vertical axis the fitted K relative to the exact MLE, with a dashed diagonal where the fit equals the start and a solid line at zero. Red default BFGS points lie along the dashed diagonal: in the far-start panel from about minus 55 to minus 10 per cent with a few scattered above it as high as plus 15; in the moment panel from about minus 35 to plus 20 per cent, packed onto the diagonal. Green parscale points lie on the zero line in both panels.">
<figure class="quarto-float quarto-float-fig figure">
<div aria-describedby="fig-start-caption-0ceaefa1-69ba-4598-a22c-09a6ac19f8ca">
<img src="https://tidyecology.com/posts/parameter-scale-and-what-optim-finds/index_files/figure-html/fig-start-1.png" class="img-fluid figure-img" alt="Two scatter panels, far start at K = 3000 on the left and the moment start on the right, one point per series. The horizontal axis is the starting K relative to the exact MLE and the vertical axis the fitted K relative to the exact MLE, with a dashed diagonal where the fit equals the start and a solid line at zero. Red default BFGS points lie along the dashed diagonal: in the far-start panel from about minus 55 to minus 10 per cent with a few scattered above it as high as plus 15; in the moment panel from about minus 35 to plus 20 per cent, packed onto the diagonal. Green parscale points lie on the zero line in both panels." width="672">
</div>
<figcaption class="quarto-float-caption-bottom quarto-float-caption quarto-float-fig" id="fig-start-caption-0ceaefa1-69ba-4598-a22c-09a6ac19f8ca">
Figure&nbsp;4: Where the fitted K ends up against where the search started, both relative to the exact MLE, for the far start and the moment-based start. Points on the dashed diagonal are fits that returned their starting K.
</figcaption>
</figure>
</div>
</div>
</div>
</section>
<section id="look-for-the-linear-form-first" class="level2">
<h2 id="look-for-the-linear-form-first-h" class="anchored" data-anchor-id="look-for-the-linear-form-first">Look for the linear form first</h2>
<p>The honest ordering of repairs starts before <code>optim()</code>. This model is a linear regression in (r, b), and a reader who noticed that would never have met any of the above; <code>lm()</code> gives the maximum, its standard errors, and K as a ratio whose interval can be had by the delta method or by profiling. Many ecological models are not linear in any spelling, and for those the order is: put every parameter on a scale where one unit is a meaningful change, either by rescaling the parameter itself (K in thousands, or log K, as the theta-logistic post does) or by passing <code>parscale</code> with the rough size of each parameter; then check the answer against a second method that does not share the first one’s weakness. Nelder-Mead and <code>nlminb()</code> were exact here from a bad start, and a disagreement between two fitters is information that a convergence code never carries. Bolker 2008 treats this kind of fitting at length for ecological models; Nash 2014 is the book on what the R optimisers do inside.</p>
<p>The two rescalings are cheap to check on the same series and from the same start, with the plain BFGS call and nothing in the control list.</p>
<div class="cell">
<div class="code-copy-outer-scaffold"><div class="sourceCode cell-code" id="cb17" style="background: #f1f3f5;"><pre class="sourceCode r code-with-copy"><code class="sourceCode r"><span id="cb17-1">res_logK <span class="ot" style="color: #003B4F;
background-color: null;
font-style: inherit;">&lt;-</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">vapply</span>(fms, <span class="cf" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">function</span>(fm) {</span>
<span id="cb17-2">  o <span class="ot" style="color: #003B4F;
background-color: null;
font-style: inherit;">&lt;-</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">optim</span>(<span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">c</span>(start_far[<span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">1</span>], <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">log</span>(start_far[<span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">2</span>]), start_far[<span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">3</span>]),</span>
<span id="cb17-3">             <span class="cf" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">function</span>(th) fm<span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">$</span><span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">nll_K</span>(<span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">c</span>(th[<span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">1</span>], <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">exp</span>(th[<span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">2</span>]), th[<span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">3</span>])), <span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">method =</span> <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"BFGS"</span>)</span>
<span id="cb17-4">  <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">c</span>(<span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">K =</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">exp</span>(o<span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">$</span>par[<span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">2</span>]), <span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">code =</span> o<span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">$</span>convergence) }, <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">numeric</span>(<span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">2</span>))</span>
<span id="cb17-5">res_kK <span class="ot" style="color: #003B4F;
background-color: null;
font-style: inherit;">&lt;-</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">vapply</span>(fms, <span class="cf" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">function</span>(fm) {</span>
<span id="cb17-6">  o <span class="ot" style="color: #003B4F;
background-color: null;
font-style: inherit;">&lt;-</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">optim</span>(<span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">c</span>(start_far[<span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">1</span>], start_far[<span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">2</span>] <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">/</span> <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">1000</span>, start_far[<span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">3</span>]),</span>
<span id="cb17-7">             <span class="cf" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">function</span>(th) fm<span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">$</span><span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">nll_K</span>(<span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">c</span>(th[<span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">1</span>], <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">1000</span> <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">*</span> th[<span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">2</span>], th[<span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">3</span>])), <span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">method =</span> <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"BFGS"</span>)</span>
<span id="cb17-8">  <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">c</span>(<span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">K =</span> <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">1000</span> <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">*</span> o<span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">$</span>par[<span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">2</span>], <span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">code =</span> o<span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">$</span>convergence) }, <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">numeric</span>(<span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">2</span>))</span>
<span id="cb17-9">err_logK <span class="ot" style="color: #003B4F;
background-color: null;
font-style: inherit;">&lt;-</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">abs</span>(res_logK[<span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"K"</span>, ] <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">-</span> K_ex) <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">/</span> K_ex</span>
<span id="cb17-10">err_kK   <span class="ot" style="color: #003B4F;
background-color: null;
font-style: inherit;">&lt;-</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">abs</span>(res_kK[<span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"K"</span>, ] <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">-</span> K_ex) <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">/</span> K_ex</span></code></pre></div></div>
</div>
<p>In log K the largest relative error in K over all 500 series is 0.00013, and with K in thousands it is 0.000059; both calls report code 0 in a share of 1.000 and 1.000 of series. Either spelling gives the restart an identity matrix of about the right shape to return to.</p>
<p><code>?optim</code> documents <code>parscale</code> accurately, and it is still not a matter of reading the help page, for two reasons. The failing call is the plain one, <code>optim(start, nll, method = "BFGS")</code>, with no control list at all, and the output either says it converged or gives a code 1 that a raised <code>maxit</code> often removes. And the obvious neighbouring methods do not agree: L-BFGS-B, with its own tighter default tolerance, mostly succeeds from the same start, so a reader who had once switched methods and seen the problem go away would have learned the wrong lesson.</p>
</section>
<section id="what-to-report" class="level2">
<h2 id="what-to-report-h" class="anchored" data-anchor-id="what-to-report">What to report</h2>
<p>State the parameterisation that was optimised, not only the one reported. A carrying capacity reported from a fit in log K and one from a fit in K are the same number only when both searches reached the maximum.</p>
<p>Report the optimiser, the start and the control list, including any <code>parscale</code> or rescaling. A reader who can see <code>method = "BFGS"</code> with a K in the thousands and no scaling now knows what to check.</p>
<p>Report the log-likelihood at the answer, and where possible the log-likelihood from a second fitter or a second start. Here the default fits fell a median 4.62 to 4.99 units short of the maximum per block, which is a difference a second fit would have shown immediately and a convergence code never did.</p>
<p>Do not report convergence code 0 as evidence that the maximum was found. In this model it was reported by 61 per cent of fits with a raised iteration limit, most of them wrong by more than a tenth of K.</p>
</section>
<section id="honest-limits" class="level2">
<h2 id="honest-limits-h" class="anchored" data-anchor-id="honest-limits">Honest limits</h2>
<p>The size of the failure is a function of how far the start is from the maximum, and most of the headline numbers here are for one fixed start. The moment-based arm is the check on that: it shrinks the error to roughly the error of the start itself. The finding that survives both starts is the fraction of the distance travelled, not the size of the error.</p>
<p>This is one model with three parameters, one of them thousands of times larger than the others. The same mechanism applies to any parameter whose gradient is small next to its neighbours’, such as a home-range scale in metres, an asymptotic length in millimetres or a population size, but the size of the effect in those models was not measured here. Rescaling every parameter to order one removes this particular failure when the gradient is of order one as well; a parameter near one that multiplies a covariate measured in thousands is badly scaled in the same way.</p>
<p>Only one noise level, one series length and one true growth rate were run. A longer series or a noisier one changes the curvature of the likelihood and could change how far BFGS gets before its relative tolerance stops it. For BFGS the tolerance was varied in one arm only, a tighter <code>reltol</code> at the default iteration limit; the tighter tolerance combined with a raised limit was not run.</p>
<p>For BFGS the mechanism is measured: the R copy of <code>vmmin</code> returns the same convergence code as <code>optim()</code> in a share of 0.998 of series, and deleting its restart line and nothing else makes every fit exact. For L-BFGS-B only part of it is: bounds are not what make it work, its tighter default tolerance accounts for much of its advantage, and when it fails it stops at its starting K. That the rest comes from not restarting is an inference from its published design, not a step through its source. <code>nlminb()</code> never failed here, and that is one model’s result, not a guarantee.</p>
<p>Finally, everything here is a demonstration of a known property of gradient methods, whose scaling Nash and Varadhan 2011 treat among the diagnostics for <code>optim()</code> and its relatives. The measured pieces are the size of the shortfall on an ordinary ecological fit, the rise in clean convergence codes under a raised <code>maxit</code>, and the tracing of the failure past the finite-difference step and the step length to the periodic restart in <code>optim()</code>’s BFGS code.</p>
</section>
<section id="references" class="level2">
<h2 id="references-h" class="anchored" data-anchor-id="references">References</h2>
<p>Nash JC, Varadhan R 2011 Journal of Statistical Software 43(9):1-14 (<a href="https://doi.org/10.18637/jss.v043.i09">10.18637/jss.v043.i09</a>)</p>
<p>Nelder JA, Mead R 1965 Computer Journal 7(4):308-313 (<a href="https://doi.org/10.1093/comjnl/7.4.308">10.1093/comjnl/7.4.308</a>)</p>
<p>Byrd RH, Lu P, Nocedal J, Zhu C 1995 SIAM Journal on Scientific Computing 16(5):1190-1208 (<a href="https://doi.org/10.1137/0916069">10.1137/0916069</a>)</p>
<p>Ricker WE 1954 Journal of the Fisheries Research Board of Canada 11(5):559-623 (<a href="https://doi.org/10.1139/f54-039">10.1139/f54-039</a>)</p>
<p>Nash JC 2014 Nonlinear Parameter Optimization Using R Tools (ISBN 978-1-118-56928-3)</p>
<p>Bolker BM 2008 Ecological Models and Data in R (ISBN 978-0-691-12522-0)</p>
</section>
<section id="related-tutorials" class="level2">
<h2 id="related-tutorials-h" class="anchored" data-anchor-id="related-tutorials">Related tutorials</h2>
<ul>
<li><a href="https://tidyecology.com/posts/starting-values-and-identifiability/">Starting values and identifiability in nls</a></li>
<li><a href="https://tidyecology.com/posts/theta-logistic-model/">The theta-logistic model in R</a></li>
<li><a href="https://tidyecology.com/posts/maximum-likelihood-with-optim/">Maximum likelihood by hand with optim() in R</a></li>
<li><a href="https://tidyecology.com/posts/lme4-convergence-warnings-and-scale/">The lme4 max|grad| warning and predictor scale</a></li>
</ul>
<details class="te-repro" data-pagefind-ignore="">
<summary>Reproducibility</summary>
<ul>
<li>Code last run: 2026-10-15</li>
<li>R version 4.5.3 (2026-03-11), aarch64-apple-darwin20</li>
<li>Packages: ggplot2 4.0.3, patchwork 1.3.2</li>
</ul>
</details>


<!-- -->

</section>

 ]]></description>
  <category>R</category>
  <category>numerical methods</category>
  <category>likelihood</category>
  <category>population dynamics</category>
  <category>reproducibility</category>
  <category>ecology tutorial</category>
  <guid isPermaLink="false">https://tidyecology.com/posts/parameter-scale-and-what-optim-finds/</guid>
  <pubDate>Mon, 28 Sep 2026 09:00:00 GMT</pubDate>
  <media:content url="https://tidyecology.com/posts/parameter-scale-and-what-optim-finds/thumbnail.png" medium="image" type="image/png" height="104" width="144"/>
</item>
<item>
  <title>The delta method: standard errors for derived values</title>
  <dc:creator>Tidy Ecology</dc:creator>
  <link>https://tidyecology.com/posts/the-delta-method/</link>
  <description><![CDATA[ 





<p>A hundred and fifty plots spread over a region where mean annual temperature runs from 2 to 22 C, and in each plot a record of whether a grassland plant is present. You fit <code>glm(pres ~ temp + I(temp^2), family = binomial)</code>, the squared term comes out negative, and the fitted curve has a hump. The species’ optimum, the temperature where the curve peaks, is <code>-b1 / (2 * b2)</code>. <code>summary()</code> gives you a standard error for <code>b1</code> and one for <code>b2</code>. What is the standard error of the optimum?</p>
<p>The optimum is a derived value: a function of fitted coefficients, not a coefficient itself. The delta method is the standard tool for its uncertainty, and many posts on this site use it in passing (for effective doses, return levels, occupancy). This post teaches it on the optimum: one line of algebra, a small helper that works for any derived value, a check that the helper is right, and the one trap in doing the calculation by hand from the <code>summary()</code> table.</p>
<p><strong>The short answer.</strong> Write the derived value as a function <code>g()</code> of the coefficient vector. Its standard error is <code>sqrt(t(grad) %*% vcov(fit) %*% grad)</code>, where <code>grad</code> holds the partial derivatives of <code>g()</code> with respect to each coefficient, evaluated at the estimates. Use the whole covariance matrix from <code>vcov()</code>, not only the standard errors on its diagonal: coefficients of <code>temp</code> and <code>temp^2</code> are strongly correlated, and leaving that out can make the standard error several times too large. When the derived value is a ratio whose denominator is poorly determined, the symmetric interval from the delta method misses mostly on one side, and percentiles of the derived value computed from simulated coefficient vectors follow the skew better.</p>
<p>All data here are simulated, and every seed is in the code.</p>
<div class="cell">
<div class="code-copy-outer-scaffold"><div class="sourceCode cell-code" id="cb1" style="background: #f1f3f5;"><pre class="sourceCode r code-with-copy"><code class="sourceCode r"><span id="cb1-1"><span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">library</span>(ggplot2)</span>
<span id="cb1-2"></span>
<span id="cb1-3">te_paper  <span class="ot" style="color: #003B4F;
background-color: null;
font-style: inherit;">&lt;-</span> <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"#f5f4ee"</span></span>
<span id="cb1-4">te_ink    <span class="ot" style="color: #003B4F;
background-color: null;
font-style: inherit;">&lt;-</span> <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"#16241d"</span></span>
<span id="cb1-5">te_body   <span class="ot" style="color: #003B4F;
background-color: null;
font-style: inherit;">&lt;-</span> <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"#2c3a31"</span></span>
<span id="cb1-6">te_forest <span class="ot" style="color: #003B4F;
background-color: null;
font-style: inherit;">&lt;-</span> <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"#275139"</span></span>
<span id="cb1-7">te_rust   <span class="ot" style="color: #003B4F;
background-color: null;
font-style: inherit;">&lt;-</span> <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"#b5534e"</span></span>
<span id="cb1-8">te_gold   <span class="ot" style="color: #003B4F;
background-color: null;
font-style: inherit;">&lt;-</span> <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"#c9b458"</span></span>
<span id="cb1-9">te_line   <span class="ot" style="color: #003B4F;
background-color: null;
font-style: inherit;">&lt;-</span> <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"#dad9ca"</span></span>
<span id="cb1-10"></span>
<span id="cb1-11">theme_datasheet <span class="ot" style="color: #003B4F;
background-color: null;
font-style: inherit;">&lt;-</span> <span class="cf" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">function</span>() {</span>
<span id="cb1-12">  <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">theme_minimal</span>(<span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">base_size =</span> <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">12</span>) <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">+</span></span>
<span id="cb1-13">    <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">theme</span>(<span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">plot.background  =</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">element_rect</span>(<span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">fill =</span> te_paper, <span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">colour =</span> <span class="cn" style="color: #8f5902;
background-color: null;
font-style: inherit;">NA</span>),</span>
<span id="cb1-14">          <span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">panel.background =</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">element_rect</span>(<span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">fill =</span> te_paper, <span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">colour =</span> <span class="cn" style="color: #8f5902;
background-color: null;
font-style: inherit;">NA</span>),</span>
<span id="cb1-15">          <span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">panel.grid.major =</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">element_line</span>(<span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">colour =</span> te_line, <span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">linewidth =</span> <span class="fl" style="color: #AD0000;
background-color: null;
font-style: inherit;">0.3</span>),</span>
<span id="cb1-16">          <span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">panel.grid.minor =</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">element_blank</span>(),</span>
<span id="cb1-17">          <span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">text             =</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">element_text</span>(<span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">colour =</span> te_body),</span>
<span id="cb1-18">          <span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">axis.text        =</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">element_text</span>(<span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">colour =</span> te_body),</span>
<span id="cb1-19">          <span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">strip.text       =</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">element_text</span>(<span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">colour =</span> te_ink, <span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">face =</span> <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"bold"</span>))</span>
<span id="cb1-20">}</span></code></pre></div></div>
</div>
<section id="a-humped-response-and-its-optimum" class="level2">
<h2 id="a-humped-response-and-its-optimum-h" class="anchored" data-anchor-id="a-humped-response-and-its-optimum">A humped response and its optimum</h2>
<p>A logistic regression with a linear and a squared term, <code>logit(p) = b0 + b1 * temp + b2 * temp^2</code>, is the Gaussian logit response model of ter Braak and Looman (1986). When <code>b2</code> is negative the curve has one peak. Its optimum is <code>u = -b1 / (2 * b2)</code>, its tolerance (the width of the hump, like a standard deviation) is <code>1 / sqrt(-2 * b2)</code>, and the peak probability is <code>plogis(b0 - b1^2 / (4 * b2))</code>. The simulation starts from those three quantities, fixed before anything was run: optimum 14 C, tolerance 4 C, peak probability 0.8. Temperature is left in degrees Celsius, as most people would enter it.</p>
<div class="cell">
<div class="code-copy-outer-scaffold"><div class="sourceCode cell-code" id="cb2" style="background: #f1f3f5;"><pre class="sourceCode r code-with-copy"><code class="sourceCode r"><span id="cb2-1">opt_true  <span class="ot" style="color: #003B4F;
background-color: null;
font-style: inherit;">&lt;-</span> <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">14</span>      <span class="co" style="color: #5E5E5E;
background-color: null;
font-style: inherit;"># C</span></span>
<span id="cb2-2">tol_true  <span class="ot" style="color: #003B4F;
background-color: null;
font-style: inherit;">&lt;-</span> <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">4</span>       <span class="co" style="color: #5E5E5E;
background-color: null;
font-style: inherit;"># C</span></span>
<span id="cb2-3">peak_true <span class="ot" style="color: #003B4F;
background-color: null;
font-style: inherit;">&lt;-</span> <span class="fl" style="color: #AD0000;
background-color: null;
font-style: inherit;">0.8</span></span>
<span id="cb2-4">b2_true <span class="ot" style="color: #003B4F;
background-color: null;
font-style: inherit;">&lt;-</span> <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">-</span><span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">1</span> <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">/</span> (<span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">2</span> <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">*</span> tol_true<span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">^</span><span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">2</span>)</span>
<span id="cb2-5">b1_true <span class="ot" style="color: #003B4F;
background-color: null;
font-style: inherit;">&lt;-</span> <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">-</span><span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">2</span> <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">*</span> b2_true <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">*</span> opt_true</span>
<span id="cb2-6">b0_true <span class="ot" style="color: #003B4F;
background-color: null;
font-style: inherit;">&lt;-</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">qlogis</span>(peak_true) <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">-</span> (b1_true <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">*</span> opt_true <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">+</span> b2_true <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">*</span> opt_true<span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">^</span><span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">2</span>)</span>
<span id="cb2-7"></span>
<span id="cb2-8">simulate_plots <span class="ot" style="color: #003B4F;
background-color: null;
font-style: inherit;">&lt;-</span> <span class="cf" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">function</span>(n_plots) {</span>
<span id="cb2-9">  temp <span class="ot" style="color: #003B4F;
background-color: null;
font-style: inherit;">&lt;-</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">runif</span>(n_plots, <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">2</span>, <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">22</span>)</span>
<span id="cb2-10">  <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">data.frame</span>(temp, <span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">pres =</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">rbinom</span>(n_plots, <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">1</span>, <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">plogis</span>(b0_true <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">+</span> b1_true <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">*</span> temp <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">+</span> b2_true <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">*</span> temp<span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">^</span><span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">2</span>)))</span>
<span id="cb2-11">}</span>
<span id="cb2-12"></span>
<span id="cb2-13"><span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">set.seed</span>(<span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">1016</span>)</span>
<span id="cb2-14">plots <span class="ot" style="color: #003B4F;
background-color: null;
font-style: inherit;">&lt;-</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">simulate_plots</span>(<span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">150</span>)</span>
<span id="cb2-15">fit   <span class="ot" style="color: #003B4F;
background-color: null;
font-style: inherit;">&lt;-</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">glm</span>(pres <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">~</span> temp <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">+</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">I</span>(temp<span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">^</span><span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">2</span>), <span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">family =</span> binomial, <span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">data =</span> plots)</span>
<span id="cb2-16"><span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">round</span>(<span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">summary</span>(fit)<span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">$</span>coefficients, <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">4</span>)</span></code></pre></div></div>
<div class="cell-output cell-output-stdout">
<pre><code>            Estimate Std. Error z value Pr(&gt;|z|)
(Intercept)  -3.4121     0.9118 -3.7422    2e-04
temp          0.6895     0.1663  4.1450    0e+00
I(temp^2)    -0.0255     0.0066 -3.8830    1e-04</code></pre>
</div>
<div class="code-copy-outer-scaffold"><div class="sourceCode cell-code" id="cb4" style="background: #f1f3f5;"><pre class="sourceCode r code-with-copy"><code class="sourceCode r"><span id="cb4-1">optimum <span class="ot" style="color: #003B4F;
background-color: null;
font-style: inherit;">&lt;-</span> <span class="cf" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">function</span>(b) <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">unname</span>(<span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">-</span>b[<span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">2</span>] <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">/</span> (<span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">2</span> <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">*</span> b[<span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">3</span>]))</span>
<span id="cb4-2">opt_hat <span class="ot" style="color: #003B4F;
background-color: null;
font-style: inherit;">&lt;-</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">optimum</span>(<span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">coef</span>(fit))</span>
<span id="cb4-3">opt_hat</span></code></pre></div></div>
<div class="cell-output cell-output-stdout">
<pre><code>[1] 13.52679</code></pre>
</div>
</div>
<p>The species was found in 89 of the 150 plots, and the fitted optimum is 13.53 C against the true 14. <code>summary()</code> has nothing to say about how certain that number is, because the optimum is not a row of its table.</p>
</section>
<section id="the-delta-method-in-one-line" class="level2">
<h2 id="the-delta-method-in-one-line-h" class="anchored" data-anchor-id="the-delta-method-in-one-line">The delta method in one line</h2>
<p>If the estimates are close to the truth, a smooth function <code>g()</code> of them is close to a straight line in the coefficients, and a straight line of normally distributed estimates has a variance you can write down. The first-order Taylor approximation gives</p>
<pre><code>Var(g(b_hat))  ~  t(grad) %*% V %*% grad</code></pre>
<p>where <code>V</code> is the covariance matrix of the coefficients (<code>vcov(fit)</code>) and <code>grad</code> is the vector of partial derivatives of <code>g()</code> with respect to <code>b0</code>, <code>b1</code> and <code>b2</code>, evaluated at the estimates (Oehlert 1992; Ver Hoef 2012 traces who first published it). For the optimum <code>-b1 / (2 * b2)</code> the derivatives are 0 for <code>b0</code>, <code>-1 / (2 * b2)</code> for <code>b1</code> and <code>b1 / (2 * b2^2)</code> for <code>b2</code>. Working out derivatives by hand is where mistakes creep in, so here is a helper that computes them numerically by central differences and works for any <code>g()</code>. Its step is a fixed fraction of each coefficient, because coefficients can be tiny (the squared term of an elevation in metres, say).</p>
<div class="cell">
<div class="code-copy-outer-scaffold"><div class="sourceCode cell-code" id="cb7" style="background: #f1f3f5;"><pre class="sourceCode r code-with-copy"><code class="sourceCode r"><span id="cb7-1">delta_se <span class="ot" style="color: #003B4F;
background-color: null;
font-style: inherit;">&lt;-</span> <span class="cf" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">function</span>(g, est, V, <span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">rel_step =</span> <span class="fl" style="color: #AD0000;
background-color: null;
font-style: inherit;">1e-5</span>) {</span>
<span id="cb7-2">  grad <span class="ot" style="color: #003B4F;
background-color: null;
font-style: inherit;">&lt;-</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">sapply</span>(<span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">seq_along</span>(est), <span class="cf" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">function</span>(j) {</span>
<span id="cb7-3">    step <span class="ot" style="color: #003B4F;
background-color: null;
font-style: inherit;">&lt;-</span> <span class="cf" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">if</span> (est[j] <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">!=</span> <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">0</span>) rel_step <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">*</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">abs</span>(est[j]) <span class="cf" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">else</span> rel_step</span>
<span id="cb7-4">    up <span class="ot" style="color: #003B4F;
background-color: null;
font-style: inherit;">&lt;-</span> est; up[j] <span class="ot" style="color: #003B4F;
background-color: null;
font-style: inherit;">&lt;-</span> est[j] <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">+</span> step</span>
<span id="cb7-5">    dn <span class="ot" style="color: #003B4F;
background-color: null;
font-style: inherit;">&lt;-</span> est; dn[j] <span class="ot" style="color: #003B4F;
background-color: null;
font-style: inherit;">&lt;-</span> est[j] <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">-</span> step</span>
<span id="cb7-6">    (<span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">g</span>(up) <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">-</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">g</span>(dn)) <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">/</span> (<span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">2</span> <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">*</span> step)</span>
<span id="cb7-7">  })</span>
<span id="cb7-8">  <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">sqrt</span>(<span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">drop</span>(<span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">t</span>(grad) <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">%*%</span> V <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">%*%</span> grad))</span>
<span id="cb7-9">}</span>
<span id="cb7-10"></span>
<span id="cb7-11">se_opt <span class="ot" style="color: #003B4F;
background-color: null;
font-style: inherit;">&lt;-</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">delta_se</span>(optimum, <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">coef</span>(fit), <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">vcov</span>(fit))</span>
<span id="cb7-12"></span>
<span id="cb7-13"><span class="co" style="color: #5E5E5E;
background-color: null;
font-style: inherit;"># the same with the derivatives written out</span></span>
<span id="cb7-14">b_hat <span class="ot" style="color: #003B4F;
background-color: null;
font-style: inherit;">&lt;-</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">coef</span>(fit); V_hat <span class="ot" style="color: #003B4F;
background-color: null;
font-style: inherit;">&lt;-</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">vcov</span>(fit)</span>
<span id="cb7-15">grad_opt <span class="ot" style="color: #003B4F;
background-color: null;
font-style: inherit;">&lt;-</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">c</span>(<span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">0</span>, <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">-</span><span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">1</span> <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">/</span> (<span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">2</span> <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">*</span> b_hat[<span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">3</span>]), b_hat[<span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">2</span>] <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">/</span> (<span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">2</span> <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">*</span> b_hat[<span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">3</span>]<span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">^</span><span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">2</span>))</span>
<span id="cb7-16">se_opt_analytic <span class="ot" style="color: #003B4F;
background-color: null;
font-style: inherit;">&lt;-</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">sqrt</span>(<span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">drop</span>(<span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">t</span>(grad_opt) <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">%*%</span> V_hat <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">%*%</span> grad_opt))</span>
<span id="cb7-17"><span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">c</span>(<span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">numeric =</span> se_opt, <span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">analytic =</span> se_opt_analytic)</span></code></pre></div></div>
<div class="cell-output cell-output-stdout">
<pre><code>  numeric  analytic 
0.6759742 0.6759742 </code></pre>
</div>
<div class="code-copy-outer-scaffold"><div class="sourceCode cell-code" id="cb9" style="background: #f1f3f5;"><pre class="sourceCode r code-with-copy"><code class="sourceCode r"><span id="cb9-1"><span class="co" style="color: #5E5E5E;
background-color: null;
font-style: inherit;"># the helper works for any derived value</span></span>
<span id="cb9-2">tolerance <span class="ot" style="color: #003B4F;
background-color: null;
font-style: inherit;">&lt;-</span> <span class="cf" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">function</span>(b) <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">unname</span>(<span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">1</span> <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">/</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">sqrt</span>(<span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">-</span><span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">2</span> <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">*</span> b[<span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">3</span>]))</span>
<span id="cb9-3"><span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">c</span>(<span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">tolerance =</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">tolerance</span>(<span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">coef</span>(fit)), <span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">se =</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">delta_se</span>(tolerance, <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">coef</span>(fit), <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">vcov</span>(fit)))</span></code></pre></div></div>
<div class="cell-output cell-output-stdout">
<pre><code>tolerance        se 
4.4292851 0.5703455 </code></pre>
</div>
</div>
<p>The numerical and the analytic gradient give the same standard error, 0.676 C, to a relative difference of <img src="https://latex.codecogs.com/png.latex?2.1%20%5Ctimes%2010%5E%7B-10%7D">. The 95 per cent interval for the optimum is the estimate plus or minus 1.96 standard errors: 12.20 to 14.85 C. The same helper, given a different <code>g()</code>, puts a standard error of 0.57 C on the tolerance of 4.43 C, and it would do the same for a peak probability, an LC50 or a population growth rate built from vital rates; Powell (2007) works through such demographic examples for field biologists.</p>
</section>
<section id="the-trap-two-standard-errors-without-their-covariance" class="level2">
<h2 id="the-trap-two-standard-errors-without-their-covariance-h" class="anchored" data-anchor-id="the-trap-two-standard-errors-without-their-covariance">The trap: two standard errors without their covariance</h2>
<p>The tempting shortcut takes the two standard errors from <code>summary()</code> and combines them as if the estimates of <code>b1</code> and <code>b2</code> were independent: the same formula with only the diagonal of <code>V</code>. That is what a hand calculation from the coefficient table gives, since the table has no covariances in it.</p>
<div class="cell">
<div class="code-copy-outer-scaffold"><div class="sourceCode cell-code" id="cb11" style="background: #f1f3f5;"><pre class="sourceCode r code-with-copy"><code class="sourceCode r"><span id="cb11-1">ci_full <span class="ot" style="color: #003B4F;
background-color: null;
font-style: inherit;">&lt;-</span> opt_hat <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">+</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">c</span>(<span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">-</span><span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">1</span>, <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">1</span>) <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">*</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">qnorm</span>(<span class="fl" style="color: #AD0000;
background-color: null;
font-style: inherit;">0.975</span>) <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">*</span> se_opt   <span class="co" style="color: #5E5E5E;
background-color: null;
font-style: inherit;"># the interval with the covariance</span></span>
<span id="cb11-2">se_diag <span class="ot" style="color: #003B4F;
background-color: null;
font-style: inherit;">&lt;-</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">sqrt</span>(<span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">sum</span>(grad_opt<span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">^</span><span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">2</span> <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">*</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">diag</span>(V_hat)))</span>
<span id="cb11-3">ci_diag <span class="ot" style="color: #003B4F;
background-color: null;
font-style: inherit;">&lt;-</span> opt_hat <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">+</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">c</span>(<span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">-</span><span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">1</span>, <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">1</span>) <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">*</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">qnorm</span>(<span class="fl" style="color: #AD0000;
background-color: null;
font-style: inherit;">0.975</span>) <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">*</span> se_diag</span>
<span id="cb11-4"><span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">round</span>(<span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">c</span>(<span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">full =</span> se_opt, <span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">diagonal_only =</span> se_diag, <span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">ratio =</span> se_diag <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">/</span> se_opt), <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">3</span>)</span></code></pre></div></div>
<div class="cell-output cell-output-stdout">
<pre><code>         full diagonal_only         ratio 
        0.676         4.773         7.062 </code></pre>
</div>
<div class="code-copy-outer-scaffold"><div class="sourceCode cell-code" id="cb13" style="background: #f1f3f5;"><pre class="sourceCode r code-with-copy"><code class="sourceCode r"><span id="cb13-1"><span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">round</span>(<span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">cov2cor</span>(V_hat), <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">3</span>)     <span class="co" style="color: #5E5E5E;
background-color: null;
font-style: inherit;"># correlations between the coefficient estimates</span></span></code></pre></div></div>
<div class="cell-output cell-output-stdout">
<pre><code>            (Intercept)   temp I(temp^2)
(Intercept)       1.000 -0.945     0.879
temp             -0.945  1.000    -0.982
I(temp^2)         0.879 -0.982     1.000</code></pre>
</div>
</div>
<p>Leaving out the covariance makes the standard error 7.1 times too large here. The reason is in the correlation matrix: the estimates of <code>b1</code> and <code>b2</code> have a correlation of -0.982. With temperature running from 2 to 22 C, <code>temp</code> and <code>temp^2</code> rise together across the plots, so a fit that tilts <code>b1</code> up must bend <code>b2</code> down to follow the data, and the optimum, their ratio, moves much less than either coefficient does. The diagonal-only formula throws that information away. The interval it reports for this survey runs from 4.2 to 22.9 C, from near the cold end of the sampled gradient to past its warm end:</p>
<div class="cell">
<div class="cell-output-display">
<div id="fig-one-survey" class="quarto-float quarto-figure quarto-figure-center anchored" alt="Scatter of 150 plots, presence at 1 and absence at 0, against mean annual temperature from 2 to 22 C. A green fitted curve rises from about 0.1 at 2 C to a peak near 0.78 at about 13.5 C and falls to about 0.36 at 22 C. A dotted gold vertical line marks 14 C. Two horizontal interval bars share the estimate of 13.5 C: a short green bar labelled full covariance runs from about 12.2 to 14.9 C, and a long red bar labelled diagonal only runs from about 4.2 to 22.9 C, past the warm end of the data.">
<figure class="quarto-float quarto-float-fig figure">
<div aria-describedby="fig-one-survey-caption-0ceaefa1-69ba-4598-a22c-09a6ac19f8ca">
<img src="https://tidyecology.com/posts/the-delta-method/index_files/figure-html/fig-one-survey-1.png" class="img-fluid figure-img" alt="Scatter of 150 plots, presence at 1 and absence at 0, against mean annual temperature from 2 to 22 C. A green fitted curve rises from about 0.1 at 2 C to a peak near 0.78 at about 13.5 C and falls to about 0.36 at 22 C. A dotted gold vertical line marks 14 C. Two horizontal interval bars share the estimate of 13.5 C: a short green bar labelled full covariance runs from about 12.2 to 14.9 C, and a long red bar labelled diagonal only runs from about 4.2 to 22.9 C, past the warm end of the data." width="720">
</div>
<figcaption class="quarto-float-caption-bottom quarto-float-caption quarto-float-fig" id="fig-one-survey-caption-0ceaefa1-69ba-4598-a22c-09a6ac19f8ca">
Figure&nbsp;1: One simulated survey of 150 plots. Points: presence (1) or absence (0), jittered vertically. Green curve: the fitted quadratic logistic regression. Horizontal bars: 95 per cent intervals for the optimum from the delta method with the full covariance matrix and with its diagonal only. The dotted line marks the true optimum of 14 C.
</figcaption>
</figure>
</div>
</div>
</div>
<p>One survey shows the size of the error, not how often each interval covers the truth. For that, the survey is repeated with new plots at three sample sizes, and both intervals are computed from the same fit each time:</p>
<div class="cell">
<div class="code-copy-outer-scaffold"><div class="sourceCode cell-code" id="cb15" style="background: #f1f3f5;"><pre class="sourceCode r code-with-copy"><code class="sourceCode r"><span id="cb15-1">one_survey <span class="ot" style="color: #003B4F;
background-color: null;
font-style: inherit;">&lt;-</span> <span class="cf" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">function</span>(n_plots) {</span>
<span id="cb15-2">  d  <span class="ot" style="color: #003B4F;
background-color: null;
font-style: inherit;">&lt;-</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">simulate_plots</span>(n_plots)</span>
<span id="cb15-3">  m  <span class="ot" style="color: #003B4F;
background-color: null;
font-style: inherit;">&lt;-</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">glm</span>(pres <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">~</span> temp <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">+</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">I</span>(temp<span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">^</span><span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">2</span>), <span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">family =</span> binomial, <span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">data =</span> d)</span>
<span id="cb15-4">  b  <span class="ot" style="color: #003B4F;
background-color: null;
font-style: inherit;">&lt;-</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">coef</span>(m); V <span class="ot" style="color: #003B4F;
background-color: null;
font-style: inherit;">&lt;-</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">vcov</span>(m)</span>
<span id="cb15-5">  gr <span class="ot" style="color: #003B4F;
background-color: null;
font-style: inherit;">&lt;-</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">c</span>(<span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">0</span>, <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">-</span><span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">1</span> <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">/</span> (<span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">2</span> <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">*</span> b[<span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">3</span>]), b[<span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">2</span>] <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">/</span> (<span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">2</span> <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">*</span> b[<span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">3</span>]<span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">^</span><span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">2</span>))</span>
<span id="cb15-6">  <span class="co" style="color: #5E5E5E;
background-color: null;
font-style: inherit;"># a percentile interval from 1000 simulated coefficient vectors (explained further down)</span></span>
<span id="cb15-7">  b_sim <span class="ot" style="color: #003B4F;
background-color: null;
font-style: inherit;">&lt;-</span> MASS<span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">::</span><span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">mvrnorm</span>(<span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">1000</span>, b, V); q <span class="ot" style="color: #003B4F;
background-color: null;
font-style: inherit;">&lt;-</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">quantile</span>(<span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">-</span>b_sim[, <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">2</span>] <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">/</span> (<span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">2</span> <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">*</span> b_sim[, <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">3</span>]), <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">c</span>(<span class="fl" style="color: #AD0000;
background-color: null;
font-style: inherit;">0.025</span>, <span class="fl" style="color: #AD0000;
background-color: null;
font-style: inherit;">0.975</span>))</span>
<span id="cb15-8">  <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">c</span>(<span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">n =</span> n_plots, <span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">opt =</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">optimum</span>(b), <span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">se_full =</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">sqrt</span>(<span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">drop</span>(<span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">t</span>(gr) <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">%*%</span> V <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">%*%</span> gr)),</span>
<span id="cb15-9">    <span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">se_diag =</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">sqrt</span>(<span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">sum</span>(gr<span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">^</span><span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">2</span> <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">*</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">diag</span>(V))), <span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">cor_b1b2 =</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">cov2cor</span>(V)[<span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">2</span>, <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">3</span>],</span>
<span id="cb15-10">    <span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">b2 =</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">unname</span>(b[<span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">3</span>]), <span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">lo_sim =</span> q[[<span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">1</span>]], <span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">hi_sim =</span> q[[<span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">2</span>]], <span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">converged =</span> m<span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">$</span>converged)</span>
<span id="cb15-11">}</span>
<span id="cb15-12">n_rep <span class="ot" style="color: #003B4F;
background-color: null;
font-style: inherit;">&lt;-</span> <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">3000</span></span>
<span id="cb15-13"><span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">set.seed</span>(<span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">2016</span>)</span>
<span id="cb15-14">reps <span class="ot" style="color: #003B4F;
background-color: null;
font-style: inherit;">&lt;-</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">as.data.frame</span>(<span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">do.call</span>(rbind, <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">lapply</span>(<span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">c</span>(<span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">60</span>, <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">150</span>, <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">400</span>), <span class="cf" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">function</span>(n_plots)</span>
<span id="cb15-15">  <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">t</span>(<span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">replicate</span>(n_rep, <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">one_survey</span>(n_plots))))))</span>
<span id="cb15-16"></span>
<span id="cb15-17">z95 <span class="ot" style="color: #003B4F;
background-color: null;
font-style: inherit;">&lt;-</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">qnorm</span>(<span class="fl" style="color: #AD0000;
background-color: null;
font-style: inherit;">0.975</span>)</span>
<span id="cb15-18">reps<span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">$</span>cover_full <span class="ot" style="color: #003B4F;
background-color: null;
font-style: inherit;">&lt;-</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">abs</span>(reps<span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">$</span>opt <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">-</span> opt_true) <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">&lt;</span> z95 <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">*</span> reps<span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">$</span>se_full</span>
<span id="cb15-19">reps<span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">$</span>cover_diag <span class="ot" style="color: #003B4F;
background-color: null;
font-style: inherit;">&lt;-</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">abs</span>(reps<span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">$</span>opt <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">-</span> opt_true) <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">&lt;</span> z95 <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">*</span> reps<span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">$</span>se_diag</span>
<span id="cb15-20">cover_tab <span class="ot" style="color: #003B4F;
background-color: null;
font-style: inherit;">&lt;-</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">do.call</span>(rbind, <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">lapply</span>(<span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">split</span>(reps, reps<span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">$</span>n), <span class="cf" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">function</span>(r) <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">data.frame</span>(</span>
<span id="cb15-21">  <span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">n_plots =</span> r<span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">$</span>n[<span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">1</span>], <span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">cover_full =</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">mean</span>(r<span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">$</span>cover_full),</span>
<span id="cb15-22">  <span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">mc_se =</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">sqrt</span>(<span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">mean</span>(r<span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">$</span>cover_full) <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">*</span> (<span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">1</span> <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">-</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">mean</span>(r<span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">$</span>cover_full)) <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">/</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">nrow</span>(r)),</span>
<span id="cb15-23">  <span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">cover_diag =</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">mean</span>(r<span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">$</span>cover_diag), <span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">width_ratio =</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">median</span>(r<span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">$</span>se_diag <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">/</span> r<span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">$</span>se_full),</span>
<span id="cb15-24">  <span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">cor_b1b2 =</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">median</span>(r<span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">$</span>cor_b1b2))))</span>
<span id="cb15-25"><span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">round</span>(cover_tab, <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">3</span>)</span></code></pre></div></div>
<div class="cell-output cell-output-stdout">
<pre><code>    n_plots cover_full mc_se cover_diag width_ratio cor_b1b2
60       60      0.948 0.004          1       7.242   -0.984
150     150      0.956 0.004          1       7.180   -0.983
400     400      0.951 0.004          1       7.164   -0.983</code></pre>
</div>
</div>
<p>With the full covariance the interval covers the true optimum in 0.948 to 0.956 of the surveys, depending on the sample size, against the nominal 0.95 (one Monte Carlo standard error is about 0.004). At every sample size the share is within 1.7 standard errors of 0.95, but the total hides lopsided misses, shown in the section on the ratio below. The diagonal-only interval missed the truth in 0 of the 9000 surveys (by the rule of three, an approximate 95 per cent upper bound of 0.0003 on its miss rate). That is not a better interval: it covers everything because its median width is 7.16 to 7.24 times the width of the correct one, at every sample size. More plots shrink both standard errors but not the ratio between them, because the ratio is set by the correlation between the estimates of <code>b1</code> and <code>b2</code> (median -0.983 to -0.984 across the three designs), and that correlation depends on where the temperatures lie, not on how many plots there are.</p>
</section>
<section id="centring-changes-the-parts-not-the-answer" class="level2">
<h2 id="centring-changes-the-parts-not-the-answer-h" class="anchored" data-anchor-id="centring-changes-the-parts-not-the-answer">Centring changes the parts, not the answer</h2>
<p>If the correlation comes from <code>temp</code> and <code>temp^2</code> rising together, subtracting the mean temperature before squaring should break it. It does, and it is worth seeing what it does and does not change:</p>
<div class="cell">
<div class="code-copy-outer-scaffold"><div class="sourceCode cell-code" id="cb17" style="background: #f1f3f5;"><pre class="sourceCode r code-with-copy"><code class="sourceCode r"><span id="cb17-1">temp_mean <span class="ot" style="color: #003B4F;
background-color: null;
font-style: inherit;">&lt;-</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">mean</span>(plots<span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">$</span>temp)</span>
<span id="cb17-2">plots<span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">$</span>temp_c <span class="ot" style="color: #003B4F;
background-color: null;
font-style: inherit;">&lt;-</span> plots<span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">$</span>temp <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">-</span> temp_mean</span>
<span id="cb17-3">fit_c <span class="ot" style="color: #003B4F;
background-color: null;
font-style: inherit;">&lt;-</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">glm</span>(pres <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">~</span> temp_c <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">+</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">I</span>(temp_c<span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">^</span><span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">2</span>), <span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">family =</span> binomial, <span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">data =</span> plots)</span>
<span id="cb17-4">b_c <span class="ot" style="color: #003B4F;
background-color: null;
font-style: inherit;">&lt;-</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">coef</span>(fit_c); V_c <span class="ot" style="color: #003B4F;
background-color: null;
font-style: inherit;">&lt;-</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">vcov</span>(fit_c)</span>
<span id="cb17-5">grad_c <span class="ot" style="color: #003B4F;
background-color: null;
font-style: inherit;">&lt;-</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">c</span>(<span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">0</span>, <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">-</span><span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">1</span> <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">/</span> (<span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">2</span> <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">*</span> b_c[<span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">3</span>]), b_c[<span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">2</span>] <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">/</span> (<span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">2</span> <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">*</span> b_c[<span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">3</span>]<span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">^</span><span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">2</span>))</span>
<span id="cb17-6">se_full_c <span class="ot" style="color: #003B4F;
background-color: null;
font-style: inherit;">&lt;-</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">delta_se</span>(optimum, b_c, V_c)</span>
<span id="cb17-7">se_diag_c <span class="ot" style="color: #003B4F;
background-color: null;
font-style: inherit;">&lt;-</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">sqrt</span>(<span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">sum</span>(grad_c<span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">^</span><span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">2</span> <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">*</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">diag</span>(V_c)))</span>
<span id="cb17-8">cor_c <span class="ot" style="color: #003B4F;
background-color: null;
font-style: inherit;">&lt;-</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">cov2cor</span>(V_c)[<span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">2</span>, <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">3</span>]</span>
<span id="cb17-9"><span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">round</span>(<span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">c</span>(<span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">cor_b1b2_c =</span> cor_c, <span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">optimum_c =</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">optimum</span>(b_c) <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">+</span> temp_mean,</span>
<span id="cb17-10">        <span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">se_full_c =</span> se_full_c, <span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">se_diag_c =</span> se_diag_c), <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">4</span>)</span></code></pre></div></div>
<div class="cell-output cell-output-stdout">
<pre><code>cor_b1b2_c  optimum_c  se_full_c  se_diag_c 
   -0.0623    13.5268     0.6760     0.6938 </code></pre>
</div>
</div>
<p>On the centred scale the correlation between the two estimates is -0.062 instead of -0.982, and the diagonal-only standard error drops to 0.694 C, 1.03 times the full one. The fitted curve, the optimum (once the mean temperature of 12.29 C is added back) and the full delta standard error, 0.676 C, are the same as before. That is the point of this section: the two models are one model written in two codings, and the correct standard error cannot depend on the coding. Centring made the shortcut less wrong on this survey; it did not make the shortcut the method, and the correlation will not be this small in every data set. Use the full <code>vcov()</code> in either coding. (Centring has a real job when a penalty is involved, which is the subject of <a href="https://tidyecology.com/posts/centring-a-quadratic-before-the-penalty/">Centring a quadratic before lasso or ridge</a>.)</p>
</section>
<section id="two-formulas-that-are-not-what-they-look-like" class="level2">
<h2 id="two-formulas-that-are-not-what-they-look-like-h" class="anchored" data-anchor-id="two-formulas-that-are-not-what-they-look-like">Two formulas that are not what they look like</h2>
<p>Centring is a coding that changes the parts and nothing else. Two other ways of writing the squared term look like codings too, and they are easy to type when a model is refitted from memory:</p>
<div class="cell">
<div class="code-copy-outer-scaffold"><div class="sourceCode cell-code" id="cb19" style="background: #f1f3f5;"><pre class="sourceCode r code-with-copy"><code class="sourceCode r"><span id="cb19-1">f_caret <span class="ot" style="color: #003B4F;
background-color: null;
font-style: inherit;">&lt;-</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">glm</span>(pres <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">~</span> temp <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">+</span> temp<span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">^</span><span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">2</span>, <span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">family =</span> binomial, <span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">data =</span> plots)             <span class="co" style="color: #5E5E5E;
background-color: null;
font-style: inherit;"># no I()</span></span>
<span id="cb19-2">f_poly  <span class="ot" style="color: #003B4F;
background-color: null;
font-style: inherit;">&lt;-</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">glm</span>(pres <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">~</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">poly</span>(temp, <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">2</span>), <span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">family =</span> binomial, <span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">data =</span> plots)              <span class="co" style="color: #5E5E5E;
background-color: null;
font-style: inherit;"># orthogonal basis</span></span>
<span id="cb19-3">f_raw   <span class="ot" style="color: #003B4F;
background-color: null;
font-style: inherit;">&lt;-</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">glm</span>(pres <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">~</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">poly</span>(temp, <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">2</span>, <span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">raw =</span> <span class="cn" style="color: #8f5902;
background-color: null;
font-style: inherit;">TRUE</span>), <span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">family =</span> binomial, <span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">data =</span> plots)  <span class="co" style="color: #5E5E5E;
background-color: null;
font-style: inherit;"># plain powers</span></span>
<span id="cb19-4"><span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">attr</span>(<span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">terms</span>(f_caret), <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"term.labels"</span>)   <span class="co" style="color: #5E5E5E;
background-color: null;
font-style: inherit;"># the terms R actually fitted</span></span></code></pre></div></div>
<div class="cell-output cell-output-stdout">
<pre><code>[1] "temp"</code></pre>
</div>
<div class="code-copy-outer-scaffold"><div class="sourceCode cell-code" id="cb21" style="background: #f1f3f5;"><pre class="sourceCode r code-with-copy"><code class="sourceCode r"><span id="cb21-1">coding_fits <span class="ot" style="color: #003B4F;
background-color: null;
font-style: inherit;">&lt;-</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">list</span>(f_caret, f_poly, f_raw)</span>
<span id="cb21-2">coding_tab <span class="ot" style="color: #003B4F;
background-color: null;
font-style: inherit;">&lt;-</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">data.frame</span>(<span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">formula =</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">c</span>(<span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"temp + temp^2"</span>, <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"poly(temp, 2)"</span>, <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"poly(temp, 2, raw = TRUE)"</span>),</span>
<span id="cb21-3">  <span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">n_coef   =</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">sapply</span>(coding_fits, <span class="cf" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">function</span>(m) <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">length</span>(<span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">coef</span>(m))),</span>
<span id="cb21-4">  <span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">optimum  =</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">sapply</span>(coding_fits, <span class="cf" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">function</span>(m) <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">optimum</span>(<span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">coef</span>(m))),</span>
<span id="cb21-5">  <span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">delta_se =</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">sapply</span>(coding_fits, <span class="cf" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">function</span>(m) <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">delta_se</span>(optimum, <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">coef</span>(m), <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">vcov</span>(m))),</span>
<span id="cb21-6">  <span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">AIC      =</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">sapply</span>(coding_fits, AIC))</span>
<span id="cb21-7"><span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">print</span>(coding_tab, <span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">digits =</span> <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">4</span>)</span></code></pre></div></div>
<div class="cell-output cell-output-stdout">
<pre><code>                    formula n_coef optimum delta_se   AIC
1             temp + temp^2      2      NA       NA 201.4
2             poly(temp, 2)      3  0.2857   0.1325 186.5
3 poly(temp, 2, raw = TRUE)      3 13.5268   0.6760 186.5</code></pre>
</div>
</div>
<p>The first formula runs without an error or a warning, and it is not a quadratic. In a model formula <code>^</code> means crossing, not a power: <code>(a + b)^2</code> asks for both main effects and their interaction, and <code>temp</code> crossed with itself is just <code>temp</code>. The model has 2 coefficients, exactly those of <code>glm(pres ~ temp)</code>. Its <code>summary()</code> shows a positive slope for temperature with p = 0.024, which read on its own says the plant favours warm plots, and its AIC is 201.39 against 186.52 for the humped model. The optimum comes back <code>NA</code>, because there is no third coefficient to divide by. <code>I(temp^2)</code> is what keeps the arithmetic away from the formula algebra.</p>
<p>The orthogonal polynomial is the same model: its fitted probabilities equal those of <code>fit</code> at every plot. Its coefficients are not <code>b0</code>, <code>b1</code> and <code>b2</code>, though. The first column of <code>poly()</code> is the centred temperature of the section above, rescaled to unit length, and the second is a quadratic made orthogonal to the first and to the intercept, also of unit length, both built from this survey’s own mean (12.29 C) and spread. Put these coefficients into <code>-b1 / (2 * b2)</code> and the “optimum” is 0.29, which read as a temperature lies below the coldest plot at 2.01 C. It is not a temperature. Worked through the basis, the formula returns <code>k * (u - c)</code>: the optimum <code>u</code> of the fitted curve shifted by <code>c</code> = 12.07 C (the average of the two centring constants <code>poly()</code> stored) and multiplied by <code>k</code> = 0.196 per C (the ratio of the lengths of the two basis columns before <code>poly()</code> scaled them to unit length), so on this survey’s basis any optimum from 2 to 22 C lands between -2.0 and 1.9. <code>delta_se()</code> gives it a standard error of 0.133, the correct 0.676 C times the same <code>k</code>: the uncertainty is right, the scale is foreign, and nothing in the output says so. Every step runs and the result looks like a temperature with a tight interval, which makes this the more dangerous of the two. With <code>raw = TRUE</code>, <code>poly()</code> returns the plain powers, the coefficients equal those of <code>fit</code>, and the optimum and its standard error are the ones found earlier, 13.53 and 0.676 C.</p>
<p>A check that does not depend on the coding reads the optimum off the fitted curve. <code>predict()</code> rebuilds the orthogonal basis for new temperatures from what the model stored, so this works for <code>f_poly</code> as well as for <code>fit</code>:</p>
<div class="cell">
<div class="code-copy-outer-scaffold"><div class="sourceCode cell-code" id="cb23" style="background: #f1f3f5;"><pre class="sourceCode r code-with-copy"><code class="sourceCode r"><span id="cb23-1">opt_curve <span class="ot" style="color: #003B4F;
background-color: null;
font-style: inherit;">&lt;-</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">optimize</span>(<span class="cf" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">function</span>(x) <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">predict</span>(f_poly, <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">data.frame</span>(<span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">temp =</span> x)), <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">c</span>(<span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">2</span>, <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">22</span>), <span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">maximum =</span> <span class="cn" style="color: #8f5902;
background-color: null;
font-style: inherit;">TRUE</span>)<span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">$</span>maximum</span>
<span id="cb23-2"><span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">c</span>(<span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">from_curve =</span> opt_curve, <span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">from_fit =</span> opt_hat)</span></code></pre></div></div>
<div class="cell-output cell-output-stdout">
<pre><code>from_curve   from_fit 
  13.52679   13.52679 </code></pre>
</div>
<div class="code-copy-outer-scaffold"><div class="sourceCode cell-code" id="cb25" style="background: #f1f3f5;"><pre class="sourceCode r code-with-copy"><code class="sourceCode r"><span id="cb25-1"><span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">stopifnot</span>(<span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">abs</span>(opt_curve <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">-</span> opt_hat) <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">&lt;</span> <span class="fl" style="color: #AD0000;
background-color: null;
font-style: inherit;">1e-3</span>)</span></code></pre></div></div>
</div>
<p>It returns 13.53 C, the optimum of <code>fit</code> to the tolerance of <code>optimize()</code>. <a href="https://tidyecology.com/posts/species-distribution-model-glm/">Species distribution modelling with GLM in R</a> reads the peak of its <code>poly()</code> fits the same way, from a grid of predictions. The curve gives the optimum but not its standard error: for that, refit with <code>I(temp^2)</code> or <code>raw = TRUE</code> and use <code>delta_se()</code>, or resample the plots and read the curve again each time (a bootstrap, not shown here).</p>
</section>
<section id="when-the-ratio-misbehaves" class="level2">
<h2 id="when-the-ratio-misbehaves-h" class="anchored" data-anchor-id="when-the-ratio-misbehaves">When the ratio misbehaves</h2>
<p>The delta method replaces <code>g()</code> by a straight line, and the optimum is a ratio. When the denominator, the curvature <code>b2</code>, is estimated well, a straight line is a good approximation, and the two-sided coverage in the coverage table above is close to 0.95. When <code>b2</code> is poorly determined, small changes in it move the optimum a long way in one direction and a short way in the other. The replicate surveys show it:</p>
<div class="cell">
<div class="code-copy-outer-scaffold"><div class="sourceCode cell-code" id="cb26" style="background: #f1f3f5;"><pre class="sourceCode r code-with-copy"><code class="sourceCode r"><span id="cb26-1">tail_tab <span class="ot" style="color: #003B4F;
background-color: null;
font-style: inherit;">&lt;-</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">do.call</span>(rbind, <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">lapply</span>(<span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">split</span>(reps, reps<span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">$</span>n), <span class="cf" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">function</span>(r) {</span>
<span id="cb26-2">  q <span class="ot" style="color: #003B4F;
background-color: null;
font-style: inherit;">&lt;-</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">quantile</span>(r<span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">$</span>opt, <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">c</span>(<span class="fl" style="color: #AD0000;
background-color: null;
font-style: inherit;">0.025</span>, <span class="fl" style="color: #AD0000;
background-color: null;
font-style: inherit;">0.975</span>))</span>
<span id="cb26-3">  <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">data.frame</span>(<span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">n_plots =</span> r<span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">$</span>n[<span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">1</span>], <span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">median_se =</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">median</span>(r<span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">$</span>se_full), <span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">sd_opt =</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">sd</span>(r<span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">$</span>opt),</span>
<span id="cb26-4">             <span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">below =</span> opt_true <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">-</span> q[[<span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">1</span>]], <span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">above =</span> q[[<span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">2</span>]] <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">-</span> opt_true,</span>
<span id="cb26-5">             <span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">miss_low =</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">mean</span>(r<span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">$</span>opt <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">+</span> z95 <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">*</span> r<span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">$</span>se_full <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">&lt;</span> opt_true),</span>
<span id="cb26-6">             <span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">miss_high =</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">mean</span>(r<span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">$</span>opt <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">-</span> z95 <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">*</span> r<span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">$</span>se_full <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">&gt;</span> opt_true))</span>
<span id="cb26-7">}))</span>
<span id="cb26-8"><span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">round</span>(tail_tab, <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">3</span>)</span></code></pre></div></div>
<div class="cell-output cell-output-stdout">
<pre><code>    n_plots median_se sd_opt below above miss_low miss_high
60       60     0.927  5.589 1.626 4.202    0.052     0.001
150     150     0.595  0.698 1.051 1.675    0.041     0.003
400     400     0.366  0.392 0.692 0.868    0.040     0.009</code></pre>
</div>
</div>
<p>At 60 plots the standard deviation of the 3000 estimated optima is 5.59 C, while the median delta standard error is 0.93 C. The standard deviation is driven by a few surveys: in 3 of them <code>b2</code> came out zero or positive, so the curve had no hump at all, and in others it was only slightly negative, which puts the “optimum” far from the true 14 C; 41 of the 3000 estimates lie outside 11 to 21 C, and without those the standard deviation is 1.18 C. The percentiles tell the shape better. The 2.5th percentile of the estimates lies 1.63 C below the true optimum and the 97.5th lies 4.20 C above it, while the delta interval reaches the same distance, about 1.82 C at the median standard error, on both sides. The coverage stayed near 0.95, but the misses are lopsided, where a symmetric interval should put 0.025 on each side: 0.052 of the intervals fell entirely below the truth and 0.001 entirely above it.</p>
<p>The misses sit on the cold side, opposite to the long warm tail, because the standard error moves with the estimate. The gradient of the optimum has <code>b2</code> in its denominator, so a flatter fitted curve (<code>b2</code> closer to zero) gets a larger standard error, and flatter curves also tend to put the optimum on the warm side. A warm estimate therefore carries a wide interval that still reaches back to 14 C, while a cold estimate from a sharp hump gets a narrow interval that can stop short of it. At 60 plots the median standard error is 0.77 C for estimates below 14 C and 1.23 C for those above; an interval of one fixed width (the median standard error) would have missed 0.014 below and 0.086 above, mostly on the warm side. The total coverage is what is left after the two sides trade off: at 150 plots 0.003 of the intervals missed on the warm side and 0.041 on the cold side, 0.044 in all against the nominal 0.05. With more plots the tails shrink and even out, 0.69 C below and 0.87 C above at 400 plots, but the misses there are still 0.040 below and 0.009 above.</p>
<div class="cell">
<div class="cell-output-display">
<div id="fig-tail" class="quarto-float quarto-figure quarto-figure-center anchored" alt="Three stacked histograms of estimated optima for 60, 150 and 400 plots, on an axis from 11 to 21 C, each with a red normal curve centred on a dotted gold line at 14 C. At 60 plots the bars follow the curve on the cold side but leave a long, thin tail of low bars stretching past 20 C on the warm side. At 150 plots the warm tail is short and ends near 16 C, and at 400 plots the bars are narrow and sit close to the curve between about 13 and 15.5 C.">
<figure class="quarto-float quarto-float-fig figure">
<div aria-describedby="fig-tail-caption-0ceaefa1-69ba-4598-a22c-09a6ac19f8ca">
<img src="https://tidyecology.com/posts/the-delta-method/index_files/figure-html/fig-tail-1.png" class="img-fluid figure-img" alt="Three stacked histograms of estimated optima for 60, 150 and 400 plots, on an axis from 11 to 21 C, each with a red normal curve centred on a dotted gold line at 14 C. At 60 plots the bars follow the curve on the cold side but leave a long, thin tail of low bars stretching past 20 C on the warm side. At 150 plots the warm tail is short and ends near 16 C, and at 400 plots the bars are narrow and sit close to the curve between about 13 and 15.5 C." width="720">
</div>
<figcaption class="quarto-float-caption-bottom quarto-float-caption quarto-float-fig" id="fig-tail-caption-0ceaefa1-69ba-4598-a22c-09a6ac19f8ca">
Figure&nbsp;2: Estimated optima from 3000 simulated surveys at each of three sample sizes. Bars: the estimates. Curve: a normal distribution centred on the true optimum with the median delta standard error, for comparison. The dotted line is the true optimum of 14 C. At 60 plots the estimates have a long warm tail; a few fall outside the plotted range.
</figcaption>
</figure>
</div>
</div>
</div>
<p>A symmetric interval centred on the estimate cannot follow this. The better intervals for a ratio of coefficients, Fieller’s interval and the profile likelihood interval, are compared with the delta interval in <a href="https://tidyecology.com/posts/confidence-intervals-for-effective-doses/">Confidence intervals for effective doses</a>; <a href="https://tidyecology.com/posts/maximum-likelihood-with-optim/">Maximum likelihood by hand with optim() in R</a> shows how to profile a parameter; and <a href="https://tidyecology.com/posts/return-levels-and-uncertainty/">Return levels and uncertainty</a> shows the same failure for a high quantile of an extreme value fit, where the delta interval is too short on the upper side.</p>
<p>The same fitted model gives a second route to an interval, without any derivatives: draw many coefficient vectors from a multivariate normal distribution with mean <code>coef(fit)</code> and covariance <code>vcov(fit)</code>, compute the optimum for each, and read off percentiles. <code>MASS::mvrnorm()</code> does the drawing. Here it is for the one survey of 150 plots, and then for the replicate surveys, where <code>one_survey()</code> already drew 1000 coefficient vectors per fit:</p>
<div class="cell">
<div class="code-copy-outer-scaffold"><div class="sourceCode cell-code" id="cb28" style="background: #f1f3f5;"><pre class="sourceCode r code-with-copy"><code class="sourceCode r"><span id="cb28-1"><span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">set.seed</span>(<span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">3016</span>)</span>
<span id="cb28-2">coef_draws <span class="ot" style="color: #003B4F;
background-color: null;
font-style: inherit;">&lt;-</span> MASS<span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">::</span><span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">mvrnorm</span>(<span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">10000</span>, <span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">mu =</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">coef</span>(fit), <span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">Sigma =</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">vcov</span>(fit))</span>
<span id="cb28-3">opt_draws  <span class="ot" style="color: #003B4F;
background-color: null;
font-style: inherit;">&lt;-</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">apply</span>(coef_draws, <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">1</span>, optimum)</span>
<span id="cb28-4"><span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">round</span>(<span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">rbind</span>(<span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">delta_interval =</span> ci_full, <span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">simulated =</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">quantile</span>(opt_draws, <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">c</span>(<span class="fl" style="color: #AD0000;
background-color: null;
font-style: inherit;">0.025</span>, <span class="fl" style="color: #AD0000;
background-color: null;
font-style: inherit;">0.975</span>))), <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">2</span>)</span></code></pre></div></div>
<div class="cell-output cell-output-stdout">
<pre><code>                2.5% 97.5%
delta_interval 12.20 14.85
simulated      12.31 15.42</code></pre>
</div>
<div class="code-copy-outer-scaffold"><div class="sourceCode cell-code" id="cb30" style="background: #f1f3f5;"><pre class="sourceCode r code-with-copy"><code class="sourceCode r"><span id="cb30-1"><span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">c</span>(<span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">sd_of_draws =</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">sd</span>(opt_draws), <span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">delta_se =</span> se_opt)</span></code></pre></div></div>
<div class="cell-output cell-output-stdout">
<pre><code>sd_of_draws    delta_se 
  7.3448119   0.6759742 </code></pre>
</div>
<div class="code-copy-outer-scaffold"><div class="sourceCode cell-code" id="cb32" style="background: #f1f3f5;"><pre class="sourceCode r code-with-copy"><code class="sourceCode r"><span id="cb32-1">sim_tab <span class="ot" style="color: #003B4F;
background-color: null;
font-style: inherit;">&lt;-</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">sapply</span>(<span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">split</span>(reps, reps<span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">$</span>n), <span class="cf" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">function</span>(r) <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">c</span>(<span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">miss_low =</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">mean</span>(r<span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">$</span>hi_sim <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">&lt;</span> opt_true),</span>
<span id="cb32-2">  <span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">miss_high =</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">mean</span>(r<span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">$</span>lo_sim <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">&gt;</span> opt_true), <span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">cover =</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">mean</span>(r<span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">$</span>lo_sim <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">&lt;</span> opt_true <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">&amp;</span> r<span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">$</span>hi_sim <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">&gt;</span> opt_true)))</span>
<span id="cb32-3"><span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">round</span>(sim_tab, <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">3</span>)       <span class="co" style="color: #5E5E5E;
background-color: null;
font-style: inherit;"># percentile intervals in the replicate surveys, columns = plots</span></span></code></pre></div></div>
<div class="cell-output cell-output-stdout">
<pre><code>             60   150  400
miss_low  0.023 0.020 0.03
miss_high 0.004 0.023 0.03
cover     0.973 0.957 0.94</code></pre>
</div>
</div>
<p>The percentile interval for the one survey runs from 12.31 to 15.42 C, against 12.20 to 14.85 C from the delta method: a lower end 0.11 C higher and an upper end 0.57 C higher, the same warm lean as in the replicate surveys. Read percentiles, not the standard deviation of the draws: one draw of the 10000 had <code>b2</code> practically zero and an optimum of 743 C, which inflates the standard deviation to 7.34 C (0.85 C without it) but moves a percentile by at most one place in the sorted draws. Over the replicate surveys the percentile interval spreads its misses more evenly than the delta interval at 150 and 400 plots (0.020 below and 0.023 above at 150, 0.030 and 0.030 at 400), with coverage 0.957 and 0.940. At 60 plots it covers 0.973 and still misses more often on the cold side (0.023 below, 0.004 above), though less often than the delta interval did. It follows the skew better; it is not exact either.</p>
<p>All of this has the optimum well inside the gradient. The usual sample-size check for a logistic regression is the rule of at least 10 events per variable (EPV) from the simulations of Peduzzi et al.&nbsp;(1996); events are the rarer outcome, and here the variables are the two slope coefficients, of <code>temp</code> and <code>temp^2</code>. The chunk below keeps the tolerance of 4 C and the peak probability of 0.8, sets the number of plots so that the rarer outcome is expected in 20 or 80 of them (EPV 10 or 40 at the expected prevalence; <code>epv_seen</code> is the average realised EPV), and moves the optimum from 14 C to 20 C, 2 C from the warm end of the sampled gradient. Beside the delta interval it computes Fieller’s set for the optimum, the same construction as for the effective doses: <code>b1 + 2 * u * b2</code> is zero at the optimum <code>u</code>, so the set holds every <code>u</code> for which <code>(b1 + 2 * u * b2)^2 &lt;= 1.96^2 * (v11 + 4 * u * v12 + 4 * u^2 * v22)</code>, with <code>v</code> the entries of <code>vcov()</code> for <code>b1</code> and <code>b2</code>. That is a quadratic inequality in <code>u</code>, and when <code>b2</code> cannot be told from zero its solution is not a bounded interval.</p>
<div class="cell">
<div class="code-copy-outer-scaffold"><div class="sourceCode cell-code" id="cb34" style="background: #f1f3f5;"><pre class="sourceCode r code-with-copy"><code class="sourceCode r"><span id="cb34-1">edge_design <span class="ot" style="color: #003B4F;
background-color: null;
font-style: inherit;">&lt;-</span> <span class="cf" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">function</span>(u, epv) {   <span class="co" style="color: #5E5E5E;
background-color: null;
font-style: inherit;"># host tolerance and peak, optimum u, plots set by the expected EPV</span></span>
<span id="cb34-2">  b2 <span class="ot" style="color: #003B4F;
background-color: null;
font-style: inherit;">&lt;-</span> <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">-</span><span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">1</span> <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">/</span> (<span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">2</span> <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">*</span> tol_true<span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">^</span><span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">2</span>); b1 <span class="ot" style="color: #003B4F;
background-color: null;
font-style: inherit;">&lt;-</span> <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">-</span><span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">2</span> <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">*</span> b2 <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">*</span> u; b0 <span class="ot" style="color: #003B4F;
background-color: null;
font-style: inherit;">&lt;-</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">qlogis</span>(peak_true) <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">-</span> (b1 <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">*</span> u <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">+</span> b2 <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">*</span> u<span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">^</span><span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">2</span>)</span>
<span id="cb34-3">  prev <span class="ot" style="color: #003B4F;
background-color: null;
font-style: inherit;">&lt;-</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">integrate</span>(<span class="cf" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">function</span>(x) <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">plogis</span>(b0 <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">+</span> b1 <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">*</span> x <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">+</span> b2 <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">*</span> x<span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">^</span><span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">2</span>), <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">2</span>, <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">22</span>)<span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">$</span>value <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">/</span> <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">20</span></span>
<span id="cb34-4">  <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">c</span>(<span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">opt =</span> u, <span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">epv =</span> epv, <span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">plots =</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">ceiling</span>(<span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">2</span> <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">*</span> epv <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">/</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">min</span>(prev, <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">1</span> <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">-</span> prev)), <span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">b0 =</span> b0, <span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">b1 =</span> b1, <span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">b2 =</span> b2)</span>
<span id="cb34-5">}</span>
<span id="cb34-6">edge_survey <span class="ot" style="color: #003B4F;
background-color: null;
font-style: inherit;">&lt;-</span> <span class="cf" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">function</span>(d) {</span>
<span id="cb34-7">  temp <span class="ot" style="color: #003B4F;
background-color: null;
font-style: inherit;">&lt;-</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">runif</span>(d[[<span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"plots"</span>]], <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">2</span>, <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">22</span>); warned <span class="ot" style="color: #003B4F;
background-color: null;
font-style: inherit;">&lt;-</span> <span class="cn" style="color: #8f5902;
background-color: null;
font-style: inherit;">FALSE</span></span>
<span id="cb34-8">  pres <span class="ot" style="color: #003B4F;
background-color: null;
font-style: inherit;">&lt;-</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">rbinom</span>(d[[<span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"plots"</span>]], <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">1</span>, <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">plogis</span>(d[[<span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"b0"</span>]] <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">+</span> d[[<span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"b1"</span>]] <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">*</span> temp <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">+</span> d[[<span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"b2"</span>]] <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">*</span> temp<span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">^</span><span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">2</span>))</span>
<span id="cb34-9">  m <span class="ot" style="color: #003B4F;
background-color: null;
font-style: inherit;">&lt;-</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">withCallingHandlers</span>(<span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">glm</span>(pres <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">~</span> temp <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">+</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">I</span>(temp<span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">^</span><span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">2</span>), <span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">family =</span> binomial),   <span class="co" style="color: #5E5E5E;
background-color: null;
font-style: inherit;"># count the 0-or-1 warning, do not print it</span></span>
<span id="cb34-10">    <span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">warning =</span> <span class="cf" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">function</span>(w) { <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">stopifnot</span>(<span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">grepl</span>(<span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"0 or 1"</span>, <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">conditionMessage</span>(w))); warned <span class="ot" style="color: #003B4F;
background-color: null;
font-style: inherit;">&lt;&lt;-</span> <span class="cn" style="color: #8f5902;
background-color: null;
font-style: inherit;">TRUE</span>; <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">invokeRestart</span>(<span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"muffleWarning"</span>) })</span>
<span id="cb34-11">  b <span class="ot" style="color: #003B4F;
background-color: null;
font-style: inherit;">&lt;-</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">unname</span>(<span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">coef</span>(m)); V <span class="ot" style="color: #003B4F;
background-color: null;
font-style: inherit;">&lt;-</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">vcov</span>(m); u <span class="ot" style="color: #003B4F;
background-color: null;
font-style: inherit;">&lt;-</span> d[[<span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"opt"</span>]]; o <span class="ot" style="color: #003B4F;
background-color: null;
font-style: inherit;">&lt;-</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">optimum</span>(b)</span>
<span id="cb34-12">  gr <span class="ot" style="color: #003B4F;
background-color: null;
font-style: inherit;">&lt;-</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">c</span>(<span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">0</span>, <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">-</span><span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">1</span> <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">/</span> (<span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">2</span> <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">*</span> b[<span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">3</span>]), b[<span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">2</span>] <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">/</span> (<span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">2</span> <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">*</span> b[<span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">3</span>]<span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">^</span><span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">2</span>)); se <span class="ot" style="color: #003B4F;
background-color: null;
font-style: inherit;">&lt;-</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">sqrt</span>(<span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">drop</span>(<span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">t</span>(gr) <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">%*%</span> V <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">%*%</span> gr))</span>
<span id="cb34-13">  <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">c</span>(<span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">epv_seen =</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">min</span>(<span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">sum</span>(pres), <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">sum</span>(<span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">1</span> <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">-</span> pres)) <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">/</span> <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">2</span>, <span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">warned =</span> warned, <span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">converged =</span> m<span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">$</span>converged,</span>
<span id="cb34-14">    <span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">wald_b1 =</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">abs</span>(b[<span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">2</span>] <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">-</span> d[[<span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"b1"</span>]]) <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">&lt;</span> z95 <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">*</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">sqrt</span>(V[<span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">2</span>, <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">2</span>]), <span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">wald_b2 =</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">abs</span>(b[<span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">3</span>] <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">-</span> d[[<span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"b2"</span>]]) <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">&lt;</span> z95 <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">*</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">sqrt</span>(V[<span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">3</span>, <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">3</span>]),</span>
<span id="cb34-15">    <span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">delta =</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">abs</span>(o <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">-</span> u) <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">&lt;</span> z95 <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">*</span> se, <span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">delta_low =</span> o <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">+</span> z95 <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">*</span> se <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">&lt;</span> u, <span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">delta_high =</span> o <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">-</span> z95 <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">*</span> se <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">&gt;</span> u,</span>
<span id="cb34-16">    <span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">fieller =</span> (b[<span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">2</span>] <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">+</span> <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">2</span> <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">*</span> u <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">*</span> b[<span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">3</span>])<span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">^</span><span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">2</span> <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">&lt;=</span> z95<span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">^</span><span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">2</span> <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">*</span> (V[<span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">2</span>, <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">2</span>] <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">+</span> <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">4</span> <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">*</span> u <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">*</span> V[<span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">2</span>, <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">3</span>] <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">+</span> <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">4</span> <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">*</span> u<span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">^</span><span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">2</span> <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">*</span> V[<span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">3</span>, <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">3</span>]),</span>
<span id="cb34-17">    <span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">bounded =</span> b[<span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">3</span>]<span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">^</span><span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">2</span> <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">&gt;</span> z95<span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">^</span><span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">2</span> <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">*</span> V[<span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">3</span>, <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">3</span>], <span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">nohump =</span> b[<span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">3</span>] <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">&gt;=</span> <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">0</span>, <span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">outside =</span> b[<span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">3</span>] <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">&lt;</span> <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">0</span> <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">&amp;&amp;</span> (o <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">&lt;</span> <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">2</span> <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">||</span> o <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">&gt;</span> <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">22</span>))   <span class="co" style="color: #5E5E5E;
background-color: null;
font-style: inherit;"># bounded: u^2 term &gt; 0</span></span>
<span id="cb34-18">}</span>
<span id="cb34-19">n_epv <span class="ot" style="color: #003B4F;
background-color: null;
font-style: inherit;">&lt;-</span> <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">2000</span>; <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">set.seed</span>(<span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">4016</span>); epv_tab <span class="ot" style="color: #003B4F;
background-color: null;
font-style: inherit;">&lt;-</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">t</span>(<span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">sapply</span>(<span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">list</span>(<span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">edge_design</span>(<span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">14</span>, <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">10</span>), <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">edge_design</span>(<span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">20</span>, <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">10</span>), <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">edge_design</span>(<span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">20</span>, <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">40</span>)), <span class="cf" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">function</span>(d)</span>
<span id="cb34-20">  <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">c</span>(d[<span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">c</span>(<span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"opt"</span>, <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"epv"</span>, <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"plots"</span>)], <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">colMeans</span>(<span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">t</span>(<span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">replicate</span>(n_epv, <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">edge_survey</span>(d)))))))</span>
<span id="cb34-21"><span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">round</span>(epv_tab, <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">3</span>)</span></code></pre></div></div>
<div class="cell-output cell-output-stdout">
<pre><code>     opt epv plots epv_seen warned converged wald_b1 wald_b2 delta delta_low
[1,]  14  10    46    9.661  0.000         1   0.970   0.970 0.948     0.052
[2,]  20  10    53   10.003  0.021         1   0.952   0.957 0.824     0.176
[3,]  20  40   211   40.103  0.000         1   0.957   0.959 0.889     0.110
     delta_high fieller bounded nohump outside
[1,]      0.001   0.958   0.744  0.004   0.012
[2,]      0.000   0.966   0.162  0.080   0.271
[3,]      0.000   0.962   0.769  0.002   0.212</code></pre>
</div>
</div>
<p>The rule does what it was built for: the Wald intervals for <code>b1</code> and <code>b2</code> cover their true values in 0.952 to 0.970 of the 2000 surveys per design, edge or not, and with the optimum at 14 C, EPV 10 (46 plots) gives the delta interval for the optimum a coverage of 0.948. With the optimum at 20 C the same EPV (53 plots) gives 0.824 (Monte Carlo standard error 0.009), every miss an interval that ends below 20 C, as most misses at 14 C did (0.052 below, 0.001 above), the cold-side lean of the 60-plot surveys above; four times the events (211 plots) raise it only to 0.889. The estimated optimum lay outside the sampled 2 to 22 C in 0.271 of the edge surveys at EPV 10 and 0.212 at EPV 40; in a further 0.080 at EPV 10 <code>b2</code> came out zero or positive, with no hump at all, and <code>glm()</code> warned of fitted probabilities of 0 or 1 in 0.021; every column counts both kinds of fit. Fieller’s set covers the true optimum in 0.958 to 0.966 of the surveys in every design, but read that as <a href="https://tidyecology.com/posts/confidence-intervals-for-effective-doses/">Confidence intervals for effective doses</a> reads its very narrow layout: at the edge with EPV 10 only 0.162 of the sets were a bounded interval (0.769 at EPV 40), and the rest were unbounded (every temperature outside one stretch, or every temperature). Such a set can rule out a stretch but does not pin the optimum to one, so its coverage says little; it is a more honest answer than a delta interval that misses, not a narrower one. EPV protects the coefficients; it says nothing about a ratio of them near the edge of the design.</p>
</section>
<section id="what-to-check-in-your-own-data" class="level2">
<h2 id="what-to-check-in-your-own-data-h" class="anchored" data-anchor-id="what-to-check-in-your-own-data">What to check in your own data</h2>
<p>Check that your derived value uses <code>vcov(fit)</code> and not <code>sqrt(diag(vcov(fit)))</code>. If you are copying numbers from a <code>summary()</code> table into a calculator or a spreadsheet, you are almost certainly leaving out the covariance. Check that a model with a squared term has three coefficients: <code>temp^2</code> without <code>I()</code> fits a straight line, and coefficients from <code>poly()</code> without <code>raw = TRUE</code> do not go into <code>-b1 / (2 * b2)</code>.</p>
<p>Check your gradient before you trust it. Compute the standard error with the numerical helper and with the derivatives you wrote out; if they differ beyond the fifth or sixth digit, one of them is wrong: check the step size of the numerical one and your algebra.</p>
<p>Look at the estimate of the denominator of any ratio you report. For an optimum, a curvature <code>b2</code> whose interval comes close to zero means the data barely show a hump, and the optimum can then lie anywhere; report that, and the profile or simulated interval, rather than a symmetric one. If the optimum sits near the end of your sampled gradient (the 20 C design above, where every delta miss fell on the cold side and 0.271 of the estimates at EPV 10 lay outside the gradient), expect a more lopsided sampling distribution, because the curve is only seen falling on one side. Draw coefficient vectors as in the <code>MASS::mvrnorm()</code> chunk above and look at the histogram of the derived value before you report plus or minus 1.96 standard errors.</p>
</section>
<section id="honest-limits" class="level2">
<h2 id="honest-limits-h" class="anchored" data-anchor-id="honest-limits">Honest limits</h2>
<p>The simulation uses one species: an optimum at 14 C (20 C, near the warm end, only in the events-per-variable check), a tolerance of 4 C, a peak probability of 0.8 and plots spread evenly from 2 to 22 C. The size of the diagonal-only error depends on the correlation between the coefficient estimates, and so on where the temperatures lie: centring made the shortcut look harmless on this survey. The coverage study counts every fit, including the 3 at 60 plots with no hump and 0.080 of the edge surveys at EPV 10, from which a real analysis would not report an optimum. The delta method is also only as good as <code>vcov()</code>: with overdispersed or spatially correlated presence data the covariance matrix is too small, and the delta standard error inherits that.</p>
</section>
<section id="references" class="level2">
<h2 id="references-h" class="anchored" data-anchor-id="references">References</h2>
<p>Oehlert GW 1992 The American Statistician 46(1):27-29 (<a href="https://doi.org/10.1080/00031305.1992.10475842">10.1080/00031305.1992.10475842</a>)</p>
<p>Peduzzi P, Concato J, Kemper E, Holford TR, Feinstein AR 1996 Journal of Clinical Epidemiology 49(12):1373-1379 (<a href="https://doi.org/10.1016/S0895-4356(96)00236-3">10.1016/S0895-4356(96)00236-3</a>)</p>
<p>Powell LA 2007 The Condor 109(4):949-954 (<a href="https://doi.org/10.1093/condor/109.4.949">10.1093/condor/109.4.949</a>)</p>
<p>ter Braak CJF, Looman CWN 1986 Vegetatio 65(1):3-11 (<a href="https://doi.org/10.1007/BF00032121">10.1007/BF00032121</a>)</p>
<p>Ver Hoef JM 2012 The American Statistician 66(2):124-127 (<a href="https://doi.org/10.1080/00031305.2012.687494">10.1080/00031305.2012.687494</a>)</p>
</section>
<section id="related-tutorials" class="level2">
<h2 id="related-tutorials-h" class="anchored" data-anchor-id="related-tutorials">Related tutorials</h2>
<ul>
<li><a href="https://tidyecology.com/posts/confidence-intervals-for-effective-doses/">Confidence intervals for effective doses</a></li>
<li><a href="https://tidyecology.com/posts/maximum-likelihood-with-optim/">Maximum likelihood by hand with optim() in R</a></li>
<li><a href="https://tidyecology.com/posts/global-sensitivity-and-sobol-indices/">Global sensitivity analysis with Sobol indices</a></li>
<li><a href="https://tidyecology.com/posts/standard-errors-confidence-intervals/">Standard errors and confidence intervals in R</a></li>
</ul>
<details class="te-repro" data-pagefind-ignore="">
<summary>Reproducibility</summary>
<ul>
<li>Code last run: 2026-09-30</li>
<li>R version 4.5.3 (2026-03-11), aarch64-apple-darwin20</li>
<li>Packages: ggplot2 4.0.3, MASS 7.3-66</li>
</ul>
</details>


<!-- -->

</section>

 ]]></description>
  <category>R</category>
  <category>statistics</category>
  <category>GLM</category>
  <category>logistic regression</category>
  <category>uncertainty</category>
  <category>simulation</category>
  <category>ecology tutorial</category>
  <guid isPermaLink="false">https://tidyecology.com/posts/the-delta-method/</guid>
  <pubDate>Mon, 28 Sep 2026 08:00:00 GMT</pubDate>
  <media:content url="https://tidyecology.com/posts/the-delta-method/thumbnail.png" medium="image" type="image/png" height="104" width="144"/>
</item>
<item>
  <title>Maximum likelihood by hand with optim() in R</title>
  <dc:creator>Tidy Ecology</dc:creator>
  <link>https://tidyecology.com/posts/maximum-likelihood-with-optim/</link>
  <description><![CDATA[ 





<p>Eighty quadrats across a wet meadow, half of them inside a cattle paddock, and in each one a count of marsh marigold plants and a reading of soil moisture. You already know how to fit this: <code>glm(count ~ moisture + grazed, family = poisson)</code>. Then you open an occupancy or capture-recapture post on this site and find no <code>glm()</code> at all. Instead there is a function called <code>nll</code>, a vector of starting numbers, and a call to <code>optim()</code>. This post is the bridge between the two. It writes the likelihood that <code>glm()</code> maximises for you, maximises it by hand, and then uses the same recipe for a model that <code>glm()</code> cannot fit.</p>
<p>The recipe has four parts: a function that takes a vector of parameters and returns minus the log-likelihood of the data, a starting vector, a call to <code>optim()</code> that returns the minimum, and the curvature at that minimum, which gives the standard errors. Everything else in this post is a check that the recipe did what you think it did, and one trap that makes it fail before it takes a single step. Chapters 6 and 7 of Bolker (2008) teach the same recipe at book length, and the <code>optim()</code> help page documents every argument used below.</p>
<p><strong>The short answer.</strong> Write the log-likelihood as a sum of <code>log = TRUE</code> densities, never as the log of a product. Return it with a minus sign, because <code>optim()</code> minimises. Ask for <code>hessian = TRUE</code> and invert the Hessian for the covariance. Keep each parameter on a scale where any real number is allowed (logs for positive quantities), and back-transform interval endpoints, not standard errors. Before you trust the recipe on a new model, run it once on a model that <code>glm()</code> can fit and compare.</p>
<p>The applied version of this recipe, for occupancy, is in <a href="https://tidyecology.com/posts/single-season-occupancy-model/">Fitting single-season occupancy models in R</a>. The data here are simulated, and every seed is in the code.</p>
<div class="cell">
<div class="code-copy-outer-scaffold"><div class="sourceCode cell-code" id="cb1" style="background: #f1f3f5;"><pre class="sourceCode r code-with-copy"><code class="sourceCode r"><span id="cb1-1"><span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">library</span>(ggplot2)</span>
<span id="cb1-2"><span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">options</span>(<span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">scipen =</span> <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">6</span>)</span>
<span id="cb1-3"></span>
<span id="cb1-4">te_paper  <span class="ot" style="color: #003B4F;
background-color: null;
font-style: inherit;">&lt;-</span> <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"#f5f4ee"</span></span>
<span id="cb1-5">te_ink    <span class="ot" style="color: #003B4F;
background-color: null;
font-style: inherit;">&lt;-</span> <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"#16241d"</span></span>
<span id="cb1-6">te_body   <span class="ot" style="color: #003B4F;
background-color: null;
font-style: inherit;">&lt;-</span> <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"#2c3a31"</span></span>
<span id="cb1-7">te_forest <span class="ot" style="color: #003B4F;
background-color: null;
font-style: inherit;">&lt;-</span> <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"#275139"</span></span>
<span id="cb1-8">te_rust   <span class="ot" style="color: #003B4F;
background-color: null;
font-style: inherit;">&lt;-</span> <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"#b5534e"</span></span>
<span id="cb1-9">te_gold   <span class="ot" style="color: #003B4F;
background-color: null;
font-style: inherit;">&lt;-</span> <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"#c9b458"</span></span>
<span id="cb1-10">te_line   <span class="ot" style="color: #003B4F;
background-color: null;
font-style: inherit;">&lt;-</span> <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"#dad9ca"</span></span>
<span id="cb1-11"></span>
<span id="cb1-12">theme_datasheet <span class="ot" style="color: #003B4F;
background-color: null;
font-style: inherit;">&lt;-</span> <span class="cf" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">function</span>() {</span>
<span id="cb1-13">  <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">theme_minimal</span>(<span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">base_size =</span> <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">12</span>) <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">+</span></span>
<span id="cb1-14">    <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">theme</span>(<span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">plot.background  =</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">element_rect</span>(<span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">fill =</span> te_paper, <span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">colour =</span> <span class="cn" style="color: #8f5902;
background-color: null;
font-style: inherit;">NA</span>),</span>
<span id="cb1-15">          <span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">panel.background =</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">element_rect</span>(<span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">fill =</span> te_paper, <span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">colour =</span> <span class="cn" style="color: #8f5902;
background-color: null;
font-style: inherit;">NA</span>),</span>
<span id="cb1-16">          <span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">panel.grid.major =</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">element_line</span>(<span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">colour =</span> te_line, <span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">linewidth =</span> <span class="fl" style="color: #AD0000;
background-color: null;
font-style: inherit;">0.3</span>),</span>
<span id="cb1-17">          <span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">panel.grid.minor =</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">element_blank</span>(),</span>
<span id="cb1-18">          <span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">text             =</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">element_text</span>(<span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">colour =</span> te_body),</span>
<span id="cb1-19">          <span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">axis.text        =</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">element_text</span>(<span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">colour =</span> te_body),</span>
<span id="cb1-20">          <span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">strip.text       =</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">element_text</span>(<span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">colour =</span> te_ink, <span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">face =</span> <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"bold"</span>))</span>
<span id="cb1-21">}</span></code></pre></div></div>
</div>
<section id="the-meadow-data" class="level2">
<h2 id="the-meadow-data-h" class="anchored" data-anchor-id="the-meadow-data">The meadow data</h2>
<p>Soil moisture is recorded as volumetric water content, a fraction between 0.05 and 0.60. The true mean count rises with moisture and levels off in wet soil, and grazing lowers the level it reaches. The design constants are fixed in the code: an ungrazed asymptote of 12 plants per quadrat, a rate of 6 per unit of water content, and grazed quadrats reaching 0.6 of the ungrazed asymptote.</p>
<div class="cell">
<div class="code-copy-outer-scaffold"><div class="sourceCode cell-code" id="cb2" style="background: #f1f3f5;"><pre class="sourceCode r code-with-copy"><code class="sourceCode r"><span id="cb2-1"><span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">set.seed</span>(<span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">1410</span>)</span>
<span id="cb2-2">n_quad   <span class="ot" style="color: #003B4F;
background-color: null;
font-style: inherit;">&lt;-</span> <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">80</span></span>
<span id="cb2-3">moisture <span class="ot" style="color: #003B4F;
background-color: null;
font-style: inherit;">&lt;-</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">round</span>(<span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">runif</span>(n_quad, <span class="fl" style="color: #AD0000;
background-color: null;
font-style: inherit;">0.05</span>, <span class="fl" style="color: #AD0000;
background-color: null;
font-style: inherit;">0.60</span>), <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">3</span>)     <span class="co" style="color: #5E5E5E;
background-color: null;
font-style: inherit;"># volumetric water content</span></span>
<span id="cb2-4">grazed   <span class="ot" style="color: #003B4F;
background-color: null;
font-style: inherit;">&lt;-</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">rep</span>(<span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">c</span>(<span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">0</span>, <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">1</span>), <span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">each =</span> n_quad <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">/</span> <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">2</span>)          <span class="co" style="color: #5E5E5E;
background-color: null;
font-style: inherit;"># 1 = inside the paddock</span></span>
<span id="cb2-5">a_true <span class="ot" style="color: #003B4F;
background-color: null;
font-style: inherit;">&lt;-</span> <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">12</span>; b_true <span class="ot" style="color: #003B4F;
background-color: null;
font-style: inherit;">&lt;-</span> <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">6</span>; graze_ratio <span class="ot" style="color: #003B4F;
background-color: null;
font-style: inherit;">&lt;-</span> <span class="fl" style="color: #AD0000;
background-color: null;
font-style: inherit;">0.6</span>        <span class="co" style="color: #5E5E5E;
background-color: null;
font-style: inherit;"># design constants</span></span>
<span id="cb2-6">lambda_true <span class="ot" style="color: #003B4F;
background-color: null;
font-style: inherit;">&lt;-</span> a_true <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">*</span> graze_ratio<span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">^</span>grazed <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">*</span> (<span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">1</span> <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">-</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">exp</span>(<span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">-</span>b_true <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">*</span> moisture))</span>
<span id="cb2-7"></span>
<span id="cb2-8">quads <span class="ot" style="color: #003B4F;
background-color: null;
font-style: inherit;">&lt;-</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">data.frame</span>(moisture, grazed, <span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">count =</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">rpois</span>(n_quad, lambda_true))</span>
<span id="cb2-9"><span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">head</span>(quads, <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">3</span>)</span></code></pre></div></div>
<div class="cell-output cell-output-stdout">
<pre><code>  moisture grazed count
1    0.198      0     7
2    0.342      0    10
3    0.564      0    11</code></pre>
</div>
</div>
</section>
<section id="a-likelihood-glm-already-knows" class="level2">
<h2 id="a-likelihood-glm-already-knows-h" class="anchored" data-anchor-id="a-likelihood-glm-already-knows">A likelihood glm() already knows</h2>
<p>A Poisson GLM with a log link says that each count is a Poisson draw whose mean is <code>exp(b0 + b1 * moisture + b2 * grazed)</code>. The likelihood of the whole data set is the product of the 80 Poisson probabilities, one per quadrat, and its log is their sum. <code>dpois(..., log = TRUE)</code> gives each log probability directly. <code>optim()</code> looks for a minimum, so the function returns the sum with a minus sign. The default search in <code>optim()</code> is Nelder-Mead, which only compares function values; <code>method = "BFGS"</code> also uses the slope of the function, and it is the usual choice for a smooth likelihood with a few parameters:</p>
<div class="cell">
<div class="code-copy-outer-scaffold"><div class="sourceCode cell-code" id="cb4" style="background: #f1f3f5;"><pre class="sourceCode r code-with-copy"><code class="sourceCode r"><span id="cb4-1">nll_pois <span class="ot" style="color: #003B4F;
background-color: null;
font-style: inherit;">&lt;-</span> <span class="cf" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">function</span>(par, dat) {</span>
<span id="cb4-2">  eta <span class="ot" style="color: #003B4F;
background-color: null;
font-style: inherit;">&lt;-</span> par[<span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">1</span>] <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">+</span> par[<span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">2</span>] <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">*</span> dat<span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">$</span>moisture <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">+</span> par[<span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">3</span>] <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">*</span> dat<span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">$</span>grazed</span>
<span id="cb4-3">  <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">-</span><span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">sum</span>(<span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">dpois</span>(dat<span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">$</span>count, <span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">lambda =</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">exp</span>(eta), <span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">log =</span> <span class="cn" style="color: #8f5902;
background-color: null;
font-style: inherit;">TRUE</span>))</span>
<span id="cb4-4">}</span>
<span id="cb4-5">fit_hand <span class="ot" style="color: #003B4F;
background-color: null;
font-style: inherit;">&lt;-</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">optim</span>(<span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">c</span>(<span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">0</span>, <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">0</span>, <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">0</span>), nll_pois, <span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">dat =</span> quads, <span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">method =</span> <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"BFGS"</span>, <span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">hessian =</span> <span class="cn" style="color: #8f5902;
background-color: null;
font-style: inherit;">TRUE</span>)</span>
<span id="cb4-6">fit_glm  <span class="ot" style="color: #003B4F;
background-color: null;
font-style: inherit;">&lt;-</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">glm</span>(count <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">~</span> moisture <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">+</span> grazed, <span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">family =</span> poisson, <span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">data =</span> quads)</span>
<span id="cb4-7"><span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">stopifnot</span>(fit_hand<span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">$</span>convergence <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">==</span> <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">0</span>)   <span class="co" style="color: #5E5E5E;
background-color: null;
font-style: inherit;"># check before trusting the Hessian</span></span>
<span id="cb4-8">se_hand <span class="ot" style="color: #003B4F;
background-color: null;
font-style: inherit;">&lt;-</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">sqrt</span>(<span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">diag</span>(<span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">solve</span>(fit_hand<span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">$</span>hessian)))</span>
<span id="cb4-9">compare <span class="ot" style="color: #003B4F;
background-color: null;
font-style: inherit;">&lt;-</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">data.frame</span>(<span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">optim =</span> fit_hand<span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">$</span>par, <span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">glm =</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">coef</span>(fit_glm),</span>
<span id="cb4-10">                      <span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">se_optim =</span> se_hand, <span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">se_glm =</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">sqrt</span>(<span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">diag</span>(<span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">vcov</span>(fit_glm))))</span>
<span id="cb4-11"><span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">round</span>(compare, <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">4</span>)</span></code></pre></div></div>
<div class="cell-output cell-output-stdout">
<pre><code>              optim     glm se_optim se_glm
(Intercept)  1.5894  1.5894   0.1030 0.1030
moisture     1.8729  1.8729   0.2569 0.2569
grazed      -0.5318 -0.5318   0.0860 0.0860</code></pre>
</div>
</div>
<p>Both columns agree to the four decimals printed, estimates and standard errors alike: the largest difference is <img src="https://latex.codecogs.com/png.latex?2.0%20%5Ctimes%2010%5E%7B-6%7D"> for an estimate and <img src="https://latex.codecogs.com/png.latex?1.4%20%5Ctimes%2010%5E%7B-6%7D"> for a standard error, the size of difference left by the stopping rule of the search and by the numerical second derivatives. The minimum value of the function, 191.4158, is minus the log-likelihood that <code>logLik(fit_glm)</code> reports. (If you prefer to maximise, <code>control = list(fnscale = -1)</code> makes <code>optim()</code> do that, and then the function returns the log-likelihood without the minus sign.)</p>
<p>The standard errors come from the Hessian, the matrix of second derivatives of the function at its minimum, which <code>optim()</code> estimates numerically when asked. A sharply curved minimum means the data pin the parameter down; a flat one means they do not. Inverting the Hessian of minus the log-likelihood gives the estimated covariance matrix of the parameters, and the square roots of its diagonal are the standard errors. <code>glm()</code> uses the expected curvature, averaged over the data the model could produce, instead of the curvature of this data set’s function, and for a Poisson model with a log link or a binomial model with a logit link the two are the same, which is why the columns match. With other links the two can differ, and families such as gaussian or Gamma add a dispersion parameter that <code>glm()</code> estimates by a route of its own, so run the comparison on one of those two models.</p>
<p>Moisture is stored as a fraction on purpose. With the same readings in per cent, the moisture coefficient is a hundred times smaller (0.0187 instead of 1.87), and the same <code>optim()</code> call stops 0.0010 away from the <code>glm()</code> intercept. That is harmless here, less than a hundredth of the intercept’s standard error of 0.103, but it is 473 times the largest gap left with moisture as a fraction. Why a parameter’s size changes what <code>optim()</code> finds, and what to do about it, is the subject of <a href="https://tidyecology.com/posts/parameter-scale-and-what-optim-finds/">Parameter scale decides what optim() finds</a>.</p>
</section>
<section id="the-product-that-turns-into-zero" class="level2">
<h2 id="the-product-that-turns-into-zero-h" class="anchored" data-anchor-id="the-product-that-turns-into-zero">The product that turns into zero</h2>
<p>The likelihood is a product, so it is tempting to write it as one and take the log at the end. On these data, from the same starting values, that version cannot even begin:</p>
<div class="cell">
<div class="code-copy-outer-scaffold"><div class="sourceCode cell-code" id="cb6" style="background: #f1f3f5;"><pre class="sourceCode r code-with-copy"><code class="sourceCode r"><span id="cb6-1">nll_prod <span class="ot" style="color: #003B4F;
background-color: null;
font-style: inherit;">&lt;-</span> <span class="cf" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">function</span>(par, dat) {</span>
<span id="cb6-2">  eta <span class="ot" style="color: #003B4F;
background-color: null;
font-style: inherit;">&lt;-</span> par[<span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">1</span>] <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">+</span> par[<span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">2</span>] <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">*</span> dat<span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">$</span>moisture <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">+</span> par[<span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">3</span>] <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">*</span> dat<span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">$</span>grazed</span>
<span id="cb6-3">  <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">-</span><span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">log</span>(<span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">prod</span>(<span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">dpois</span>(dat<span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">$</span>count, <span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">lambda =</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">exp</span>(eta))))</span>
<span id="cb6-4">}</span>
<span id="cb6-5"><span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">nll_prod</span>(<span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">c</span>(<span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">0</span>, <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">0</span>, <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">0</span>), quads)</span></code></pre></div></div>
<div class="cell-output cell-output-stdout">
<pre><code>[1] Inf</code></pre>
</div>
<div class="code-copy-outer-scaffold"><div class="sourceCode cell-code" id="cb8" style="background: #f1f3f5;"><pre class="sourceCode r code-with-copy"><code class="sourceCode r"><span id="cb8-1">fit_prod <span class="ot" style="color: #003B4F;
background-color: null;
font-style: inherit;">&lt;-</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">tryCatch</span>(<span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">optim</span>(<span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">c</span>(<span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">0</span>, <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">0</span>, <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">0</span>), nll_prod, <span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">dat =</span> quads, <span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">method =</span> <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"BFGS"</span>),</span>
<span id="cb8-2">                     <span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">error =</span> <span class="cf" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">function</span>(e) e)</span>
<span id="cb8-3"><span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">conditionMessage</span>(fit_prod)</span></code></pre></div></div>
<div class="cell-output cell-output-stdout">
<pre><code>[1] "initial value in 'vmmin' is not finite"</code></pre>
</div>
<div class="code-copy-outer-scaffold"><div class="sourceCode cell-code" id="cb10" style="background: #f1f3f5;"><pre class="sourceCode r code-with-copy"><code class="sourceCode r"><span id="cb10-1">running <span class="ot" style="color: #003B4F;
background-color: null;
font-style: inherit;">&lt;-</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">cumprod</span>(<span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">dpois</span>(quads<span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">$</span>count, <span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">lambda =</span> <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">1</span>))   <span class="co" style="color: #5E5E5E;
background-color: null;
font-style: inherit;"># the start: every mean is exp(0) = 1</span></span>
<span id="cb10-2">first_tiny <span class="ot" style="color: #003B4F;
background-color: null;
font-style: inherit;">&lt;-</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">which</span>(running <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">&lt;</span> .Machine<span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">$</span>double.xmin)[<span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">1</span>]</span>
<span id="cb10-3">first_zero <span class="ot" style="color: #003B4F;
background-color: null;
font-style: inherit;">&lt;-</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">which</span>(running <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">==</span> <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">0</span>)[<span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">1</span>]</span>
<span id="cb10-4"><span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">c</span>(<span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">below_double_xmin =</span> first_tiny, <span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">exactly_zero =</span> first_zero)</span></code></pre></div></div>
<div class="cell-output cell-output-stdout">
<pre><code>below_double_xmin      exactly_zero 
               55                60 </code></pre>
</div>
</div>
<p>At the start every quadrat is given a mean of one plant, so a quadrat with ten plants has a Poisson probability of <img src="https://latex.codecogs.com/png.latex?1.0%20%5Ctimes%2010%5E%7B-7%7D">, and the running product shrinks fast. R stores numbers as doubles. Below <code>.Machine$double.xmin</code>, which is <code>2^-1022</code> or <img src="https://latex.codecogs.com/png.latex?2.2%20%5Ctimes%2010%5E%7B-308%7D">, a double keeps fewer and fewer digits, and below <code>2^-1074</code> (<img src="https://latex.codecogs.com/png.latex?4.9%20%5Ctimes%2010%5E%7B-324%7D">) no positive number is left. Multiplying the probabilities in row order, the product passes the first of these lines at quadrat 55 and reaches exactly zero at quadrat 60. The log of zero is <code>-Inf</code>, minus that is <code>Inf</code>, and <code>optim()</code> stops with an error before its first step. The sum of logs has no such floor: <code>dpois(200, 1)</code> is zero in R, while <code>dpois(200, 1, log = TRUE)</code> is -864.2.</p>
<p>On these 80 quadrats a sensible start rescues it. With the log of the mean count as the intercept and zeros for the two slopes, the product version returns a finite 234.61 and BFGS reaches the <code>glm()</code> answer; at the maximum the product of the 80 probabilities is <img src="https://latex.codecogs.com/png.latex?7.4%20%5Ctimes%2010%5E%7B-84%7D">, far from the floor. For a larger survey, though, even the right answer underflows. Here is the same design with 1000 quadrats, with every probability computed at the TRUE parameter values:</p>
<div class="cell">
<div class="code-copy-outer-scaffold"><div class="sourceCode cell-code" id="cb12" style="background: #f1f3f5;"><pre class="sourceCode r code-with-copy"><code class="sourceCode r"><span id="cb12-1"><span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">set.seed</span>(<span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">1411</span>)</span>
<span id="cb12-2">big_moist  <span class="ot" style="color: #003B4F;
background-color: null;
font-style: inherit;">&lt;-</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">runif</span>(<span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">1000</span>, <span class="fl" style="color: #AD0000;
background-color: null;
font-style: inherit;">0.05</span>, <span class="fl" style="color: #AD0000;
background-color: null;
font-style: inherit;">0.60</span>)</span>
<span id="cb12-3">big_grazed <span class="ot" style="color: #003B4F;
background-color: null;
font-style: inherit;">&lt;-</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">rep</span>(<span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">c</span>(<span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">0</span>, <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">1</span>), <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">500</span>)</span>
<span id="cb12-4">big_lambda <span class="ot" style="color: #003B4F;
background-color: null;
font-style: inherit;">&lt;-</span> a_true <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">*</span> graze_ratio<span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">^</span>big_grazed <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">*</span> (<span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">1</span> <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">-</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">exp</span>(<span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">-</span>b_true <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">*</span> big_moist))</span>
<span id="cb12-5">big_count  <span class="ot" style="color: #003B4F;
background-color: null;
font-style: inherit;">&lt;-</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">rpois</span>(<span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">1000</span>, big_lambda)</span>
<span id="cb12-6">big_logp   <span class="ot" style="color: #003B4F;
background-color: null;
font-style: inherit;">&lt;-</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">dpois</span>(big_count, big_lambda, <span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">log =</span> <span class="cn" style="color: #8f5902;
background-color: null;
font-style: inherit;">TRUE</span>)</span>
<span id="cb12-7">big_zero   <span class="ot" style="color: #003B4F;
background-color: null;
font-style: inherit;">&lt;-</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">which</span>(<span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">cumprod</span>(<span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">dpois</span>(big_count, big_lambda)) <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">==</span> <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">0</span>)[<span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">1</span>]</span>
<span id="cb12-8">big_zero                        <span class="co" style="color: #5E5E5E;
background-color: null;
font-style: inherit;"># the product, in row order, is zero from here on</span></span></code></pre></div></div>
<div class="cell-output cell-output-stdout">
<pre><code>[1] 308</code></pre>
</div>
<div class="code-copy-outer-scaffold"><div class="sourceCode cell-code" id="cb14" style="background: #f1f3f5;"><pre class="sourceCode r code-with-copy"><code class="sourceCode r"><span id="cb14-1"><span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">sum</span>(big_logp)                   <span class="co" style="color: #5E5E5E;
background-color: null;
font-style: inherit;"># the sum of logs is an ordinary number</span></span></code></pre></div></div>
<div class="cell-output cell-output-stdout">
<pre><code>[1] -2420.459</code></pre>
</div>
<div class="code-copy-outer-scaffold"><div class="sourceCode cell-code" id="cb16" style="background: #f1f3f5;"><pre class="sourceCode r code-with-copy"><code class="sourceCode r"><span id="cb16-1"><span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">log</span>(<span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">2</span><span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">^-</span><span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">1074</span>) <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">/</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">mean</span>(big_logp)   <span class="co" style="color: #5E5E5E;
background-color: null;
font-style: inherit;"># how many average quadrats reach the floor</span></span></code></pre></div></div>
<div class="cell-output cell-output-stdout">
<pre><code>[1] 307.5615</code></pre>
</div>
</div>
<p>With the true values plugged in, the product is zero from quadrat 308 onwards, while the sum of logs, -2420.5, is an ordinary number. The quadrat where it happens follows from two numbers. The log of the smallest positive double is <code>log(2^-1074)</code>, or -744.4, and at the true values an average quadrat adds -2.42 to the log-likelihood, so the product runs out after about 744.4 / 2.42 = 308 quadrats. A survey of that size is not unusual, and the product version then has nothing to work with even at the right answer. Use the sum.</p>
</section>
<section id="a-curve-glm-cannot-fit" class="level2">
<h2 id="a-curve-glm-cannot-fit-h" class="anchored" data-anchor-id="a-curve-glm-cannot-fit">A curve glm() cannot fit</h2>
<p>The log-linear GLM makes the mean grow exponentially with moisture, without limit. The simulated meadow does something else: the count is low in dry soil, rises as the soil gets wetter, and above some moisture it levels off. A curve with those three properties is <code>lambda = a * exp(g * grazed) * (1 - exp(-b * moisture))</code>, where <code>a</code> is the ungrazed asymptote, <code>b</code> is how quickly the count approaches it, and <code>exp(g)</code> is the grazed asymptote as a share of the ungrazed one. The rate <code>b</code> sits inside an exponential inside the mean, and no link function turns this mean into coefficients times columns of data, which is the form every <code>glm()</code> needs. For <code>optim()</code> it is only a different line inside the function.</p>
<p><code>a</code> and <code>b</code> must be positive. Instead of constraining the search, the function takes their logs and exponentiates them, so any real number is a legal value:</p>
<div class="cell">
<div class="code-copy-outer-scaffold"><div class="sourceCode cell-code" id="cb18" style="background: #f1f3f5;"><pre class="sourceCode r code-with-copy"><code class="sourceCode r"><span id="cb18-1">nll_sat <span class="ot" style="color: #003B4F;
background-color: null;
font-style: inherit;">&lt;-</span> <span class="cf" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">function</span>(par, dat) {</span>
<span id="cb18-2">  a <span class="ot" style="color: #003B4F;
background-color: null;
font-style: inherit;">&lt;-</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">exp</span>(par[<span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">1</span>]); b <span class="ot" style="color: #003B4F;
background-color: null;
font-style: inherit;">&lt;-</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">exp</span>(par[<span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">2</span>]); g <span class="ot" style="color: #003B4F;
background-color: null;
font-style: inherit;">&lt;-</span> par[<span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">3</span>]</span>
<span id="cb18-3">  lambda <span class="ot" style="color: #003B4F;
background-color: null;
font-style: inherit;">&lt;-</span> a <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">*</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">exp</span>(g <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">*</span> dat<span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">$</span>grazed) <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">*</span> (<span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">1</span> <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">-</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">exp</span>(<span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">-</span>b <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">*</span> dat<span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">$</span>moisture))</span>
<span id="cb18-4">  <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">-</span><span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">sum</span>(<span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">dpois</span>(dat<span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">$</span>count, lambda, <span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">log =</span> <span class="cn" style="color: #8f5902;
background-color: null;
font-style: inherit;">TRUE</span>))</span>
<span id="cb18-5">}</span>
<span id="cb18-6">init_sat <span class="ot" style="color: #003B4F;
background-color: null;
font-style: inherit;">&lt;-</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">c</span>(<span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">log</span>(<span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">10</span>), <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">log</span>(<span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">5</span>), <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">0</span>)     <span class="co" style="color: #5E5E5E;
background-color: null;
font-style: inherit;"># read off the scatter: level near 10, most of the rise done by 0.3</span></span>
<span id="cb18-7">fit_sat  <span class="ot" style="color: #003B4F;
background-color: null;
font-style: inherit;">&lt;-</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">optim</span>(init_sat, nll_sat, <span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">dat =</span> quads, <span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">method =</span> <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"BFGS"</span>, <span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">hessian =</span> <span class="cn" style="color: #8f5902;
background-color: null;
font-style: inherit;">TRUE</span>)</span>
<span id="cb18-8"><span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">stopifnot</span>(fit_sat<span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">$</span>convergence <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">==</span> <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">0</span>)    <span class="co" style="color: #5E5E5E;
background-color: null;
font-style: inherit;"># zero is necessary, not sufficient (see the checks at the end)</span></span>
<span id="cb18-9">se_sat   <span class="ot" style="color: #003B4F;
background-color: null;
font-style: inherit;">&lt;-</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">sqrt</span>(<span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">diag</span>(<span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">solve</span>(fit_sat<span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">$</span>hessian)))</span>
<span id="cb18-10">z95 <span class="ot" style="color: #003B4F;
background-color: null;
font-style: inherit;">&lt;-</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">qnorm</span>(<span class="fl" style="color: #AD0000;
background-color: null;
font-style: inherit;">0.975</span>)</span>
<span id="cb18-11">sat_table <span class="ot" style="color: #003B4F;
background-color: null;
font-style: inherit;">&lt;-</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">data.frame</span>(<span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">estimate =</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">exp</span>(fit_sat<span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">$</span>par),</span>
<span id="cb18-12">                        <span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">lower =</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">exp</span>(fit_sat<span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">$</span>par <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">-</span> z95 <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">*</span> se_sat),</span>
<span id="cb18-13">                        <span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">upper =</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">exp</span>(fit_sat<span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">$</span>par <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">+</span> z95 <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">*</span> se_sat),</span>
<span id="cb18-14">                        <span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">row.names =</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">c</span>(<span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"a (ungrazed asymptote)"</span>, <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"b (rate)"</span>, <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"exp(g) (grazed share)"</span>))</span>
<span id="cb18-15"><span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">round</span>(sat_table, <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">3</span>)</span></code></pre></div></div>
<div class="cell-output cell-output-stdout">
<pre><code>                       estimate  lower  upper
a (ungrazed asymptote)   13.656 10.931 17.060
b (rate)                  4.381  2.846  6.744
exp(g) (grazed share)     0.588  0.497  0.696</code></pre>
</div>
</div>
<p>Each interval is built on the scale where the search ran and then its two endpoints are exponentiated. The asymptote comes out at 13.66 plants per quadrat with an interval from 10.93 to 17.06, which reaches further above the estimate than below it, as an interval built on the log scale does. Grazed quadrats level off at 0.59 of the ungrazed asymptote (interval 0.50 to 0.70). The standard error 0.114 belongs to log <code>a</code>; it is not a standard error of <code>a</code> in plants, and an interval of 13.66 plus or minus 1.96 times it would be 0.45 plants wide instead of 6.13. A second start far from the first, at a = 20, b = 1 and g = -1, reaches the same minimum; <a href="https://tidyecology.com/posts/starting-values-and-identifiability/">Starting values and identifiability in nls</a> covers choosing starts, and the case where no start can pin a parameter down.</p>
<div class="cell">
<div class="cell-output-display">
<div id="fig-fits" class="quarto-float quarto-figure quarto-figure-center anchored" alt="Scatter plot of 80 quadrats, marsh marigold count from 0 to 18 against soil moisture from 0.05 to 0.60, green points for ungrazed and red points for grazed quadrats, the red points mostly lower. For each group a dashed log-linear GLM line rises steadily to about 15 plants (ungrazed) and 9 plants (grazed) at moisture 0.6, and a solid saturating curve rises steeply at low moisture and then flattens, ending near 12.7 and 7.5 plants.">
<figure class="quarto-float quarto-float-fig figure">
<div aria-describedby="fig-fits-caption-0ceaefa1-69ba-4598-a22c-09a6ac19f8ca">
<img src="https://tidyecology.com/posts/maximum-likelihood-with-optim/index_files/figure-html/fig-fits-1.png" class="img-fluid figure-img" alt="Scatter plot of 80 quadrats, marsh marigold count from 0 to 18 against soil moisture from 0.05 to 0.60, green points for ungrazed and red points for grazed quadrats, the red points mostly lower. For each group a dashed log-linear GLM line rises steadily to about 15 plants (ungrazed) and 9 plants (grazed) at moisture 0.6, and a solid saturating curve rises steeply at low moisture and then flattens, ending near 12.7 and 7.5 plants." width="720">
</div>
<figcaption class="quarto-float-caption-bottom quarto-float-caption quarto-float-fig" id="fig-fits-caption-0ceaefa1-69ba-4598-a22c-09a6ac19f8ca">
Figure&nbsp;1: The 80 simulated quadrats with two fitted models. Dashed lines: the log-linear Poisson GLM, fitted by hand and by glm(). Solid lines: the saturating curve, fitted by hand with optim(). Colour marks grazing.
</figcaption>
</figure>
</div>
</div>
</div>
</section>
<section id="nested-models-likelihood-ratio-and-aic" class="level2">
<h2 id="nested-models-likelihood-ratio-and-aic-h" class="anchored" data-anchor-id="nested-models-likelihood-ratio-and-aic">Nested models: likelihood ratio and AIC</h2>
<p>Does grazing lower the asymptote? Fix <code>g</code> at zero, fit again, and compare. The two fits are nested (the smaller one is the larger one with a parameter held at a value inside its range), so twice the difference in their log-likelihoods has, in large samples, a chi-squared distribution with one degree of freedom when grazing does nothing (Wilks 1938). The minimum values from <code>optim()</code> are all the test needs:</p>
<div class="cell">
<div class="code-copy-outer-scaffold"><div class="sourceCode cell-code" id="cb20" style="background: #f1f3f5;"><pre class="sourceCode r code-with-copy"><code class="sourceCode r"><span id="cb20-1">nll_sat_nograze <span class="ot" style="color: #003B4F;
background-color: null;
font-style: inherit;">&lt;-</span> <span class="cf" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">function</span>(par, dat) <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">nll_sat</span>(<span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">c</span>(par, <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">0</span>), dat)</span>
<span id="cb20-2">fit_nograze <span class="ot" style="color: #003B4F;
background-color: null;
font-style: inherit;">&lt;-</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">optim</span>(fit_sat<span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">$</span>par[<span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">1</span><span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">:</span><span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">2</span>], nll_sat_nograze, <span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">dat =</span> quads, <span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">method =</span> <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"BFGS"</span>)</span>
<span id="cb20-3">lr_stat <span class="ot" style="color: #003B4F;
background-color: null;
font-style: inherit;">&lt;-</span> <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">2</span> <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">*</span> (fit_nograze<span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">$</span>value <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">-</span> fit_sat<span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">$</span>value)</span>
<span id="cb20-4"><span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">round</span>(<span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">c</span>(<span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">LR =</span> lr_stat, <span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">critical_95 =</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">qchisq</span>(<span class="fl" style="color: #AD0000;
background-color: null;
font-style: inherit;">0.95</span>, <span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">df =</span> <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">1</span>)), <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">2</span>)</span></code></pre></div></div>
<div class="cell-output cell-output-stdout">
<pre><code>         LR critical_95 
      39.40        3.84 </code></pre>
</div>
<div class="code-copy-outer-scaffold"><div class="sourceCode cell-code" id="cb22" style="background: #f1f3f5;"><pre class="sourceCode r code-with-copy"><code class="sourceCode r"><span id="cb22-1"><span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">formatC</span>(<span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">pchisq</span>(lr_stat, <span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">df =</span> <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">1</span>, <span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">lower.tail =</span> <span class="cn" style="color: #8f5902;
background-color: null;
font-style: inherit;">FALSE</span>), <span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">format =</span> <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"e"</span>, <span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">digits =</span> <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">1</span>)   <span class="co" style="color: #5E5E5E;
background-color: null;
font-style: inherit;"># p-value</span></span></code></pre></div></div>
<div class="cell-output cell-output-stdout">
<pre><code>[1] "3.5e-10"</code></pre>
</div>
</div>
<p>AIC comes from the same numbers: twice the minimum plus twice the number of parameters. It also compares the saturating curve with the log-linear GLM, which the likelihood ratio test cannot do, because neither of those two models is a special case of the other. The comparison is fair because both functions use the full Poisson density, constants included:</p>
<div class="cell">
<div class="code-copy-outer-scaffold"><div class="sourceCode cell-code" id="cb24" style="background: #f1f3f5;"><pre class="sourceCode r code-with-copy"><code class="sourceCode r"><span id="cb24-1">aic_tab <span class="ot" style="color: #003B4F;
background-color: null;
font-style: inherit;">&lt;-</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">c</span>(<span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">loglinear_glm      =</span> <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">2</span> <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">*</span> fit_hand<span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">$</span>value <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">+</span> <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">2</span> <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">*</span> <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">3</span>,</span>
<span id="cb24-2">             <span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">saturating_nograze =</span> <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">2</span> <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">*</span> fit_nograze<span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">$</span>value <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">+</span> <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">2</span> <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">*</span> <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">2</span>,</span>
<span id="cb24-3">             <span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">saturating_grazed  =</span> <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">2</span> <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">*</span> fit_sat<span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">$</span>value <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">+</span> <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">2</span> <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">*</span> <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">3</span>)</span>
<span id="cb24-4"><span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">round</span>(aic_tab <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">-</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">min</span>(aic_tab), <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">2</span>)</span></code></pre></div></div>
<div class="cell-output cell-output-stdout">
<pre><code>     loglinear_glm saturating_nograze  saturating_grazed 
             17.17              37.40               0.00 </code></pre>
</div>
</div>
<p>The likelihood ratio statistic is 39.4 against a 95 per cent critical value of 3.84 (p = <img src="https://latex.codecogs.com/png.latex?3.5%20%5Ctimes%2010%5E%7B-10%7D">), so the grazing term stays. The hand-computed AIC of the log-linear model equals <code>AIC(fit_glm)</code>, 388.83, and the saturating curve with grazing is lower by 17.2. What an AIC difference of that size means, and when to average over models instead of choosing one, is in <a href="https://tidyecology.com/posts/model-selection-aic/">Model selection with AIC in R for ecology</a>.</p>
</section>
<section id="profile-likelihood-next-to-the-wald-interval" class="level2">
<h2 id="profile-likelihood-next-to-the-wald-interval-h" class="anchored" data-anchor-id="profile-likelihood-next-to-the-wald-interval">Profile likelihood next to the Wald interval</h2>
<p>The intervals above are Wald intervals: estimate plus or minus 1.96 standard errors, on the log scale. They treat minus the log-likelihood as a parabola around its minimum, with the curvature measured at the bottom. A profile likelihood interval uses the function itself instead. Fix <code>b</code> at a value, let <code>optim()</code> find the best <code>a</code> and <code>g</code> for it, and record the minimum; repeat along a grid of <code>b</code>. Twice the rise of that profile above the overall minimum is the likelihood ratio statistic of the previous section for that value of <code>b</code>, so it is compared with <code>qchisq(0.95, 1)</code>, and the interval is the set of <code>b</code> values below that cut (Venzon and Moolgavkar 1988):</p>
<div class="cell">
<div class="code-copy-outer-scaffold"><div class="sourceCode cell-code" id="cb26" style="background: #f1f3f5;"><pre class="sourceCode r code-with-copy"><code class="sourceCode r"><span id="cb26-1">profile_b <span class="ot" style="color: #003B4F;
background-color: null;
font-style: inherit;">&lt;-</span> <span class="cf" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">function</span>(log_b, dat, init) {</span>
<span id="cb26-2">  inner <span class="ot" style="color: #003B4F;
background-color: null;
font-style: inherit;">&lt;-</span> <span class="cf" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">function</span>(p) <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">nll_sat</span>(<span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">c</span>(p[<span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">1</span>], log_b, p[<span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">2</span>]), dat)   <span class="co" style="color: #5E5E5E;
background-color: null;
font-style: inherit;"># p = (log a, g)</span></span>
<span id="cb26-3">  <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">optim</span>(init, inner, <span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">method =</span> <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"BFGS"</span>)<span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">$</span>value</span>
<span id="cb26-4">}</span>
<span id="cb26-5">grid_lb <span class="ot" style="color: #003B4F;
background-color: null;
font-style: inherit;">&lt;-</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">seq</span>(<span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">log</span>(<span class="fl" style="color: #AD0000;
background-color: null;
font-style: inherit;">0.05</span>), <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">log</span>(<span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">60</span>), <span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">length.out =</span> <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">500</span>)   <span class="co" style="color: #5E5E5E;
background-color: null;
font-style: inherit;"># b from 0.05 to 60, even steps on the log scale</span></span>
<span id="cb26-6">cut_95  <span class="ot" style="color: #003B4F;
background-color: null;
font-style: inherit;">&lt;-</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">qchisq</span>(<span class="fl" style="color: #AD0000;
background-color: null;
font-style: inherit;">0.95</span>, <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">1</span>)</span>
<span id="cb26-7">wald_b  <span class="ot" style="color: #003B4F;
background-color: null;
font-style: inherit;">&lt;-</span> <span class="cf" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">function</span>(fit) <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">exp</span>(fit<span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">$</span>par[<span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">2</span>] <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">+</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">c</span>(<span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">-</span><span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">1</span>, <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">1</span>) <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">*</span> z95 <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">*</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">sqrt</span>(<span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">diag</span>(<span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">solve</span>(fit<span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">$</span>hessian)))[<span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">2</span>])</span>
<span id="cb26-8"></span>
<span id="cb26-9">dev_all <span class="ot" style="color: #003B4F;
background-color: null;
font-style: inherit;">&lt;-</span> <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">2</span> <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">*</span> (<span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">sapply</span>(grid_lb, profile_b, <span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">dat =</span> quads, <span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">init =</span> fit_sat<span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">$</span>par[<span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">c</span>(<span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">1</span>, <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">3</span>)]) <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">-</span> fit_sat<span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">$</span>value)</span>
<span id="cb26-10">small <span class="ot" style="color: #003B4F;
background-color: null;
font-style: inherit;">&lt;-</span> quads[<span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">c</span>(<span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">1</span><span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">:</span><span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">12</span>, <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">41</span><span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">:</span><span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">52</span>), ]      <span class="co" style="color: #5E5E5E;
background-color: null;
font-style: inherit;"># 24 quadrats: the first 12 of each group</span></span>
<span id="cb26-11">fit_small <span class="ot" style="color: #003B4F;
background-color: null;
font-style: inherit;">&lt;-</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">optim</span>(init_sat, nll_sat, <span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">dat =</span> small, <span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">method =</span> <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"BFGS"</span>, <span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">hessian =</span> <span class="cn" style="color: #8f5902;
background-color: null;
font-style: inherit;">TRUE</span>)</span>
<span id="cb26-12"><span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">stopifnot</span>(fit_small<span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">$</span>convergence <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">==</span> <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">0</span>)</span>
<span id="cb26-13">dev_small <span class="ot" style="color: #003B4F;
background-color: null;
font-style: inherit;">&lt;-</span> <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">2</span> <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">*</span> (<span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">sapply</span>(grid_lb, profile_b, <span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">dat =</span> small, <span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">init =</span> fit_small<span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">$</span>par[<span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">c</span>(<span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">1</span>, <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">3</span>)]) <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">-</span> fit_small<span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">$</span>value)</span>
<span id="cb26-14"></span>
<span id="cb26-15">ci_tab <span class="ot" style="color: #003B4F;
background-color: null;
font-style: inherit;">&lt;-</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">rbind</span>(<span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">profile_80 =</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">range</span>(<span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">exp</span>(grid_lb[dev_all <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">&lt;</span> cut_95])),   <span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">wald_80 =</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">wald_b</span>(fit_sat),</span>
<span id="cb26-16">                <span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">profile_24 =</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">range</span>(<span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">exp</span>(grid_lb[dev_small <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">&lt;</span> cut_95])), <span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">wald_24 =</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">wald_b</span>(fit_small))</span>
<span id="cb26-17"><span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">colnames</span>(ci_tab) <span class="ot" style="color: #003B4F;
background-color: null;
font-style: inherit;">&lt;-</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">c</span>(<span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"lower"</span>, <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"upper"</span>)</span>
<span id="cb26-18"><span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">round</span>(ci_tab, <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">2</span>)</span></code></pre></div></div>
<div class="cell-output cell-output-stdout">
<pre><code>           lower upper
profile_80  2.71  6.54
wald_80     2.85  6.74
profile_24  0.05  7.33
wald_24     0.80  9.46</code></pre>
</div>
</div>
<p><code>range()</code> takes the smallest and the largest <code>b</code> on the grid whose profile lies below the cut, so the ends are only as fine as the grid: neighbouring grid points are 1.4 per cent apart. It also assumes a single valley, which the figure below shows. When an end of the interval lands on the first or last point of the grid, the grid was too narrow on that side: widen it and look again. If the end stays on the edge however far you widen, the interval has no end on that side.</p>
<p>With all 80 quadrats the two intervals for <code>b</code> are close: the profile runs from 2.71 to 6.54 and the Wald interval from 2.85 to 6.74. With 24 quadrats they are not. The estimate is 2.75 and the Wald interval is 0.80 to 9.46. The profile interval ends at 7.33 on the right, but its lower end in the table, 0.05, is the first point of the grid, not an end of the interval. As <code>b</code> shrinks, the best <code>a</code> grows so that <code>a * b</code> settles at a fixed value, and the curve becomes a straight line through the origin in each group. For that straight line, twice the rise in minus the log-likelihood is 3.67, below the cut of 3.84, so the profile never reaches the cut on that side and the interval has no lower end above zero. The 24 quadrats cannot rule out that the count never levels off in this moisture range, and only the profile says so.</p>
<div class="cell">
<div class="cell-output-display">
<div id="fig-profile" class="quarto-float quarto-figure quarto-figure-center anchored" alt="Two panels showing twice the rise in minus the log-likelihood against the rate b on a log axis from 0.05 to 60, with a dotted gold line at 3.84. Left panel, all 80 quadrats: the solid green profile and the dashed red Wald parabola almost coincide in a narrow valley with its bottom near b = 4.4, crossing the line between 2.7 and 2.9 and between 6.6 and 6.7. Right panel, 24 quadrats (12 per group): a wider valley with its bottom near b = 2.8; the dashed parabola crosses the line near 0.8 and 9.5, while the solid profile crosses it only on the right, near 7.4, and on the left rises slowly towards the line without reaching it, at about 3.5 when b is 0.05.">
<figure class="quarto-float quarto-float-fig figure">
<div aria-describedby="fig-profile-caption-0ceaefa1-69ba-4598-a22c-09a6ac19f8ca">
<img src="https://tidyecology.com/posts/maximum-likelihood-with-optim/index_files/figure-html/fig-profile-1.png" class="img-fluid figure-img" alt="Two panels showing twice the rise in minus the log-likelihood against the rate b on a log axis from 0.05 to 60, with a dotted gold line at 3.84. Left panel, all 80 quadrats: the solid green profile and the dashed red Wald parabola almost coincide in a narrow valley with its bottom near b = 4.4, crossing the line between 2.7 and 2.9 and between 6.6 and 6.7. Right panel, 24 quadrats (12 per group): a wider valley with its bottom near b = 2.8; the dashed parabola crosses the line near 0.8 and 9.5, while the solid profile crosses it only on the right, near 7.4, and on the left rises slowly towards the line without reaching it, at about 3.5 when b is 0.05." width="720">
</div>
<figcaption class="quarto-float-caption-bottom quarto-float-caption quarto-float-fig" id="fig-profile-caption-0ceaefa1-69ba-4598-a22c-09a6ac19f8ca">
Figure&nbsp;2: Profile likelihood for the rate b, as twice the rise above the minimum, for all 80 quadrats and for 24 of them (the first 12 of each group). Solid: the profile. Dashed: the parabola that the Wald interval assumes on the log scale. The dotted line is the 95 per cent cut; each interval is where its curve lies below it.
</figcaption>
</figure>
</div>
</div>
</div>
<p>The profile costs one <code>optim()</code> call per grid point, which is cheap for three parameters. For other ways of putting an interval on a derived quantity (the delta method, Fieller’s interval) see <a href="https://tidyecology.com/posts/confidence-intervals-for-effective-doses/">Confidence intervals for effective doses</a>; for what a confidence interval promises in the first place, <a href="https://tidyecology.com/posts/standard-errors-confidence-intervals/">Standard errors and confidence intervals in R</a>.</p>
</section>
<section id="what-to-check-in-your-own-data" class="level2">
<h2 id="what-to-check-in-your-own-data-h" class="anchored" data-anchor-id="what-to-check-in-your-own-data">What to check in your own data</h2>
<p>Before you trust a hand-written likelihood, run the same code on a model <code>glm()</code> can fit, and compare estimates, <code>logLik()</code> and, for a Poisson log-link or binomial logit-link model, the standard errors. If they disagree, the bug is in your function, not in the new model.</p>
<p>Evaluate the function at your starting values before calling <code>optim()</code>. It must return a finite number. If it returns <code>Inf</code> or <code>NaN</code>, look for a product of densities, a <code>log()</code> of something that can be zero, or a parameter that has left its allowed range.</p>
<p>Look at <code>fit$convergence</code> (zero means the search stopped normally, not that it found the right answer) and run it again from a clearly different start. Two starts that end at the same minimum value are the cheapest check you have.</p>
<p>Report intervals for positive or bounded parameters by transforming the endpoints of an interval built on the search scale. When the sample is small or an estimate sits near a limit of its range, compute a profile interval for the parameter you care about and report it if it disagrees with the Wald interval.</p>
</section>
<section id="honest-limits" class="level2">
<h2 id="honest-limits-h" class="anchored" data-anchor-id="honest-limits">Honest limits</h2>
<p>The demonstration assumes the counts are Poisson, which the simulation makes true; with real quadrat counts, check for overdispersion before trusting any of the standard errors above. The Hessian here is a finite-difference estimate, and its standard errors agreed with <code>glm()</code> to within <img src="https://latex.codecogs.com/png.latex?1.4%20%5Ctimes%2010%5E%7B-6%7D"> in this example; for badly scaled or nearly flat problems it can be much worse, or not invertible at all. The chi-squared reference for the likelihood ratio test needs the null value to sit inside the parameter range: testing whether a variance is zero, or whether a mixture needs a second component, puts it on the edge, and the test then needs a different reference distribution. The comparison of profile and Wald intervals uses one simulated data set and 24 of its quadrats (the first 12 of each group); it shows that the two can disagree, not how often either one covers the true value, which would need a simulation of its own.</p>
</section>
<section id="references" class="level2">
<h2 id="references-h" class="anchored" data-anchor-id="references">References</h2>
<p>Bolker BM 2008 Ecological Models and Data in R (ISBN 978-0-691-12522-0)</p>
<p>R Core Team 2024 R documentation: General-purpose optimization, optim (https://stat.ethz.ch/R-manual/R-devel/library/stats/html/optim.html)</p>
<p>Venzon DJ, Moolgavkar SH 1988 Applied Statistics 37(1):87-94 (<a href="https://doi.org/10.2307/2347496">10.2307/2347496</a>)</p>
<p>Wilks SS 1938 The Annals of Mathematical Statistics 9(1):60-62 (<a href="https://doi.org/10.1214/aoms/1177732360">10.1214/aoms/1177732360</a>)</p>
</section>
<section id="related-tutorials" class="level2">
<h2 id="related-tutorials-h" class="anchored" data-anchor-id="related-tutorials">Related tutorials</h2>
<ul>
<li><a href="https://tidyecology.com/posts/single-season-occupancy-model/">Fitting single-season occupancy models in R</a></li>
<li><a href="https://tidyecology.com/posts/parameter-scale-and-what-optim-finds/">Parameter scale decides what optim() finds</a></li>
<li><a href="https://tidyecology.com/posts/the-delta-method/">The delta method: standard errors for derived values</a></li>
<li><a href="https://tidyecology.com/posts/starting-values-and-identifiability/">Starting values and identifiability in nls</a></li>
</ul>
<details class="te-repro" data-pagefind-ignore="">
<summary>Reproducibility</summary>
<ul>
<li>Code last run: 2026-09-30</li>
<li>R version 4.5.3 (2026-03-11), aarch64-apple-darwin20</li>
<li>Packages: ggplot2 4.0.3</li>
</ul>
</details>


<!-- -->

</section>

 ]]></description>
  <category>R</category>
  <category>maximum likelihood</category>
  <category>GLM</category>
  <category>nonlinear regression</category>
  <category>count data</category>
  <category>statistics</category>
  <category>ecology tutorial</category>
  <guid isPermaLink="false">https://tidyecology.com/posts/maximum-likelihood-with-optim/</guid>
  <pubDate>Mon, 28 Sep 2026 07:00:00 GMT</pubDate>
  <media:content url="https://tidyecology.com/posts/maximum-likelihood-with-optim/thumbnail.png" medium="image" type="image/png" height="104" width="144"/>
</item>
<item>
  <title>What a p-value tells you, and what it does not</title>
  <dc:creator>Tidy Ecology</dc:creator>
  <link>https://tidyecology.com/posts/what-a-p-value-tells-you/</link>
  <description><![CDATA[ 





<p>Twelve fenced plots and twelve grazed plots on an upland pasture, and after one season the height of the tallest rowan seedling in each plot. The fenced plots grew taller seedlings on average, and <code>t.test()</code> returns p = 0.03. The question that follows is almost always the same: does that mean the effect is real, and would I find it again if I ran the experiment a second time?</p>
<p>Many posts on this site report p-values, usually in passing. This post explains what one is, on that single grazing experiment. It computes the p-value twice, once with <code>t.test()</code> and once by counting simulated experiments, then measures what happens when the same experiment is repeated with the same true effect and new plots. The answer to the second question turns out to be much less reassuring than p = 0.03 sounds.</p>
<p><strong>The short answer.</strong> A p-value is the probability, calculated on the assumption that there is no effect at all, of getting a test statistic at least as extreme as the one you observed. It is not the probability that the effect is real, and one minus p is not the chance that a repeat would be significant. That chance is the power of the design at the true effect, which depends on the true effect and the sample size, and your p-value cannot tell you the true effect. Power worked out from the effect you happened to observe is a different number, a function of p alone. Report the estimate and its confidence interval next to the p-value, because the interval shows the uncertainty that a single p-value hides.</p>
<p>All data here are simulated, and every seed is in the code.</p>
<div class="cell">
<div class="code-copy-outer-scaffold"><div class="sourceCode cell-code" id="cb1" style="background: #f1f3f5;"><pre class="sourceCode r code-with-copy"><code class="sourceCode r"><span id="cb1-1"><span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">library</span>(ggplot2)</span>
<span id="cb1-2"></span>
<span id="cb1-3">te_paper  <span class="ot" style="color: #003B4F;
background-color: null;
font-style: inherit;">&lt;-</span> <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"#f5f4ee"</span></span>
<span id="cb1-4">te_ink    <span class="ot" style="color: #003B4F;
background-color: null;
font-style: inherit;">&lt;-</span> <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"#16241d"</span></span>
<span id="cb1-5">te_body   <span class="ot" style="color: #003B4F;
background-color: null;
font-style: inherit;">&lt;-</span> <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"#2c3a31"</span></span>
<span id="cb1-6">te_forest <span class="ot" style="color: #003B4F;
background-color: null;
font-style: inherit;">&lt;-</span> <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"#275139"</span></span>
<span id="cb1-7">te_rust   <span class="ot" style="color: #003B4F;
background-color: null;
font-style: inherit;">&lt;-</span> <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"#b5534e"</span></span>
<span id="cb1-8">te_gold   <span class="ot" style="color: #003B4F;
background-color: null;
font-style: inherit;">&lt;-</span> <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"#c9b458"</span></span>
<span id="cb1-9">te_line   <span class="ot" style="color: #003B4F;
background-color: null;
font-style: inherit;">&lt;-</span> <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"#dad9ca"</span></span>
<span id="cb1-10"></span>
<span id="cb1-11">theme_datasheet <span class="ot" style="color: #003B4F;
background-color: null;
font-style: inherit;">&lt;-</span> <span class="cf" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">function</span>() {</span>
<span id="cb1-12">  <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">theme_minimal</span>(<span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">base_size =</span> <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">12</span>) <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">+</span></span>
<span id="cb1-13">    <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">theme</span>(<span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">plot.background  =</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">element_rect</span>(<span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">fill =</span> te_paper, <span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">colour =</span> <span class="cn" style="color: #8f5902;
background-color: null;
font-style: inherit;">NA</span>),</span>
<span id="cb1-14">          <span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">panel.background =</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">element_rect</span>(<span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">fill =</span> te_paper, <span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">colour =</span> <span class="cn" style="color: #8f5902;
background-color: null;
font-style: inherit;">NA</span>),</span>
<span id="cb1-15">          <span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">panel.grid.major =</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">element_line</span>(<span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">colour =</span> te_line, <span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">linewidth =</span> <span class="fl" style="color: #AD0000;
background-color: null;
font-style: inherit;">0.3</span>),</span>
<span id="cb1-16">          <span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">panel.grid.minor =</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">element_blank</span>(),</span>
<span id="cb1-17">          <span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">text             =</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">element_text</span>(<span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">colour =</span> te_body),</span>
<span id="cb1-18">          <span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">axis.text        =</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">element_text</span>(<span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">colour =</span> te_body),</span>
<span id="cb1-19">          <span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">strip.text       =</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">element_text</span>(<span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">colour =</span> te_ink, <span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">face =</span> <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"bold"</span>))</span>
<span id="cb1-20">}</span></code></pre></div></div>
</div>
<section id="one-experiment-one-p-value" class="level2">
<h2 id="one-experiment-one-p-value-h" class="anchored" data-anchor-id="one-experiment-one-p-value">One experiment, one p-value</h2>
<p>The simulated pasture has a real grazing effect: seedlings in fenced plots are 3.5 cm taller on average, and plots vary around their treatment mean with a standard deviation of 4 cm. These values, with twelve plots per treatment, were fixed before anything was run, chosen so that the design detects the effect about half the time. Your own experiment is one draw from a process like this, and in the question it came out between 0.01 and 0.05, so the chunk below draws experiments until one does and keeps that one.</p>
<div class="cell">
<div class="code-copy-outer-scaffold"><div class="sourceCode cell-code" id="cb2" style="background: #f1f3f5;"><pre class="sourceCode r code-with-copy"><code class="sourceCode r"><span id="cb2-1">n_plots     <span class="ot" style="color: #003B4F;
background-color: null;
font-style: inherit;">&lt;-</span> <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">12</span>     <span class="co" style="color: #5E5E5E;
background-color: null;
font-style: inherit;"># plots per treatment</span></span>
<span id="cb2-2">sd_height   <span class="ot" style="color: #003B4F;
background-color: null;
font-style: inherit;">&lt;-</span> <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">4</span>      <span class="co" style="color: #5E5E5E;
background-color: null;
font-style: inherit;"># cm, plot-to-plot standard deviation</span></span>
<span id="cb2-3">true_diff   <span class="ot" style="color: #003B4F;
background-color: null;
font-style: inherit;">&lt;-</span> <span class="fl" style="color: #AD0000;
background-color: null;
font-style: inherit;">3.5</span>    <span class="co" style="color: #5E5E5E;
background-color: null;
font-style: inherit;"># cm, fenced minus grazed: the true effect in the simulation</span></span>
<span id="cb2-4">grazed_mean <span class="ot" style="color: #003B4F;
background-color: null;
font-style: inherit;">&lt;-</span> <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">20</span>     <span class="co" style="color: #5E5E5E;
background-color: null;
font-style: inherit;"># cm</span></span>
<span id="cb2-5"></span>
<span id="cb2-6"><span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">set.seed</span>(<span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">1015</span>)</span>
<span id="cb2-7"><span class="cf" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">repeat</span> {</span>
<span id="cb2-8">  grazed <span class="ot" style="color: #003B4F;
background-color: null;
font-style: inherit;">&lt;-</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">rnorm</span>(n_plots, grazed_mean, sd_height)</span>
<span id="cb2-9">  fenced <span class="ot" style="color: #003B4F;
background-color: null;
font-style: inherit;">&lt;-</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">rnorm</span>(n_plots, grazed_mean <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">+</span> true_diff, sd_height)</span>
<span id="cb2-10">  p_try  <span class="ot" style="color: #003B4F;
background-color: null;
font-style: inherit;">&lt;-</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">t.test</span>(fenced, grazed)<span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">$</span>p.value</span>
<span id="cb2-11">  <span class="cf" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">if</span> (p_try <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">&gt;</span> <span class="fl" style="color: #AD0000;
background-color: null;
font-style: inherit;">0.01</span> <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">&amp;&amp;</span> p_try <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">&lt;</span> <span class="fl" style="color: #AD0000;
background-color: null;
font-style: inherit;">0.05</span>) <span class="cf" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">break</span></span>
<span id="cb2-12">}</span>
<span id="cb2-13">test_obs <span class="ot" style="color: #003B4F;
background-color: null;
font-style: inherit;">&lt;-</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">t.test</span>(fenced, grazed)</span>
<span id="cb2-14">test_obs</span></code></pre></div></div>
<div class="cell-output cell-output-stdout">
<pre><code>
    Welch Two Sample t-test

data:  fenced and grazed
t = 2.1875, df = 21.416, p-value = 0.03993
alternative hypothesis: true difference in means is not equal to 0
95 percent confidence interval:
 0.2301139 8.8936858
sample estimates:
mean of x mean of y 
 23.66038  19.09848 </code></pre>
</div>
</div>
<div class="cell">
<details class="code-fold">
<summary>Run this first: the numbers quoted in the text, and objects later chunks use</summary>
<div class="code-copy-outer-scaffold"><div class="sourceCode cell-code" id="cb4" style="background: #f1f3f5;"><pre class="sourceCode r code-with-copy"><code class="sourceCode r"><span id="cb4-1">p_obs    <span class="ot" style="color: #003B4F;
background-color: null;
font-style: inherit;">&lt;-</span> test_obs<span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">$</span>p.value</span>
<span id="cb4-2">t_obs    <span class="ot" style="color: #003B4F;
background-color: null;
font-style: inherit;">&lt;-</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">unname</span>(test_obs<span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">$</span>statistic)</span>
<span id="cb4-3">diff_obs <span class="ot" style="color: #003B4F;
background-color: null;
font-style: inherit;">&lt;-</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">mean</span>(fenced) <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">-</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">mean</span>(grazed)</span>
<span id="cb4-4">ci_obs   <span class="ot" style="color: #003B4F;
background-color: null;
font-style: inherit;">&lt;-</span> test_obs<span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">$</span>conf.int</span>
<span id="cb4-5"><span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">stopifnot</span>(p_obs <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">&gt;</span> <span class="fl" style="color: #AD0000;
background-color: null;
font-style: inherit;">0.01</span>, p_obs <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">&lt;</span> <span class="fl" style="color: #AD0000;
background-color: null;
font-style: inherit;">0.05</span>)</span>
<span id="cb4-6"><span class="co" style="color: #5E5E5E;
background-color: null;
font-style: inherit;"># the default of t.test() is the Welch test: var.equal = FALSE, conf.level = 0.95</span></span>
<span id="cb4-7"><span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">stopifnot</span>(<span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">isFALSE</span>(<span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">formals</span>(<span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">getS3method</span>(<span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"t.test"</span>, <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"default"</span>))<span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">$</span>var.equal),</span>
<span id="cb4-8">          <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">identical</span>(<span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">formals</span>(<span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">getS3method</span>(<span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"t.test"</span>, <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"default"</span>))<span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">$</span>conf.level, <span class="fl" style="color: #AD0000;
background-color: null;
font-style: inherit;">0.95</span>),</span>
<span id="cb4-9">          <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">grepl</span>(<span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"Welch"</span>, test_obs<span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">$</span>method))</span></code></pre></div></div>
</details>
</div>
<p>The fenced plots are 4.56 cm taller on average, the t statistic is 2.19 and the p-value is 0.040, inside the window of the question if not exactly 0.03; nothing below depends on that difference. The header of the output says “Welch Two Sample t-test”: by default <code>t.test()</code> has <code>var.equal = FALSE</code>, so it does not assume the two groups share one variance. <a href="https://tidyecology.com/posts/pretesting-assumptions-distorts-the-test/">Pretesting variances before a t test</a> explains why that default is the safer one to keep.</p>
</section>
<section id="what-the-p-value-counts" class="level2">
<h2 id="what-the-p-value-counts-h" class="anchored" data-anchor-id="what-the-p-value-counts">What the p-value counts</h2>
<p>The definition has two parts that matter. The probability is computed assuming there is no effect, and it covers results “at least as extreme” as yours, not results exactly like yours. Both parts can be checked by brute force. Build a world in which grazing does nothing: both groups come from the same distribution. Run the experiment in that world a hundred thousand times, compute the t statistic each time, and count how often it is at least as far from zero as the observed 2.19:</p>
<div class="cell">
<div class="code-copy-outer-scaffold"><div class="sourceCode cell-code" id="cb5" style="background: #f1f3f5;"><pre class="sourceCode r code-with-copy"><code class="sourceCode r"><span id="cb5-1">n_null <span class="ot" style="color: #003B4F;
background-color: null;
font-style: inherit;">&lt;-</span> <span class="fl" style="color: #AD0000;
background-color: null;
font-style: inherit;">1e5</span></span>
<span id="cb5-2">pooled_sd <span class="ot" style="color: #003B4F;
background-color: null;
font-style: inherit;">&lt;-</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">sqrt</span>((<span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">var</span>(fenced) <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">+</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">var</span>(grazed)) <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">/</span> <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">2</span>)</span>
<span id="cb5-3"></span>
<span id="cb5-4"><span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">set.seed</span>(<span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">2015</span>)</span>
<span id="cb5-5">null_runs <span class="ot" style="color: #003B4F;
background-color: null;
font-style: inherit;">&lt;-</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">replicate</span>(n_null, {</span>
<span id="cb5-6">  a <span class="ot" style="color: #003B4F;
background-color: null;
font-style: inherit;">&lt;-</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">rnorm</span>(n_plots, grazed_mean, pooled_sd)    <span class="co" style="color: #5E5E5E;
background-color: null;
font-style: inherit;"># fenced plots, no effect</span></span>
<span id="cb5-7">  b <span class="ot" style="color: #003B4F;
background-color: null;
font-style: inherit;">&lt;-</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">rnorm</span>(n_plots, grazed_mean, pooled_sd)    <span class="co" style="color: #5E5E5E;
background-color: null;
font-style: inherit;"># grazed plots</span></span>
<span id="cb5-8">  tt <span class="ot" style="color: #003B4F;
background-color: null;
font-style: inherit;">&lt;-</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">t.test</span>(a, b)</span>
<span id="cb5-9">  <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">c</span>(<span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">t =</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">unname</span>(tt<span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">$</span>statistic), <span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">p =</span> tt<span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">$</span>p.value)</span>
<span id="cb5-10">})</span>
<span id="cb5-11">p_counted <span class="ot" style="color: #003B4F;
background-color: null;
font-style: inherit;">&lt;-</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">mean</span>(<span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">abs</span>(null_runs[<span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"t"</span>, ]) <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">&gt;=</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">abs</span>(t_obs))</span>
<span id="cb5-12">mc_se_p   <span class="ot" style="color: #003B4F;
background-color: null;
font-style: inherit;">&lt;-</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">sqrt</span>(p_counted <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">*</span> (<span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">1</span> <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">-</span> p_counted) <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">/</span> n_null)</span>
<span id="cb5-13"><span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">round</span>(<span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">c</span>(<span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">t_test =</span> p_obs, <span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">counted =</span> p_counted, <span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">mc_se =</span> mc_se_p), <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">4</span>)</span></code></pre></div></div>
<div class="cell-output cell-output-stdout">
<pre><code> t_test counted   mc_se 
 0.0399  0.0386  0.0006 </code></pre>
</div>
</div>
<div class="cell">
<details class="code-fold">
<summary>Run this first: the numbers quoted in the text, and objects later chunks use</summary>
<div class="code-copy-outer-scaffold"><div class="sourceCode cell-code" id="cb7" style="background: #f1f3f5;"><pre class="sourceCode r code-with-copy"><code class="sourceCode r"><span id="cb7-1">null_below <span class="ot" style="color: #003B4F;
background-color: null;
font-style: inherit;">&lt;-</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">mean</span>(null_runs[<span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"p"</span>, ] <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">&lt;</span> <span class="fl" style="color: #AD0000;
background-color: null;
font-style: inherit;">0.05</span>)</span>
<span id="cb7-2">null_mcse  <span class="ot" style="color: #003B4F;
background-color: null;
font-style: inherit;">&lt;-</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">sqrt</span>(null_below <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">*</span> (<span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">1</span> <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">-</span> null_below) <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">/</span> n_null)</span>
<span id="cb7-3"><span class="co" style="color: #5E5E5E;
background-color: null;
font-style: inherit;"># with equal group sizes the Welch statistic equals the pooled t statistic,</span></span>
<span id="cb7-4"><span class="co" style="color: #5E5E5E;
background-color: null;
font-style: inherit;"># whose exact null distribution (equal variances) is t on 2n - 2 df</span></span>
<span id="cb7-5">t_pooled <span class="ot" style="color: #003B4F;
background-color: null;
font-style: inherit;">&lt;-</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">unname</span>(<span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">t.test</span>(fenced, grazed, <span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">var.equal =</span> <span class="cn" style="color: #8f5902;
background-color: null;
font-style: inherit;">TRUE</span>)<span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">$</span>statistic)</span>
<span id="cb7-6"><span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">stopifnot</span>(<span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">isTRUE</span>(<span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">all.equal</span>(t_obs, t_pooled)))</span>
<span id="cb7-7">df_exact <span class="ot" style="color: #003B4F;
background-color: null;
font-style: inherit;">&lt;-</span> <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">2</span> <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">*</span> n_plots <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">-</span> <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">2</span></span>
<span id="cb7-8">df_welch <span class="ot" style="color: #003B4F;
background-color: null;
font-style: inherit;">&lt;-</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">unname</span>(test_obs<span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">$</span>parameter)</span>
<span id="cb7-9">p_exact  <span class="ot" style="color: #003B4F;
background-color: null;
font-style: inherit;">&lt;-</span> <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">2</span> <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">*</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">pt</span>(<span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">-</span><span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">abs</span>(t_obs), <span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">df =</span> df_exact)</span>
<span id="cb7-10"><span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">stopifnot</span>(df_welch <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">&lt;</span> df_exact, p_exact <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">&lt;</span> p_obs)</span>
<span id="cb7-11">z_exact  <span class="ot" style="color: #003B4F;
background-color: null;
font-style: inherit;">&lt;-</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">abs</span>(p_counted <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">-</span> p_exact) <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">/</span> mc_se_p</span>
<span id="cb7-12">z_gap    <span class="ot" style="color: #003B4F;
background-color: null;
font-style: inherit;">&lt;-</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">abs</span>(p_counted <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">-</span> p_obs) <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">/</span> mc_se_p</span>
<span id="cb7-13">pooled_below <span class="ot" style="color: #003B4F;
background-color: null;
font-style: inherit;">&lt;-</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">mean</span>(<span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">2</span> <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">*</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">pt</span>(<span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">-</span><span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">abs</span>(null_runs[<span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"t"</span>, ]), <span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">df =</span> df_exact) <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">&lt;</span> <span class="fl" style="color: #AD0000;
background-color: null;
font-style: inherit;">0.05</span>)</span>
<span id="cb7-14">pooled_mcse  <span class="ot" style="color: #003B4F;
background-color: null;
font-style: inherit;">&lt;-</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">sqrt</span>(pooled_below <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">*</span> (<span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">1</span> <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">-</span> pooled_below) <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">/</span> n_null)</span></code></pre></div></div>
</details>
</div>
<p>In 3.86 per cent of the no-effect experiments the statistic was at least as extreme as ours, against 3.99 per cent from <code>t.test()</code>. That is the definition at work: the p-value is a share of experiments in a world without an effect. The mean and standard deviation of that world do not matter, because the t statistic does not change when all heights are shifted or rescaled; what matters is that the two groups are identical. <code>t.test()</code> reads the share from a t distribution instead of counting, and <a href="https://tidyecology.com/posts/probability-distributions-in-r/">Probability distributions in R: d, p, q and r</a> explains the p functions such as <code>pnorm()</code>; <code>pt()</code>, which <code>t.test()</code> uses, is the same for the t distribution.</p>
<p>The two numbers differ by 0.13 percentage points, 2.2 Monte Carlo standard errors (one standard error, the typical size of the simulation noise, is 0.06 points here). Most of that is simulation noise, and a small part has a reason. With the same number of plots in both groups, the Welch statistic is exactly the ordinary pooled t statistic, and when both groups share one variance, as in the simulated world, its exact distribution is the t distribution with 22 degrees of freedom. The Welch test uses 21.4 here, a little fewer, so its p-value is a little larger than the exact 3.96 per cent. The counted share is 1.7 standard errors from that exact value.</p>
<p>The same hundred thousand null experiments show the property that everything else rests on. An exact p-value is spread evenly between zero and one when there is no effect, so p &lt; 0.05 happens one time in twenty. Read from the exact t distribution, 4.91 per cent of the null experiments give p below 0.05 (Monte Carlo standard error 0.07); with the Welch p-values the share is 4.80 per cent, slightly lower for the reason just given. <a href="https://tidyecology.com/posts/checking-a-multiple-testing-analysis/">Checking a multiple-testing analysis</a> shows the flat histogram this produces and what it looks like when it goes wrong.</p>
</section>
<section id="would-a-repeat-find-it-again" class="level2">
<h2 id="would-a-repeat-find-it-again-h" class="anchored" data-anchor-id="would-a-repeat-find-it-again">Would a repeat find it again?</h2>
<p>Now the second half of the question. Take the same pasture, the same true effect of 3.5 cm, the same twelve plots per treatment, and run the experiment many times. Each run is paired with an exact replicate: same design, same truth, new plots.</p>
<div class="cell">
<div class="code-copy-outer-scaffold"><div class="sourceCode cell-code" id="cb8" style="background: #f1f3f5;"><pre class="sourceCode r code-with-copy"><code class="sourceCode r"><span id="cb8-1">n_rep <span class="ot" style="color: #003B4F;
background-color: null;
font-style: inherit;">&lt;-</span> <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">30000</span></span>
<span id="cb8-2">one_run <span class="ot" style="color: #003B4F;
background-color: null;
font-style: inherit;">&lt;-</span> <span class="cf" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">function</span>() {</span>
<span id="cb8-3">  <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">t.test</span>(<span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">rnorm</span>(n_plots, grazed_mean <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">+</span> true_diff, sd_height),</span>
<span id="cb8-4">         <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">rnorm</span>(n_plots, grazed_mean, sd_height))<span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">$</span>p.value</span>
<span id="cb8-5">}</span>
<span id="cb8-6"><span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">set.seed</span>(<span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">3015</span>)</span>
<span id="cb8-7">p_original  <span class="ot" style="color: #003B4F;
background-color: null;
font-style: inherit;">&lt;-</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">replicate</span>(n_rep, <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">one_run</span>())</span>
<span id="cb8-8">p_replicate <span class="ot" style="color: #003B4F;
background-color: null;
font-style: inherit;">&lt;-</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">replicate</span>(n_rep, <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">one_run</span>())</span>
<span id="cb8-9"></span>
<span id="cb8-10">power_sim <span class="ot" style="color: #003B4F;
background-color: null;
font-style: inherit;">&lt;-</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">mean</span>(p_original <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">&lt;</span> <span class="fl" style="color: #AD0000;
background-color: null;
font-style: inherit;">0.05</span>)</span>
<span id="cb8-11">power_se  <span class="ot" style="color: #003B4F;
background-color: null;
font-style: inherit;">&lt;-</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">sqrt</span>(power_sim <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">*</span> (<span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">1</span> <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">-</span> power_sim) <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">/</span> n_rep)</span>
<span id="cb8-12"><span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">round</span>(<span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">c</span>(<span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">power =</span> power_sim, <span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">mc_se =</span> power_se,</span>
<span id="cb8-13">        <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">quantile</span>(p_original, <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">c</span>(<span class="fl" style="color: #AD0000;
background-color: null;
font-style: inherit;">0.10</span>, <span class="fl" style="color: #AD0000;
background-color: null;
font-style: inherit;">0.50</span>, <span class="fl" style="color: #AD0000;
background-color: null;
font-style: inherit;">0.90</span>))), <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">4</span>)</span></code></pre></div></div>
<div class="cell-output cell-output-stdout">
<pre><code> power  mc_se    10%    50%    90% 
0.5324 0.0029 0.0016 0.0420 0.3917 </code></pre>
</div>
</div>
<p>At the true effect of 3.5 cm this design has power 0.532 (Monte Carlo standard error 0.003): a run of the experiment gives p &lt; 0.05 about half the time. (<code>power.t.test()</code>, which uses the pooled rather than the Welch test, gives 0.536.) Across runs of the same experiment the p-value moves over a very wide range. The middle run has p = 0.042; one run in ten has p below 0.0016, and one in ten has p above 0.39. Nothing changed between those runs except which plots were drawn. Cumming (2008) shows how wide this spread is across replications, and Halsey and colleagues (2015) make the same point for experimental biology.</p>
<div class="cell">
<div class="cell-output-display">
<div id="fig-p-spread" class="quarto-float quarto-figure quarto-figure-center anchored" alt="Histogram of 30000 p-values on a log scale running from 0.000001 to 1. Bars left of a dashed black line at 0.05 are dark green and bars to its right are pale grey. The counts rise from almost nothing near 0.00001 to about 1300 just below 0.05, peak at about 1400 near 0.1 and fall to about 700 at 1. Two gold vertical lines are labelled 10th percentile 0.0016 and 90th percentile 0.39.">
<figure class="quarto-float quarto-float-fig figure">
<div aria-describedby="fig-p-spread-caption-0ceaefa1-69ba-4598-a22c-09a6ac19f8ca">
<img src="https://tidyecology.com/posts/what-a-p-value-tells-you/index_files/figure-html/fig-p-spread-1.png" class="img-fluid figure-img" alt="Histogram of 30000 p-values on a log scale running from 0.000001 to 1. Bars left of a dashed black line at 0.05 are dark green and bars to its right are pale grey. The counts rise from almost nothing near 0.00001 to about 1300 just below 0.05, peak at about 1400 near 0.1 and fall to about 700 at 1. Two gold vertical lines are labelled 10th percentile 0.0016 and 90th percentile 0.39." width="720">
</div>
<figcaption class="quarto-float-caption-bottom quarto-float-caption quarto-float-fig" id="fig-p-spread-caption-0ceaefa1-69ba-4598-a22c-09a6ac19f8ca">
Figure&nbsp;1: The p-value from 30000 exact runs of the same simulated grazing experiment (true difference 3.5 cm, 12 plots per treatment), on a log scale. Every run has the same true effect; the spread comes from which plots were drawn. Runs left of the dashed line at 0.05 are significant.
</figcaption>
</figure>
</div>
</div>
</div>
<p>That spread already answers the question, but the question is conditional: my experiment gave p between 0.01 and 0.05, so what are the chances for the repeat? Keep only the original runs that landed in that window, as yours did, and look at their replicates:</p>
<div class="cell">
<div class="code-copy-outer-scaffold"><div class="sourceCode cell-code" id="cb10" style="background: #f1f3f5;"><pre class="sourceCode r code-with-copy"><code class="sourceCode r"><span id="cb10-1">in_window <span class="ot" style="color: #003B4F;
background-color: null;
font-style: inherit;">&lt;-</span> p_original <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">&gt;</span> <span class="fl" style="color: #AD0000;
background-color: null;
font-style: inherit;">0.01</span> <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">&amp;</span> p_original <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">&lt;</span> <span class="fl" style="color: #AD0000;
background-color: null;
font-style: inherit;">0.05</span></span>
<span id="cb10-2">rep_share <span class="ot" style="color: #003B4F;
background-color: null;
font-style: inherit;">&lt;-</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">mean</span>(p_replicate[in_window] <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">&lt;</span> <span class="fl" style="color: #AD0000;
background-color: null;
font-style: inherit;">0.05</span>)</span>
<span id="cb10-3">rep_se    <span class="ot" style="color: #003B4F;
background-color: null;
font-style: inherit;">&lt;-</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">sqrt</span>(rep_share <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">*</span> (<span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">1</span> <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">-</span> rep_share) <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">/</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">sum</span>(in_window))</span>
<span id="cb10-4"><span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">round</span>(<span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">c</span>(<span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">runs_in_window =</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">sum</span>(in_window), <span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">replicate_significant =</span> rep_share,</span>
<span id="cb10-5">        <span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">mc_se =</span> rep_se, <span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">power =</span> power_sim), <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">4</span>)</span></code></pre></div></div>
<div class="cell-output cell-output-stdout">
<pre><code>       runs_in_window replicate_significant                 mc_se 
            7889.0000                0.5350                0.0056 
                power 
               0.5324 </code></pre>
</div>
<div class="code-copy-outer-scaffold"><div class="sourceCode cell-code" id="cb12" style="background: #f1f3f5;"><pre class="sourceCode r code-with-copy"><code class="sourceCode r"><span id="cb12-1"><span class="co" style="color: #5E5E5E;
background-color: null;
font-style: inherit;"># the same share after other original results</span></span>
<span id="cb12-2">by_original <span class="ot" style="color: #003B4F;
background-color: null;
font-style: inherit;">&lt;-</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">cut</span>(p_original, <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">c</span>(<span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">0</span>, <span class="fl" style="color: #AD0000;
background-color: null;
font-style: inherit;">0.001</span>, <span class="fl" style="color: #AD0000;
background-color: null;
font-style: inherit;">0.01</span>, <span class="fl" style="color: #AD0000;
background-color: null;
font-style: inherit;">0.05</span>, <span class="fl" style="color: #AD0000;
background-color: null;
font-style: inherit;">0.2</span>, <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">1</span>))</span>
<span id="cb12-3"><span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">round</span>(<span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">tapply</span>(p_replicate <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">&lt;</span> <span class="fl" style="color: #AD0000;
background-color: null;
font-style: inherit;">0.05</span>, by_original, mean), <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">3</span>)</span></code></pre></div></div>
<div class="cell-output cell-output-stdout">
<pre><code>   (0,0.001] (0.001,0.01]  (0.01,0.05]   (0.05,0.2]      (0.2,1] 
       0.552        0.540        0.535        0.527        0.525 </code></pre>
</div>
</div>
<p>Of the 7889 original runs with p between 0.01 and 0.05, 0.535 had a significant replicate (Monte Carlo standard error 0.006), next to the power at the true effect of 0.532. The second table shows that the share hardly depends on the original p: whether the original run gave p below 0.001 or above 0.2, the share of significant replicates stays between 0.525 and 0.552, and every group is within 1.8 Monte Carlo standard errors of the power (counting the error of both shares). This is not a coincidence of the simulation. The replicate uses new plots, so it is independent of the original run once the true effect is fixed, and its chance of p &lt; 0.05 is the power of the design at the true effect, whatever the original p was. The simulation only confirms it.</p>
<p>So the honest answer to “would I find it again?” is: with the probability given by the power at the true effect, which the p-value of your experiment does not tell you. Here it is close to a coin flip, while the reading “p = 0.040, so a repeat is almost certain” would put it near one minus p, 0.96.</p>
<p>A published calculation is often quoted at this point, and it answers a different question. Goodman (1992) assumed that the true effect equals the one you observed, used a z-test, and found that a result at exactly p = 0.05 is followed by a significant replicate half of the time: <code>pnorm(qnorm(0.975) - qnorm(0.975))</code> is 0.5. At p = 0.03 the same formula gives 0.58, and at our p of 0.040 it gives 0.54. Even that optimistic assumption leaves the chance far from one minus p.&nbsp;But Goodman’s number is the power at the observed effect, which is what <a href="https://tidyecology.com/posts/observed-power-tells-you-nothing/">Observed power tells you nothing</a> calls observed power: a function of p alone. The simulated share is the power at the true effect, which p does not reveal. Apply Goodman’s formula to every original run and compare it with what the replicates did:</p>
<div class="cell">
<div class="code-copy-outer-scaffold"><div class="sourceCode cell-code" id="cb14" style="background: #f1f3f5;"><pre class="sourceCode r code-with-copy"><code class="sourceCode r"><span id="cb14-1"><span class="co" style="color: #5E5E5E;
background-color: null;
font-style: inherit;"># Goodman's replication probability for each original run: the power at its observed effect</span></span>
<span id="cb14-2">goodman_run <span class="ot" style="color: #003B4F;
background-color: null;
font-style: inherit;">&lt;-</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">pnorm</span>(<span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">qnorm</span>(<span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">1</span> <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">-</span> p_original <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">/</span> <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">2</span>) <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">-</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">qnorm</span>(<span class="fl" style="color: #AD0000;
background-color: null;
font-style: inherit;">0.975</span>))</span>
<span id="cb14-3"><span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">round</span>(<span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">rbind</span>(<span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">goodman    =</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">tapply</span>(goodman_run, by_original, mean),</span>
<span id="cb14-4">            <span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">replicates =</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">tapply</span>(p_replicate <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">&lt;</span> <span class="fl" style="color: #AD0000;
background-color: null;
font-style: inherit;">0.05</span>, by_original, mean)), <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">3</span>)</span></code></pre></div></div>
<div class="cell-output cell-output-stdout">
<pre><code>           (0,0.001] (0.001,0.01] (0.01,0.05] (0.05,0.2] (0.2,1]
goodman        0.949        0.817       0.617      0.377   0.136
replicates     0.552        0.540       0.535      0.527   0.525</code></pre>
</div>
</div>
<p>After an original p below 0.001, Goodman’s formula averages 0.95, but only 0.552 of those replicates reached significance; in the window of the question it averages 0.62 against a measured 0.535, and after p above 0.2 it averages 0.14 against 0.525. Goodman’s number follows the original p; the replicates follow the power at the true effect. The two land close together for our experiment only because its p is near 0.05 and the power at the true effect happens to be near one half.</p>
</section>
<section id="what-a-p-value-is-not" class="level2">
<h2 id="what-a-p-value-is-not-h" class="anchored" data-anchor-id="what-a-p-value-is-not">What a p-value is not</h2>
<p>Three misreadings follow from the definition; the last two have fuller treatments elsewhere on this site, so here each gets one paragraph.</p>
<p>A p-value is not the probability that there is no effect. It is the probability of data at least this extreme if there is no effect: a statement about the data, not about the hypothesis. p = 0.040 does not mean a 4 per cent chance that grazing does nothing; the second principle of the American Statistical Association statement on p-values (Wasserstein and Lazar 2016) says this in one line. How far apart the two probabilities are depends on how often the effects you test for are real; the section after this one prices that for this design.</p>
<p>A p-value is not the size of the effect. A tiny difference measured on thousands of plots gives a tiny p-value, and in a small study the runs that reach significance overestimate the effect; <a href="https://tidyecology.com/posts/power-analysis-by-simulation/">Power analysis by simulation in R</a> measures that exaggeration.</p>
<p>A p-value above 0.05 is not evidence that there is no effect. In this design 47 per cent of runs miss a real 3.5 cm difference. <a href="https://tidyecology.com/posts/observed-power-tells-you-nothing/">Observed power tells you nothing</a> explains why a power figure computed afterwards cannot repair that, and <a href="https://tidyecology.com/posts/testing-for-no-effect/">Testing for no effect: equivalence tests in R</a> gives the test that can support “no effect worth caring about”.</p>
</section>
<section id="how-often-is-there-no-effect-behind-it" class="level2">
<h2 id="how-often-is-there-no-effect-behind-it-h" class="anchored" data-anchor-id="how-often-is-there-no-effect-behind-it">How often is there no effect behind it?</h2>
<p>The first misreading can be turned into a number, but only with one ingredient that no experiment supplies: how often the effects you test for are real. Picture many experiments like this one on many pastures. In a share of them, call it the prior, fencing really adds 3.5 cm; in the rest grazing does nothing. Among the experiments that end with p between 0.01 and 0.05, as yours did, what share had no effect behind them? The post already holds both kinds of run: the hundred thousand no-effect experiments of the null simulation and the 30000 runs at the true effect.</p>
<div class="cell">
<div class="code-copy-outer-scaffold"><div class="sourceCode cell-code" id="cb16" style="background: #f1f3f5;"><pre class="sourceCode r code-with-copy"><code class="sourceCode r"><span id="cb16-1">window_null <span class="ot" style="color: #003B4F;
background-color: null;
font-style: inherit;">&lt;-</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">mean</span>(null_runs[<span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"p"</span>, ] <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">&gt;</span> <span class="fl" style="color: #AD0000;
background-color: null;
font-style: inherit;">0.01</span> <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">&amp;</span> null_runs[<span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"p"</span>, ] <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">&lt;</span> <span class="fl" style="color: #AD0000;
background-color: null;
font-style: inherit;">0.05</span>)   <span class="co" style="color: #5E5E5E;
background-color: null;
font-style: inherit;"># no effect, p in the window</span></span>
<span id="cb16-2">window_true <span class="ot" style="color: #003B4F;
background-color: null;
font-style: inherit;">&lt;-</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">mean</span>(p_original <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">&gt;</span> <span class="fl" style="color: #AD0000;
background-color: null;
font-style: inherit;">0.01</span> <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">&amp;</span> p_original <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">&lt;</span> <span class="fl" style="color: #AD0000;
background-color: null;
font-style: inherit;">0.05</span>)               <span class="co" style="color: #5E5E5E;
background-color: null;
font-style: inherit;"># true effect, p in the window</span></span>
<span id="cb16-3"><span class="co" style="color: #5E5E5E;
background-color: null;
font-style: inherit;"># among results of one kind, the share that came from a true null</span></span>
<span id="cb16-4">false_share <span class="ot" style="color: #003B4F;
background-color: null;
font-style: inherit;">&lt;-</span> <span class="cf" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">function</span>(prior, from_null, from_true) {</span>
<span id="cb16-5">  (<span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">1</span> <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">-</span> prior) <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">*</span> from_null <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">/</span> ((<span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">1</span> <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">-</span> prior) <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">*</span> from_null <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">+</span> prior <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">*</span> from_true)</span>
<span id="cb16-6">}</span>
<span id="cb16-7">priors <span class="ot" style="color: #003B4F;
background-color: null;
font-style: inherit;">&lt;-</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">c</span>(<span class="fl" style="color: #AD0000;
background-color: null;
font-style: inherit;">0.10</span>, <span class="fl" style="color: #AD0000;
background-color: null;
font-style: inherit;">0.25</span>, <span class="fl" style="color: #AD0000;
background-color: null;
font-style: inherit;">0.50</span>)</span>
<span id="cb16-8">fpr_table <span class="ot" style="color: #003B4F;
background-color: null;
font-style: inherit;">&lt;-</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">rbind</span>(<span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">window   =</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">false_share</span>(priors, window_null, window_true),</span>
<span id="cb16-9">                   <span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">below_05 =</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">false_share</span>(priors, null_below, power_sim))</span>
<span id="cb16-10"><span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">colnames</span>(fpr_table) <span class="ot" style="color: #003B4F;
background-color: null;
font-style: inherit;">&lt;-</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">sprintf</span>(<span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"prior %.2f"</span>, priors)</span>
<span id="cb16-11"><span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">round</span>(fpr_table, <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">3</span>)</span></code></pre></div></div>
<div class="cell-output cell-output-stdout">
<pre><code>         prior 0.10 prior 0.25 prior 0.50
window        0.569      0.306      0.128
below_05      0.448      0.213      0.083</code></pre>
</div>
</div>
<p>If one tested effect in ten of this kind is real, 57 per cent of the results in the window come from experiments in which grazing did nothing, and 45 per cent of all results with p &lt; 0.05 do (Monte Carlo standard errors 0.5 and 0.4 points). At one in four the shares are 31 and 21 per cent, at even odds 13 and 8 per cent. The window share falls to five per cent only at a prior of 0.74. The window is worse than p &lt; 0.05 because it leaves out the very small p-values, which the real effect often produces and a null rarely does: a run at the true effect is 6.8 times as likely as a null run to land in the window, but 11.1 times as likely to land below 0.05.</p>
<p>None of this needs the simulation. An exact p-value is uniform under the null, so a null run lands in the window with probability 0.04 and below 0.05 with probability 0.05. At the true effect the pooled t statistic follows a noncentral t distribution with 22 degrees of freedom and noncentrality 2.14, and the chance that it falls in the matching band is 0.259 for the window and 0.536 for p &lt; 0.05, the power that <code>power.t.test(strict = TRUE)</code> returns. The simulated curves in the figure reproduce these closed forms and sit a little below them, partly because the Welch test is slightly conservative and partly by chance: 3.86 per cent of the null runs landed in the window instead of 4, and the same runs read from the exact t distribution give 3.93 per cent. With the Welch share in the formula, the six simulated values in the table are within 1.7 Monte Carlo standard errors of the closed form. The window also pools p-values near 0.01 with p-values near 0.05. In the same closed form, a p-value right at 0.040 is only 4.5 times as likely at the true effect as with no effect, against 6.5 for the window as a whole, so for a result exactly like yours the share from true nulls is higher: 67, 40 and 18 per cent at the three priors.</p>
<div class="cell">
<div class="cell-output-display">
<div id="fig-false-positive-risk" class="quarto-float quarto-figure quarto-figure-center anchored" alt="Line chart with the prior share of real effects from 0 to 1 on the x axis and the share of results from a true null from 0 to 1 on the y axis. Two pairs of falling curves, one pair dark green for p between 0.01 and 0.05 and one pair red for p below 0.05, each pair a solid simulated line with a dashed closed-form line almost on top of it. At a prior of 0.01 the green pair starts near 0.94 and the red pair near 0.90. The green curves lie above the red ones at every prior; at a prior of 0.1 the green curve is near 0.57 and the red near 0.45, and at 0.5 they are near 0.13 and 0.08. A dotted black line marks 0.05, which the green curve reaches at a prior near 0.74.">
<figure class="quarto-float quarto-float-fig figure">
<div aria-describedby="fig-false-positive-risk-caption-0ceaefa1-69ba-4598-a22c-09a6ac19f8ca">
<img src="https://tidyecology.com/posts/what-a-p-value-tells-you/index_files/figure-html/fig-false-positive-risk-1.png" class="img-fluid figure-img" alt="Line chart with the prior share of real effects from 0 to 1 on the x axis and the share of results from a true null from 0 to 1 on the y axis. Two pairs of falling curves, one pair dark green for p between 0.01 and 0.05 and one pair red for p below 0.05, each pair a solid simulated line with a dashed closed-form line almost on top of it. At a prior of 0.01 the green pair starts near 0.94 and the red pair near 0.90. The green curves lie above the red ones at every prior; at a prior of 0.1 the green curve is near 0.57 and the red near 0.45, and at 0.5 they are near 0.13 and 0.08. A dotted black line marks 0.05, which the green curve reaches at a prior near 0.74." width="720">
</div>
<figcaption class="quarto-float-caption-bottom quarto-float-caption quarto-float-fig" id="fig-false-positive-risk-caption-0ceaefa1-69ba-4598-a22c-09a6ac19f8ca">
Figure&nbsp;2: Share of results that come from a true null, against the prior share of tested effects that are real, in the simulated grazing design (12 plots per treatment, true difference 3.5 cm). Solid lines use the simulated p-values, dashed lines the closed forms; the dotted line marks five per cent.
</figcaption>
</figure>
</div>
</div>
</div>
<p>This share is not the false discovery rate of <a href="https://tidyecology.com/posts/false-discovery-rate-benjamini-hochberg/">The false discovery rate and Benjamini-Hochberg</a>, which is the expected share of false rejections among many tests and is held down by a correction; it is the same kind of ratio for one uncorrected test, with the prior supplied from outside. In a screen of many tests the prior is one minus the proportion of true nulls, which <a href="https://tidyecology.com/posts/checking-a-multiple-testing-analysis/#estimating-the-proportion-of-true-nulls">Checking a multiple-testing analysis</a> estimates from the p-value histogram. A single experiment has no histogram, so the prior stays a judgement and the answer stays a curve. Colquhoun (2014), who calls this share the false discovery rate, works out the same share for other priors and powers, both for p below 0.05 and for p close to it.</p>
</section>
<section id="report-the-interval-next-to-it" class="level2">
<h2 id="report-the-interval-next-to-it-h" class="anchored" data-anchor-id="report-the-interval-next-to-it">Report the interval next to it</h2>
<p>The fix for the grazing experiment is one line that is already in the <code>t.test()</code> output: the estimate with its 95 per cent confidence interval. <a href="https://tidyecology.com/posts/standard-errors-confidence-intervals/">Standard errors and confidence intervals in R</a> explains how the interval is built and what its coverage means.</p>
<div class="cell">
<div class="code-copy-outer-scaffold"><div class="sourceCode cell-code" id="cb18" style="background: #f1f3f5;"><pre class="sourceCode r code-with-copy"><code class="sourceCode r"><span id="cb18-1"><span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">round</span>(<span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">c</span>(<span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">estimate =</span> diff_obs, <span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">lower =</span> ci_obs[<span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">1</span>], <span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">upper =</span> ci_obs[<span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">2</span>]), <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">2</span>)</span></code></pre></div></div>
<div class="cell-output cell-output-stdout">
<pre><code>estimate    lower    upper 
    4.56     0.23     8.89 </code></pre>
</div>
</div>
<p>The same experiment that gave p = 0.040 says the fenced plots are between 0.23 and 8.89 cm taller. The low end is a difference nobody would notice in the field, and the high end is 1.9 times the estimate itself. The low end sits near zero because p sits near 0.05: the interval and the p-value come from the same t statistic, but the interval states the result in centimetres, where you can judge which effects are still in play. The figure repeats the experiment twenty times with the same truth.</p>
<div class="cell">
<div class="cell-output-display">
<div id="fig-repeats" class="quarto-float quarto-figure quarto-figure-center anchored" alt="Twenty-one horizontal 95 per cent confidence intervals stacked in rows, the top one labelled your experiment and the others repeat 1 to repeat 20, on an axis of fenced minus grazed seedling height from -4 to 10 cm. A black line marks zero and a dotted gold line marks the true difference of 3.5 cm. Intervals with p below 0.05 are dark green and the others red, eleven green including your experiment and ten red, and the p-value of each row is printed at the right, from 0.002 to 0.998. Your experiment runs from about 0.2 to 8.9 cm with p = 0.040, and every interval crosses the gold line.">
<figure class="quarto-float quarto-float-fig figure">
<div aria-describedby="fig-repeats-caption-0ceaefa1-69ba-4598-a22c-09a6ac19f8ca">
<img src="https://tidyecology.com/posts/what-a-p-value-tells-you/index_files/figure-html/fig-repeats-1.png" class="img-fluid figure-img" alt="Twenty-one horizontal 95 per cent confidence intervals stacked in rows, the top one labelled your experiment and the others repeat 1 to repeat 20, on an axis of fenced minus grazed seedling height from -4 to 10 cm. A black line marks zero and a dotted gold line marks the true difference of 3.5 cm. Intervals with p below 0.05 are dark green and the others red, eleven green including your experiment and ten red, and the p-value of each row is printed at the right, from 0.002 to 0.998. Your experiment runs from about 0.2 to 8.9 cm with p = 0.040, and every interval crosses the gold line." width="720">
</div>
<figcaption class="quarto-float-caption-bottom quarto-float-caption quarto-float-fig" id="fig-repeats-caption-0ceaefa1-69ba-4598-a22c-09a6ac19f8ca">
Figure&nbsp;3: The simulated grazing experiment (top) and 20 exact repeats with the same true difference of 3.5 cm (dotted line). Each row shows the estimated difference with its 95 per cent confidence interval and the p-value of that run. With the same truth, the p-values fall on both sides of 0.05 from one run to the next, while every interval, yours included, contains the true difference.
</figcaption>
</figure>
</div>
</div>
</div>
<p>In these twenty repeats 10 gave p &lt; 0.05, and the p-values ran from 0.0016 to 0.998. All 20 intervals of the same runs contain the true 3.5 cm, whether or not their run crossed 0.05, and each states in centimetres which effects that run leaves in play. Cumming (2008) works this contrast out in general: an interval says more about where the next result will land than the p-value does.</p>
</section>
<section id="what-to-check-in-your-own-data" class="level2">
<h2 id="what-to-check-in-your-own-data-h" class="anchored" data-anchor-id="what-to-check-in-your-own-data">What to check in your own data</h2>
<p>Before you write “significant”, read what <code>t.test()</code> or <code>summary()</code> actually ran. For <code>t.test()</code> the header names the test, and the default is Welch; for <code>lm()</code> and <code>glm()</code> each coefficient’s p-value tests that one coefficient against zero with the others in the model.</p>
<p>Put the estimate and its confidence interval in the sentence, not only the p-value: “fenced plots were 4.6 cm taller (95 per cent CI 0.2 to 8.9)” says more than “p = 0.040”, and a reader can see at once whether small effects are still in play.</p>
<p>When you plan a follow-up or judge whether a result should replicate, ask what the power of the design is. At the true effect, that power is the chance a repeat reaches significance, not one minus p.&nbsp;Because the true effect is unknown, compute the power for the smallest effect you care about: it tells you whether a repeat could reliably detect an effect of that size. Do not plug in the effect you observed; that gives observed power, Goodman’s number, which only restates p.</p>
<p>If a result sits just below 0.05, treat it as what the spread of p-values above shows it to be: a single draw from a wide range. Do not sort results into real and not real at the threshold; <a href="https://tidyecology.com/posts/comparing-significance-is-not-a-test/">Comparing significance is not a test</a> shows what goes wrong when two results on either side of 0.05 are read as different.</p>
</section>
<section id="honest-limits" class="level2">
<h2 id="honest-limits-h" class="anchored" data-anchor-id="honest-limits">Honest limits</h2>
<p>The whole post uses one design: normal plot heights, equal spread in both groups, twelve plots each, and one true effect chosen so that the power sits near one half. With a stronger effect or more plots the power at the true effect, and so the replication share, rises; the point is that the share is set by that power and not by the p-value, nor by the power computed at the observed effect. The replication share was measured with the true effect fixed. In a real literature true effects vary and some are zero, and then the share of significant replicates after p between 0.01 and 0.05 depends on that mixture, which no single experiment reveals. How often is there no effect behind it? prices one consequence of that mixture in its simplest form, a fixed share of true nulls with every real effect exactly 3.5 cm: the share of window results that have no effect behind them, drawn as a curve because the mixture is unknown. The example experiment was chosen from the simulation because its p-value fell in the window of the question; the interval figures in the last section describe that one draw and twenty repeats, not a coverage study, which <a href="https://tidyecology.com/posts/standard-errors-confidence-intervals/">Standard errors and confidence intervals in R</a> runs properly.</p>
</section>
<section id="references" class="level2">
<h2 id="references-h" class="anchored" data-anchor-id="references">References</h2>
<p>Colquhoun D 2014 Royal Society Open Science 1(3):140216 (<a href="https://doi.org/10.1098/rsos.140216">10.1098/rsos.140216</a>)</p>
<p>Cumming G 2008 Perspectives on Psychological Science 3(4):286-300 (<a href="https://doi.org/10.1111/j.1745-6924.2008.00079.x">10.1111/j.1745-6924.2008.00079.x</a>)</p>
<p>Goodman SN 1992 Statistics in Medicine 11(7):875-879 (<a href="https://doi.org/10.1002/sim.4780110705">10.1002/sim.4780110705</a>)</p>
<p>Halsey LG, Curran-Everett D, Vowler SL, Drummond GB 2015 Nature Methods 12(3):179-185 (<a href="https://doi.org/10.1038/nmeth.3288">10.1038/nmeth.3288</a>)</p>
<p>Wasserstein RL, Lazar NA 2016 The American Statistician 70(2):129-133 (<a href="https://doi.org/10.1080/00031305.2016.1154108">10.1080/00031305.2016.1154108</a>)</p>
</section>
<section id="related-tutorials" class="level2">
<h2 id="related-tutorials-h" class="anchored" data-anchor-id="related-tutorials">Related tutorials</h2>
<ul>
<li><a href="https://tidyecology.com/posts/standard-errors-confidence-intervals/">Standard errors and confidence intervals in R</a></li>
<li><a href="https://tidyecology.com/posts/observed-power-tells-you-nothing/">Observed power tells you nothing</a></li>
<li><a href="https://tidyecology.com/posts/power-analysis-by-simulation/">Power analysis by simulation in R</a></li>
<li><a href="https://tidyecology.com/posts/checking-a-multiple-testing-analysis/">Checking a multiple-testing analysis</a></li>
</ul>
<details class="te-repro" data-pagefind-ignore="">
<summary>Reproducibility</summary>
<ul>
<li>Code last run: 2026-10-15</li>
<li>R version 4.5.3 (2026-03-11), aarch64-apple-darwin20</li>
<li>Packages: ggplot2 4.0.3</li>
</ul>
</details>


<!-- -->

</section>

 ]]></description>
  <category>R</category>
  <category>statistics</category>
  <category>hypothesis testing</category>
  <category>simulation</category>
  <category>ecology tutorial</category>
  <guid isPermaLink="false">https://tidyecology.com/posts/what-a-p-value-tells-you/</guid>
  <pubDate>Mon, 28 Sep 2026 06:00:00 GMT</pubDate>
  <media:content url="https://tidyecology.com/posts/what-a-p-value-tells-you/thumbnail.png" medium="image" type="image/png" height="104" width="144"/>
</item>
<item>
  <title>Simulating correlated variables in R</title>
  <dc:creator>Tidy Ecology</dc:creator>
  <link>https://tidyecology.com/posts/simulating-correlated-variables/</link>
  <description><![CDATA[ 





<p>A pilot survey counted two ground beetle species in pitfall traps at 40 grassland sites. The first species averaged a few beetles per trap, the second several more, and sites that were good for one tended to be good for the other: the Pearson correlation between the two columns of counts was about 0.6. The next step is a power analysis for a larger survey, and that needs simulated surveys that look like the pilot, with the two species correlated as they were in the field. How do you simulate two correlated variables, and how do you make the counts come out correlated at 0.6?</p>
<p><a href="https://tidyecology.com/posts/power-analysis-by-simulation/">Power analysis by simulation in R</a> builds the simulation loop, the approach Bolker (2008) teaches for ecological models, and <a href="https://tidyecology.com/posts/probability-distributions-in-r/">Probability distributions in R: d, p, q and r</a> explains <code>rnorm()</code> and <code>rpois()</code>. Neither makes two variables move together. Dozens of posts on this site do, usually with one line built around <code>chol()</code> or <code>MASS::mvrnorm()</code> and no comment. This post explains that line, then measures the trap that is easy to walk into the first time you simulate correlated counts.</p>
<p><strong>The short answer.</strong> Draw independent standard normals and mix them: for two variables, <code>x2 &lt;- rho * z1 + sqrt(1 - rho^2) * z2</code>; for any number, <code>Z %*% chol(Sigma)</code>, with the Cholesky factor on the right of the matrix of draws, or let <code>MASS::mvrnorm()</code> do it. For counts, the usual route puts the correlation on a hidden log scale and draws Poisson counts from it. The counts then correlate less than the number you typed, so decide first which scale your target belongs to. If it is the correlation of the counts, solve for the log-scale value that produces it, and check that it can be produced at all.</p>
<p>All data here are simulated, and every seed is in the code.</p>
<div class="cell">
<div class="code-copy-outer-scaffold"><div class="sourceCode cell-code" id="cb1" style="background: #f1f3f5;"><pre class="sourceCode r code-with-copy"><code class="sourceCode r"><span id="cb1-1"><span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">library</span>(ggplot2)</span>
<span id="cb1-2"></span>
<span id="cb1-3">te_paper  <span class="ot" style="color: #003B4F;
background-color: null;
font-style: inherit;">&lt;-</span> <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"#f5f4ee"</span></span>
<span id="cb1-4">te_ink    <span class="ot" style="color: #003B4F;
background-color: null;
font-style: inherit;">&lt;-</span> <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"#16241d"</span></span>
<span id="cb1-5">te_body   <span class="ot" style="color: #003B4F;
background-color: null;
font-style: inherit;">&lt;-</span> <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"#2c3a31"</span></span>
<span id="cb1-6">te_forest <span class="ot" style="color: #003B4F;
background-color: null;
font-style: inherit;">&lt;-</span> <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"#275139"</span></span>
<span id="cb1-7">te_rust   <span class="ot" style="color: #003B4F;
background-color: null;
font-style: inherit;">&lt;-</span> <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"#b5534e"</span></span>
<span id="cb1-8">te_gold   <span class="ot" style="color: #003B4F;
background-color: null;
font-style: inherit;">&lt;-</span> <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"#c9b458"</span></span>
<span id="cb1-9">te_line   <span class="ot" style="color: #003B4F;
background-color: null;
font-style: inherit;">&lt;-</span> <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"#dad9ca"</span></span>
<span id="cb1-10"></span>
<span id="cb1-11">theme_datasheet <span class="ot" style="color: #003B4F;
background-color: null;
font-style: inherit;">&lt;-</span> <span class="cf" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">function</span>() {</span>
<span id="cb1-12">  <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">theme_minimal</span>(<span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">base_size =</span> <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">12</span>) <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">+</span></span>
<span id="cb1-13">    <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">theme</span>(<span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">plot.background  =</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">element_rect</span>(<span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">fill =</span> te_paper, <span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">colour =</span> <span class="cn" style="color: #8f5902;
background-color: null;
font-style: inherit;">NA</span>),</span>
<span id="cb1-14">          <span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">panel.background =</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">element_rect</span>(<span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">fill =</span> te_paper, <span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">colour =</span> <span class="cn" style="color: #8f5902;
background-color: null;
font-style: inherit;">NA</span>),</span>
<span id="cb1-15">          <span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">panel.grid.major =</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">element_line</span>(<span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">colour =</span> te_line, <span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">linewidth =</span> <span class="fl" style="color: #AD0000;
background-color: null;
font-style: inherit;">0.3</span>),</span>
<span id="cb1-16">          <span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">panel.grid.minor =</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">element_blank</span>(),</span>
<span id="cb1-17">          <span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">text             =</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">element_text</span>(<span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">colour =</span> te_body),</span>
<span id="cb1-18">          <span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">axis.text        =</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">element_text</span>(<span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">colour =</span> te_body),</span>
<span id="cb1-19">          <span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">strip.text       =</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">element_text</span>(<span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">colour =</span> te_ink, <span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">face =</span> <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"bold"</span>))</span>
<span id="cb1-20">}</span></code></pre></div></div>
</div>
<section id="two-correlated-variables-by-hand" class="level2">
<h2 id="two-correlated-variables-by-hand-h" class="anchored" data-anchor-id="two-correlated-variables-by-hand">Two correlated variables by hand</h2>
<p>Start with two independent standard normals, <code>z1</code> and <code>z2</code>. Keep <code>z1</code> as the first variable and build the second from both: a share <code>rho</code> of <code>z1</code> plus enough of <code>z2</code> to bring the variance back to one.</p>
<div class="cell">
<div class="code-copy-outer-scaffold"><div class="sourceCode cell-code" id="cb2" style="background: #f1f3f5;"><pre class="sourceCode r code-with-copy"><code class="sourceCode r"><span id="cb2-1"><span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">set.seed</span>(<span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">1015</span>)</span>
<span id="cb2-2">n_big <span class="ot" style="color: #003B4F;
background-color: null;
font-style: inherit;">&lt;-</span> <span class="fl" style="color: #AD0000;
background-color: null;
font-style: inherit;">1e5</span></span>
<span id="cb2-3">rho   <span class="ot" style="color: #003B4F;
background-color: null;
font-style: inherit;">&lt;-</span> <span class="fl" style="color: #AD0000;
background-color: null;
font-style: inherit;">0.6</span></span>
<span id="cb2-4"></span>
<span id="cb2-5">z1 <span class="ot" style="color: #003B4F;
background-color: null;
font-style: inherit;">&lt;-</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">rnorm</span>(n_big)</span>
<span id="cb2-6">z2 <span class="ot" style="color: #003B4F;
background-color: null;
font-style: inherit;">&lt;-</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">rnorm</span>(n_big)</span>
<span id="cb2-7">x1 <span class="ot" style="color: #003B4F;
background-color: null;
font-style: inherit;">&lt;-</span> z1</span>
<span id="cb2-8">x2 <span class="ot" style="color: #003B4F;
background-color: null;
font-style: inherit;">&lt;-</span> rho <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">*</span> z1 <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">+</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">sqrt</span>(<span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">1</span> <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">-</span> rho<span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">^</span><span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">2</span>) <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">*</span> z2</span>
<span id="cb2-9"></span>
<span id="cb2-10"><span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">round</span>(<span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">c</span>(<span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">sd_x1 =</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">sd</span>(x1), <span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">sd_x2 =</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">sd</span>(x2), <span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">correlation =</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">cor</span>(x1, x2)), <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">3</span>)</span></code></pre></div></div>
<div class="cell-output cell-output-stdout">
<pre><code>      sd_x1       sd_x2 correlation 
      1.000       1.001       0.598 </code></pre>
</div>
</div>
<p>The algebra is two lines. The variance of <code>x2</code> is <code>rho^2 + (1 - rho^2) = 1</code>, because <code>z1</code> and <code>z2</code> are independent with variance one, and the covariance of <code>x1</code> and <code>x2</code> is <code>rho</code>, because only the <code>z1</code> part is shared. Both standard deviations are one, so the covariance is also the correlation, and a hundred thousand draws give 0.598 against the 0.6 we asked for. To give the variables other means and spreads, multiply and add afterwards: <code>10 + 2 * x2</code> has correlation <code>rho</code> with <code>x1</code> too, because shifting and rescaling does not change a correlation.</p>
</section>
<section id="any-number-of-variables-chol" class="level2">
<h2 id="any-number-of-variables-chol-h" class="anchored" data-anchor-id="any-number-of-variables-chol">Any number of variables: chol()</h2>
<p>With three or more variables the mixing weights are no longer obvious, and the Cholesky decomposition supplies them. Say three species have log-abundances that correlate at 0.6, 0.3 and 0.5 in pairs. Write the targets into a correlation matrix and hand it to <code>chol()</code>:</p>
<div class="cell">
<div class="code-copy-outer-scaffold"><div class="sourceCode cell-code" id="cb4" style="background: #f1f3f5;"><pre class="sourceCode r code-with-copy"><code class="sourceCode r"><span id="cb4-1">sigma3 <span class="ot" style="color: #003B4F;
background-color: null;
font-style: inherit;">&lt;-</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">matrix</span>(<span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">c</span>(<span class="fl" style="color: #AD0000;
background-color: null;
font-style: inherit;">1.0</span>, <span class="fl" style="color: #AD0000;
background-color: null;
font-style: inherit;">0.6</span>, <span class="fl" style="color: #AD0000;
background-color: null;
font-style: inherit;">0.3</span>,</span>
<span id="cb4-2">                   <span class="fl" style="color: #AD0000;
background-color: null;
font-style: inherit;">0.6</span>, <span class="fl" style="color: #AD0000;
background-color: null;
font-style: inherit;">1.0</span>, <span class="fl" style="color: #AD0000;
background-color: null;
font-style: inherit;">0.5</span>,</span>
<span id="cb4-3">                   <span class="fl" style="color: #AD0000;
background-color: null;
font-style: inherit;">0.3</span>, <span class="fl" style="color: #AD0000;
background-color: null;
font-style: inherit;">0.5</span>, <span class="fl" style="color: #AD0000;
background-color: null;
font-style: inherit;">1.0</span>), <span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">nrow =</span> <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">3</span>)</span>
<span id="cb4-4">chol_upper <span class="ot" style="color: #003B4F;
background-color: null;
font-style: inherit;">&lt;-</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">chol</span>(sigma3)</span>
<span id="cb4-5"><span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">round</span>(chol_upper, <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">3</span>)</span></code></pre></div></div>
<div class="cell-output cell-output-stdout">
<pre><code>     [,1] [,2]  [,3]
[1,]    1  0.6 0.300
[2,]    0  0.8 0.400
[3,]    0  0.0 0.866</code></pre>
</div>
</div>
<p><code>chol()</code> returns an upper triangular matrix, zeros below the diagonal, and it is the factor <code>R</code> for which <code>t(R) %*% R</code> gives back <code>sigma3</code>. That orientation decides which side of the draws it goes on. Put independent standard normals in a matrix with one row per site and one column per variable, and multiply by <code>R</code> on the right:</p>
<div class="cell">
<div class="code-copy-outer-scaffold"><div class="sourceCode cell-code" id="cb6" style="background: #f1f3f5;"><pre class="sourceCode r code-with-copy"><code class="sourceCode r"><span id="cb6-1"><span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">set.seed</span>(<span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">2015</span>)</span>
<span id="cb6-2">z3 <span class="ot" style="color: #003B4F;
background-color: null;
font-style: inherit;">&lt;-</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">matrix</span>(<span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">rnorm</span>(<span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">3</span> <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">*</span> n_big), <span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">ncol =</span> <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">3</span>)</span>
<span id="cb6-3">x3 <span class="ot" style="color: #003B4F;
background-color: null;
font-style: inherit;">&lt;-</span> z3 <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">%*%</span> chol_upper</span>
<span id="cb6-4"><span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">round</span>(<span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">cor</span>(x3), <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">3</span>)</span></code></pre></div></div>
<div class="cell-output cell-output-stdout">
<pre><code>      [,1]  [,2]  [,3]
[1,] 1.000 0.602 0.302
[2,] 0.602 1.000 0.504
[3,] 0.302 0.504 1.000</code></pre>
</div>
</div>
<p>The covariance of <code>z3 %*% R</code> is <code>t(R) %*% R</code>, which is <code>sigma3</code>, and the simulated correlations match the targets. The first column of <code>R</code> is <code>(1, 0, 0)</code>, so the first variable is simply the first column of draws, and the second column of <code>R</code> holds the same two weights as the hand-made <code>x2</code> above: the by-hand recipe is the two-variable Cholesky factor written out.</p>
<p>Put the factor on the other side, <code>z3 %*% t(R)</code>, and the covariance becomes <code>R %*% t(R)</code>, which is a different matrix:</p>
<div class="cell">
<div class="code-copy-outer-scaffold"><div class="sourceCode cell-code" id="cb8" style="background: #f1f3f5;"><pre class="sourceCode r code-with-copy"><code class="sourceCode r"><span id="cb8-1">x3_wrong <span class="ot" style="color: #003B4F;
background-color: null;
font-style: inherit;">&lt;-</span> z3 <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">%*%</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">t</span>(chol_upper)</span>
<span id="cb8-2"><span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">round</span>(<span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">cor</span>(x3_wrong), <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">3</span>)</span></code></pre></div></div>
<div class="cell-output cell-output-stdout">
<pre><code>      [,1]  [,2]  [,3]
[1,] 1.000 0.559 0.253
[2,] 0.559 1.000 0.452
[3,] 0.253 0.452 1.000</code></pre>
</div>
<div class="code-copy-outer-scaffold"><div class="sourceCode cell-code" id="cb10" style="background: #f1f3f5;"><pre class="sourceCode r code-with-copy"><code class="sourceCode r"><span id="cb10-1"><span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">round</span>(<span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">diag</span>(<span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">var</span>(x3_wrong)), <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">3</span>)</span></code></pre></div></div>
<div class="cell-output cell-output-stdout">
<pre><code>[1] 1.458 0.803 0.750</code></pre>
</div>
</div>
<p>The targets 0.6, 0.3 and 0.5 come out as 0.559, 0.253 and 0.452, and the variances, which should all be one, run from 0.75 to 1.46. Nothing warns you. The same mistake with only two variables is no safer: <code>R %*% t(R)</code> then has correlation <code>rho / sqrt(1 + rho^2)</code>, which is 0.514 for a target of 0.6. Some posts on this site draw one realisation at a time as a column, <code>t(chol(Sigma)) %*% z</code>; that is the correct product for a column, because it is the transpose of <code>z %*% chol(Sigma)</code> for a row.</p>
<p>The shortcut is <code>mvrnorm()</code> from the MASS package that accompanies Venables and Ripley (2002). It takes the means and the covariance matrix and returns one row per draw:</p>
<div class="cell">
<div class="code-copy-outer-scaffold"><div class="sourceCode cell-code" id="cb12" style="background: #f1f3f5;"><pre class="sourceCode r code-with-copy"><code class="sourceCode r"><span id="cb12-1"><span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">set.seed</span>(<span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">3015</span>)</span>
<span id="cb12-2">x3_mass <span class="ot" style="color: #003B4F;
background-color: null;
font-style: inherit;">&lt;-</span> MASS<span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">::</span><span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">mvrnorm</span>(n_big, <span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">mu =</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">c</span>(<span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">0</span>, <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">0</span>, <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">0</span>), <span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">Sigma =</span> sigma3)</span>
<span id="cb12-3"><span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">round</span>(<span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">cor</span>(x3_mass), <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">3</span>)</span></code></pre></div></div>
<div class="cell-output cell-output-stdout">
<pre><code>      [,1]  [,2]  [,3]
[1,] 1.000 0.599 0.303
[2,] 0.599 1.000 0.502
[3,] 0.303 0.502 1.000</code></pre>
</div>
</div>
<p>Internally <code>mvrnorm()</code> uses an eigen decomposition of <code>Sigma</code> rather than <code>chol()</code>, so the individual draws differ from the Cholesky ones, but the covariance they are drawn from is the same. It is the line to use in practice; writing the Cholesky version once is what makes it readable.</p>
</section>
<section id="correlated-counts-the-correlation-you-set-is-not-the-one-you-get" class="level2">
<h2 id="correlated-counts-the-correlation-you-set-is-not-the-one-you-get-h" class="anchored" data-anchor-id="correlated-counts-the-correlation-you-set-is-not-the-one-you-get">Correlated counts: the correlation you set is not the one you get</h2>
<p>Now the beetles. Counts are not normal, so the usual route, and the one behind most joint species models for counts, puts the correlation on a hidden scale. Each site gets a pair of correlated normal log-abundances with standard deviation <code>s</code>; each species’ expected count is its site mean times the exponential of its log-abundance; and the trap catches a Poisson count around that expectation. Subtracting <code>s^2 / 2</code> inside the exponential keeps the average count at the site mean, because the mean of <code>exp(x)</code> for a normal <code>x</code> with mean zero and standard deviation <code>s</code> is <code>exp(s^2 / 2)</code>.</p>
<div class="cell">
<div class="code-copy-outer-scaffold"><div class="sourceCode cell-code" id="cb14" style="background: #f1f3f5;"><pre class="sourceCode r code-with-copy"><code class="sourceCode r"><span id="cb14-1">simulate_counts <span class="ot" style="color: #003B4F;
background-color: null;
font-style: inherit;">&lt;-</span> <span class="cf" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">function</span>(n_sites, rho_latent, s, mu) {</span>
<span id="cb14-2">  sigma  <span class="ot" style="color: #003B4F;
background-color: null;
font-style: inherit;">&lt;-</span> s<span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">^</span><span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">2</span> <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">*</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">matrix</span>(<span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">c</span>(<span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">1</span>, rho_latent, rho_latent, <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">1</span>), <span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">nrow =</span> <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">2</span>)</span>
<span id="cb14-3">  latent <span class="ot" style="color: #003B4F;
background-color: null;
font-style: inherit;">&lt;-</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">matrix</span>(<span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">rnorm</span>(<span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">2</span> <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">*</span> n_sites), <span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">ncol =</span> <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">2</span>) <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">%*%</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">chol</span>(sigma)</span>
<span id="cb14-4">  expected <span class="ot" style="color: #003B4F;
background-color: null;
font-style: inherit;">&lt;-</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">cbind</span>(mu[<span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">1</span>] <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">*</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">exp</span>(latent[, <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">1</span>] <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">-</span> s<span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">^</span><span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">2</span> <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">/</span> <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">2</span>),</span>
<span id="cb14-5">                    mu[<span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">2</span>] <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">*</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">exp</span>(latent[, <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">2</span>] <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">-</span> s<span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">^</span><span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">2</span> <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">/</span> <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">2</span>))</span>
<span id="cb14-6">  counts <span class="ot" style="color: #003B4F;
background-color: null;
font-style: inherit;">&lt;-</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">matrix</span>(<span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">rpois</span>(<span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">2</span> <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">*</span> n_sites, expected), <span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">ncol =</span> <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">2</span>)</span>
<span id="cb14-7">  <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">list</span>(<span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">latent =</span> latent, <span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">counts =</span> counts)</span>
<span id="cb14-8">}</span>
<span id="cb14-9"></span>
<span id="cb14-10">mu_beetle <span class="ot" style="color: #003B4F;
background-color: null;
font-style: inherit;">&lt;-</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">c</span>(<span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">3</span>, <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">8</span>)   <span class="co" style="color: #5E5E5E;
background-color: null;
font-style: inherit;"># mean beetles per trap, species A and B</span></span>
<span id="cb14-11">s_log     <span class="ot" style="color: #003B4F;
background-color: null;
font-style: inherit;">&lt;-</span> <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">1</span>         <span class="co" style="color: #5E5E5E;
background-color: null;
font-style: inherit;"># standard deviation of log-abundance between sites</span></span>
<span id="cb14-12">n_sites   <span class="ot" style="color: #003B4F;
background-color: null;
font-style: inherit;">&lt;-</span> <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">40</span></span>
<span id="cb14-13"></span>
<span id="cb14-14"><span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">set.seed</span>(<span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">4015</span>)</span>
<span id="cb14-15">survey <span class="ot" style="color: #003B4F;
background-color: null;
font-style: inherit;">&lt;-</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">simulate_counts</span>(n_sites, <span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">rho_latent =</span> <span class="fl" style="color: #AD0000;
background-color: null;
font-style: inherit;">0.6</span>, <span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">s =</span> s_log, <span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">mu =</span> mu_beetle)</span>
<span id="cb14-16"><span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">head</span>(survey<span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">$</span>counts)</span></code></pre></div></div>
<div class="cell-output cell-output-stdout">
<pre><code>     [,1] [,2]
[1,]    4    6
[2,]    2    3
[3,]    0    1
[4,]    0    4
[5,]   10   26
[6,]    2    3</code></pre>
</div>
<div class="code-copy-outer-scaffold"><div class="sourceCode cell-code" id="cb16" style="background: #f1f3f5;"><pre class="sourceCode r code-with-copy"><code class="sourceCode r"><span id="cb16-1"><span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">round</span>(<span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">c</span>(<span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">latent =</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">cor</span>(survey<span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">$</span>latent)[<span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">1</span>, <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">2</span>], <span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">counts =</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">cor</span>(survey<span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">$</span>counts)[<span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">1</span>, <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">2</span>]), <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">3</span>)</span></code></pre></div></div>
<div class="cell-output cell-output-stdout">
<pre><code>latent counts 
 0.593  0.416 </code></pre>
</div>
</div>
<p>In this one simulated survey the log-abundances correlate at 0.593 and the counts at 0.416. One survey of 40 sites is noisy, so the chunk below asks what the counts correlate at in the long run: forty batches of fifty thousand sites each, with the correlation computed in every batch and averaged, so that the spread between batches gives a Monte Carlo standard error.</p>
<div class="cell">
<div class="code-copy-outer-scaffold"><div class="sourceCode cell-code" id="cb18" style="background: #f1f3f5;"><pre class="sourceCode r code-with-copy"><code class="sourceCode r"><span id="cb18-1">long_run <span class="ot" style="color: #003B4F;
background-color: null;
font-style: inherit;">&lt;-</span> <span class="cf" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">function</span>(rho_latent, s, mu, <span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">n_batch =</span> <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">40</span>, <span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">batch_size =</span> <span class="fl" style="color: #AD0000;
background-color: null;
font-style: inherit;">5e4</span>) {</span>
<span id="cb18-2">  per_batch <span class="ot" style="color: #003B4F;
background-color: null;
font-style: inherit;">&lt;-</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">replicate</span>(n_batch, {</span>
<span id="cb18-3">    sim <span class="ot" style="color: #003B4F;
background-color: null;
font-style: inherit;">&lt;-</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">simulate_counts</span>(batch_size, rho_latent, s, mu)</span>
<span id="cb18-4">    <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">c</span>(<span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">latent    =</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">cor</span>(sim<span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">$</span>latent)[<span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">1</span>, <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">2</span>],</span>
<span id="cb18-5">      <span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">lognormal =</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">cor</span>(<span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">exp</span>(sim<span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">$</span>latent))[<span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">1</span>, <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">2</span>],</span>
<span id="cb18-6">      <span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">counts    =</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">cor</span>(sim<span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">$</span>counts)[<span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">1</span>, <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">2</span>],</span>
<span id="cb18-7">      <span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">var_a     =</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">var</span>(sim<span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">$</span>counts[, <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">1</span>]),</span>
<span id="cb18-8">      <span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">var_b     =</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">var</span>(sim<span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">$</span>counts[, <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">2</span>]),</span>
<span id="cb18-9">      <span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">cov_ab    =</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">cov</span>(sim<span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">$</span>counts)[<span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">1</span>, <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">2</span>])</span>
<span id="cb18-10">  })</span>
<span id="cb18-11">  <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">rbind</span>(<span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">mean =</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">rowMeans</span>(per_batch),</span>
<span id="cb18-12">        <span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">mc_se =</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">apply</span>(per_batch, <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">1</span>, sd) <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">/</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">sqrt</span>(n_batch))</span>
<span id="cb18-13">}</span>
<span id="cb18-14"></span>
<span id="cb18-15"><span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">set.seed</span>(<span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">5015</span>)</span>
<span id="cb18-16">run_06 <span class="ot" style="color: #003B4F;
background-color: null;
font-style: inherit;">&lt;-</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">long_run</span>(<span class="fl" style="color: #AD0000;
background-color: null;
font-style: inherit;">0.6</span>, s_log, mu_beetle)</span>
<span id="cb18-17"><span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">round</span>(run_06, <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">3</span>)</span></code></pre></div></div>
<div class="cell-output cell-output-stdout">
<pre><code>      latent lognormal counts  var_a   var_b cov_ab
mean   0.600     0.481  0.424 18.642 117.763 19.883
mc_se  0.001     0.002  0.002  0.102   0.847  0.137</code></pre>
</div>
</div>
<p>The latent correlation is the 0.60 we set. The exponentials of the log-abundances already correlate at only 0.481, and the counts at 0.424. A power analysis run with <code>rho_latent = 0.6</code> would simulate beetles that are much less tied to each other than the pilot’s, and every power figure from it would answer a different question.</p>
<p>None of this needs a simulation to predict. Two short results give the long-run values. The count formulas are in Aitchison and Ho (1989); the first result is the same calculation without the Poisson term. For the exponentials: the sum of the two log-abundances is normal with variance <code>2 s^2 (1 + rho)</code>, so the mean of the product of the exponentials is <code>exp(s^2 (1 + rho))</code>, and dividing the covariance by the variance gives</p>
<pre><code>cor(exp(x1), exp(x2)) = (exp(rho * s^2) - 1) / (exp(s^2) - 1)</code></pre>
<p>For the counts: given the expected counts, the two Poisson draws are independent, so the Poisson noise adds its mean to each variance and nothing to the covariance,</p>
<pre><code>var(y)       = mu + mu^2 * (exp(s^2) - 1)
cov(y1, y2)  = mu1 * mu2 * (exp(rho * s^2) - 1)</code></pre>
<p>and the count correlation is the covariance over the product of the two standard deviations. The Poisson term <code>mu</code> in each variance is the second loss: it is largest, relative to the rest, for the rarer species.</p>
<div class="cell">
<div class="code-copy-outer-scaffold"><div class="sourceCode cell-code" id="cb22" style="background: #f1f3f5;"><pre class="sourceCode r code-with-copy"><code class="sourceCode r"><span id="cb22-1">count_cor <span class="ot" style="color: #003B4F;
background-color: null;
font-style: inherit;">&lt;-</span> <span class="cf" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">function</span>(rho_latent, s, mu) {</span>
<span id="cb22-2">  cov_ab <span class="ot" style="color: #003B4F;
background-color: null;
font-style: inherit;">&lt;-</span> mu[<span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">1</span>] <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">*</span> mu[<span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">2</span>] <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">*</span> (<span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">exp</span>(rho_latent <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">*</span> s<span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">^</span><span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">2</span>) <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">-</span> <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">1</span>)</span>
<span id="cb22-3">  var_ab <span class="ot" style="color: #003B4F;
background-color: null;
font-style: inherit;">&lt;-</span> mu <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">+</span> mu<span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">^</span><span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">2</span> <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">*</span> (<span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">exp</span>(s<span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">^</span><span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">2</span>) <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">-</span> <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">1</span>)</span>
<span id="cb22-4">  cov_ab <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">/</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">sqrt</span>(var_ab[<span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">1</span>] <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">*</span> var_ab[<span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">2</span>])</span>
<span id="cb22-5">}</span>
<span id="cb22-6">closed <span class="ot" style="color: #003B4F;
background-color: null;
font-style: inherit;">&lt;-</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">c</span>(<span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">lognormal =</span> (<span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">exp</span>(<span class="fl" style="color: #AD0000;
background-color: null;
font-style: inherit;">0.6</span> <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">*</span> s_log<span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">^</span><span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">2</span>) <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">-</span> <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">1</span>) <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">/</span> (<span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">exp</span>(s_log<span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">^</span><span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">2</span>) <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">-</span> <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">1</span>),</span>
<span id="cb22-7">            <span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">counts    =</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">count_cor</span>(<span class="fl" style="color: #AD0000;
background-color: null;
font-style: inherit;">0.6</span>, s_log, mu_beetle),</span>
<span id="cb22-8">            <span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">var_a     =</span> mu_beetle[<span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">1</span>] <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">+</span> mu_beetle[<span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">1</span>]<span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">^</span><span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">2</span> <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">*</span> (<span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">exp</span>(s_log<span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">^</span><span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">2</span>) <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">-</span> <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">1</span>),</span>
<span id="cb22-9">            <span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">var_b     =</span> mu_beetle[<span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">2</span>] <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">+</span> mu_beetle[<span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">2</span>]<span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">^</span><span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">2</span> <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">*</span> (<span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">exp</span>(s_log<span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">^</span><span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">2</span>) <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">-</span> <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">1</span>),</span>
<span id="cb22-10">            <span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">cov_ab    =</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">prod</span>(mu_beetle) <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">*</span> (<span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">exp</span>(<span class="fl" style="color: #AD0000;
background-color: null;
font-style: inherit;">0.6</span> <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">*</span> s_log<span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">^</span><span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">2</span>) <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">-</span> <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">1</span>))</span>
<span id="cb22-11">z_scores <span class="ot" style="color: #003B4F;
background-color: null;
font-style: inherit;">&lt;-</span> (run_06[<span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"mean"</span>, <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">names</span>(closed)] <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">-</span> closed) <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">/</span> run_06[<span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"mc_se"</span>, <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">names</span>(closed)]</span>
<span id="cb22-12"><span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">round</span>(<span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">rbind</span>(<span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">closed =</span> closed, <span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">simulated =</span> run_06[<span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"mean"</span>, <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">names</span>(closed)], <span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">z =</span> z_scores), <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">3</span>)</span></code></pre></div></div>
<div class="cell-output cell-output-stdout">
<pre><code>          lognormal counts  var_a   var_b cov_ab
closed        0.478  0.423 18.465 117.970 19.731
simulated     0.481  0.424 18.642 117.763 19.883
z             1.332  0.952  1.737  -0.244  1.108</code></pre>
</div>
</div>
<p>Each simulated value is within 1.8 Monte Carlo standard errors of its formula: the loss from 0.60 to 0.423 is arithmetic, not a finding of the simulation. It depends only on <code>rho</code>, <code>s</code> and the two means.</p>
<p>The pilot’s own 0.6 has a second weakness: it comes from 40 sites. Here is the spread of the count correlation across four thousand simulated 40-site surveys, all with the same log-scale correlation of 0.6:</p>
<div class="cell">
<div class="code-copy-outer-scaffold"><div class="sourceCode cell-code" id="cb24" style="background: #f1f3f5;"><pre class="sourceCode r code-with-copy"><code class="sourceCode r"><span id="cb24-1"><span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">set.seed</span>(<span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">6015</span>)</span>
<span id="cb24-2">cor_40 <span class="ot" style="color: #003B4F;
background-color: null;
font-style: inherit;">&lt;-</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">replicate</span>(<span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">4000</span>, {</span>
<span id="cb24-3">  <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">cor</span>(<span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">simulate_counts</span>(n_sites, <span class="fl" style="color: #AD0000;
background-color: null;
font-style: inherit;">0.6</span>, s_log, mu_beetle)<span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">$</span>counts)[<span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">1</span>, <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">2</span>]</span>
<span id="cb24-4">})</span>
<span id="cb24-5"><span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">round</span>(<span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">quantile</span>(cor_40, <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">c</span>(<span class="fl" style="color: #AD0000;
background-color: null;
font-style: inherit;">0.10</span>, <span class="fl" style="color: #AD0000;
background-color: null;
font-style: inherit;">0.50</span>, <span class="fl" style="color: #AD0000;
background-color: null;
font-style: inherit;">0.90</span>)), <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">3</span>)</span></code></pre></div></div>
<div class="cell-output cell-output-stdout">
<pre><code>  10%   50%   90% 
0.174 0.420 0.687 </code></pre>
</div>
</div>
<p>The long-run count correlation of this design is 0.423, yet one survey in ten reports less than 0.174 and one in ten more than 0.687, with the middle survey at 0.420; 19.9 per cent of these surveys report 0.6 or more. A pilot value of 0.6 from 40 sites can therefore come from a process whose long-run count correlation is well below 0.6, which is worth remembering whichever scale you settle on.</p>
</section>
<section id="the-fix-decide-which-scale-the-target-lives-on" class="level2">
<h2 id="the-fix-decide-which-scale-the-target-lives-on-h" class="anchored" data-anchor-id="the-fix-decide-which-scale-the-target-lives-on">The fix: decide which scale the target lives on</h2>
<p>If your 0.6 is a correlation on the log scale, for example a residual correlation from a fitted Poisson or negative binomial mixed model or a joint species model, then <code>rho_latent = 0.6</code> is already right and the counts should correlate less. If it is the Pearson correlation of the raw counts, as in the pilot, solve for the log-scale value that produces it. <code>count_cor()</code> rises steadily with <code>rho_latent</code>, so <code>uniroot()</code> can search between 0 and 1:</p>
<div class="cell">
<div class="code-copy-outer-scaffold"><div class="sourceCode cell-code" id="cb26" style="background: #f1f3f5;"><pre class="sourceCode r code-with-copy"><code class="sourceCode r"><span id="cb26-1">target <span class="ot" style="color: #003B4F;
background-color: null;
font-style: inherit;">&lt;-</span> <span class="fl" style="color: #AD0000;
background-color: null;
font-style: inherit;">0.6</span></span>
<span id="cb26-2">rho_needed <span class="ot" style="color: #003B4F;
background-color: null;
font-style: inherit;">&lt;-</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">uniroot</span>(<span class="cf" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">function</span>(r) <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">count_cor</span>(r, s_log, mu_beetle) <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">-</span> target,</span>
<span id="cb26-3">                      <span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">interval =</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">c</span>(<span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">0</span>, <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">1</span>))<span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">$</span>root</span>
<span id="cb26-4">rho_needed</span></code></pre></div></div>
<div class="cell-output cell-output-stdout">
<pre><code>[1] 0.7732494</code></pre>
</div>
<div class="code-copy-outer-scaffold"><div class="sourceCode cell-code" id="cb28" style="background: #f1f3f5;"><pre class="sourceCode r code-with-copy"><code class="sourceCode r"><span id="cb28-1"><span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">set.seed</span>(<span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">7015</span>)</span>
<span id="cb28-2">run_fixed <span class="ot" style="color: #003B4F;
background-color: null;
font-style: inherit;">&lt;-</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">long_run</span>(rho_needed, s_log, mu_beetle)</span>
<span id="cb28-3"><span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">round</span>(run_fixed[, <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">c</span>(<span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"latent"</span>, <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"counts"</span>)], <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">3</span>)</span></code></pre></div></div>
<div class="cell-output cell-output-stdout">
<pre><code>      latent counts
mean   0.773  0.597
mc_se  0.000  0.002</code></pre>
</div>
</div>
<p>A log-scale correlation of 0.773 gives counts that correlate at 0.597 in the long run (Monte Carlo standard error 0.002), 1.5 standard errors from the target. That is the number to put into the power analysis.</p>
<p>There is a limit, and it is better to see it before calling <code>uniroot()</code>. Even with <code>rho_latent = 1</code>, when both species follow exactly the same log-abundance, the Poisson noise keeps the counts apart, so the count correlation has a ceiling. The ceiling depends on how much the sites differ, <code>s</code>, and on how large the counts are: what matters is the between-site variance <code>mu^2 * (exp(s^2) - 1)</code> against the Poisson variance <code>mu</code>, so rarer species and more similar sites both lower it:</p>
<div class="cell">
<div class="code-copy-outer-scaffold"><div class="sourceCode cell-code" id="cb30" style="background: #f1f3f5;"><pre class="sourceCode r code-with-copy"><code class="sourceCode r"><span id="cb30-1">ceiling_s1  <span class="ot" style="color: #003B4F;
background-color: null;
font-style: inherit;">&lt;-</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">count_cor</span>(<span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">1</span>, <span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">s =</span> <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">1</span>,   <span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">mu =</span> mu_beetle)</span>
<span id="cb30-2">ceiling_s05 <span class="ot" style="color: #003B4F;
background-color: null;
font-style: inherit;">&lt;-</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">count_cor</span>(<span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">1</span>, <span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">s =</span> <span class="fl" style="color: #AD0000;
background-color: null;
font-style: inherit;">0.5</span>, <span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">mu =</span> mu_beetle)</span>
<span id="cb30-3">ceiling_s05_x10 <span class="ot" style="color: #003B4F;
background-color: null;
font-style: inherit;">&lt;-</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">count_cor</span>(<span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">1</span>, <span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">s =</span> <span class="fl" style="color: #AD0000;
background-color: null;
font-style: inherit;">0.5</span>, <span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">mu =</span> <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">10</span> <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">*</span> mu_beetle)</span>
<span id="cb30-4"><span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">round</span>(<span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">c</span>(<span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">ceiling_s1 =</span> ceiling_s1, <span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">ceiling_s05 =</span> ceiling_s05, <span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">ceiling_s05_x10 =</span> ceiling_s05_x10), <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">3</span>)</span></code></pre></div></div>
<div class="cell-output cell-output-stdout">
<pre><code>     ceiling_s1     ceiling_s05 ceiling_s05_x10 
          0.884           0.565           0.926 </code></pre>
</div>
<div class="code-copy-outer-scaffold"><div class="sourceCode cell-code" id="cb32" style="background: #f1f3f5;"><pre class="sourceCode r code-with-copy"><code class="sourceCode r"><span id="cb32-1">no_root <span class="ot" style="color: #003B4F;
background-color: null;
font-style: inherit;">&lt;-</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">tryCatch</span>(</span>
<span id="cb32-2">  <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">uniroot</span>(<span class="cf" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">function</span>(r) <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">count_cor</span>(r, <span class="fl" style="color: #AD0000;
background-color: null;
font-style: inherit;">0.5</span>, mu_beetle) <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">-</span> target, <span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">interval =</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">c</span>(<span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">0</span>, <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">1</span>)),</span>
<span id="cb32-3">  <span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">error =</span> <span class="cf" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">function</span>(e) <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">conditionMessage</span>(e))</span>
<span id="cb32-4">no_root</span></code></pre></div></div>
<div class="cell-output cell-output-stdout">
<pre><code>[1] "f() values at end points not of opposite sign"</code></pre>
</div>
</div>
<p>With <code>s = 1</code> the counts can reach 0.884, so 0.6 is attainable. With <code>s = 0.5</code>, sites that differ less, and these small means, the ceiling is 0.565: no log-scale correlation gives counts correlated at 0.6, and <code>uniroot()</code> stops with the message above, because the function it searches is below zero at both ends of the interval. That error is the model telling you the target is impossible, not a numerical problem to work around. If you meet it, either the pilot correlation is higher than this kind of process can produce (and with 40 sites, the previous section shows how easily that happens), or the counts vary between sites more than your <code>s</code> says. The same <code>s = 0.5</code> with means ten times larger, 30 and 80 beetles per trap, lifts the ceiling to 0.926, because the Poisson noise then matters much less.</p>
<div class="cell">
<div class="cell-output-display">
<div id="fig-count-cor" class="quarto-float quarto-figure quarto-figure-center anchored" alt="Line chart with the correlation set on the log scale on the horizontal axis from 0 to 1 and the correlation of the counts on the vertical axis from 0 to 1. A dashed black diagonal marks where the two are equal and a dotted gold horizontal line at 0.6 is labelled target: counts correlated at 0.6. A dark green curve for s = 1 starts at 0, bends upward below the diagonal and ends at 0.884, labelled ceiling 0.884. A red curve for s = 0.5 runs below it, almost straight, and ends at 0.565, labelled ceiling 0.565, below the target line. Two black points sit on the green curve, one above 0.6 on the horizontal axis at about 0.42, and one at about 0.77 where the green curve meets the target line.">
<figure class="quarto-float quarto-float-fig figure">
<div aria-describedby="fig-count-cor-caption-0ceaefa1-69ba-4598-a22c-09a6ac19f8ca">
<img src="https://tidyecology.com/posts/simulating-correlated-variables/index_files/figure-html/fig-count-cor-1.png" class="img-fluid figure-img" alt="Line chart with the correlation set on the log scale on the horizontal axis from 0 to 1 and the correlation of the counts on the vertical axis from 0 to 1. A dashed black diagonal marks where the two are equal and a dotted gold horizontal line at 0.6 is labelled target: counts correlated at 0.6. A dark green curve for s = 1 starts at 0, bends upward below the diagonal and ends at 0.884, labelled ceiling 0.884. A red curve for s = 0.5 runs below it, almost straight, and ends at 0.565, labelled ceiling 0.565, below the target line. Two black points sit on the green curve, one above 0.6 on the horizontal axis at about 0.42, and one at about 0.77 where the green curve meets the target line." width="691">
</div>
<figcaption class="quarto-float-caption-bottom quarto-float-caption quarto-float-fig" id="fig-count-cor-caption-0ceaefa1-69ba-4598-a22c-09a6ac19f8ca">
Figure&nbsp;1: Long-run correlation of two simulated Poisson counts (site means 3 and 8) against the correlation set on the log scale, for a between-site log-scale standard deviation of 1 and of 0.5, from the closed form. The dashed line is where the two would be equal. Points are the simulated long-run values at a log-scale correlation of 0.6 and at the value solved for a count correlation of 0.6 (dotted line). Each curve ends at its ceiling, the count correlation when the log-scale correlation is 1.
</figcaption>
</figure>
</div>
</div>
</div>
</section>
<section id="what-to-check-in-your-own-data" class="level2">
<h2 id="what-to-check-in-your-own-data-h" class="anchored" data-anchor-id="what-to-check-in-your-own-data">What to check in your own data</h2>
<p>Check the orientation once, on a large draw: <code>round(cor(Z %*% chol(Sigma)), 2)</code> should reproduce your target matrix, and the variances should be the diagonal of <code>Sigma</code>. If they are not, the factor is on the wrong side.</p>
<p>Write down which scale your target correlation was measured on. A residual correlation from a mixed model or a joint species model lives on the link scale; a correlation of raw counts lives on the count scale. Simulating one as if it were the other is the mistake measured above. <a href="https://tidyecology.com/posts/checking-a-jsdm/">Checking a joint species distribution model</a> goes the other way for presence-absence data, reading a latent correlation back from a two by two table with the tetrachoric correlation.</p>
<p>Estimate <code>s</code> from the pilot before you solve for the log-scale correlation. For each species, the variance formula above rearranges to <code>s^2 = log(1 + (var(y) - mean(y)) / mean(y)^2)</code>; if the variance is not above the mean, the counts show no extra spread between sites, <code>s</code> is near zero and so is any count correlation this model can make. If the two species give different values, the covariance becomes <code>mu1 * mu2 * (exp(rho * s1 * s2) - 1)</code> with <code>s1^2</code> and <code>s2^2</code> in the two variances.</p>
<p>Compare the ceiling, <code>count_cor(1, s, mu)</code>, with your target before calling <code>uniroot()</code>. Then simulate a large batch at the solved value and check the counts hit the target. <a href="https://tidyecology.com/posts/testing-your-analysis-code/">Testing your analysis code</a> shows how to keep a check like that as a test that runs every time the simulator changes.</p>
</section>
<section id="honest-limits" class="level2">
<h2 id="honest-limits-h" class="anchored" data-anchor-id="honest-limits">Honest limits</h2>
<p>The count model here is Poisson on a lognormal, with one <code>s</code> for both species; a negative binomial simulator, or a zero-inflated one, has other formulas and another ceiling, although the same <code>uniroot()</code> approach works once the formula is written down, or with a simulated long run in its place. Only positive correlations were shown, and a negative target meets a floor as well: at <code>s = 1</code> and these two means, <code>count_cor(-1, 1, mu)</code> is -0.325, so the counts cannot correlate more negatively than that. The whole post is about the Pearson correlation of two counts, which is only one summary of how two species go together; <a href="https://tidyecology.com/posts/copulas-for-dependent-ecological-data/">Copulas for dependent ecological data</a> measures the limits that any pair of marginal distributions puts on it, and <a href="https://tidyecology.com/posts/co-occurrence-is-not-interaction/">Co-occurrence is not interaction</a> explains why a correlation between two species, on either scale, says nothing on its own about why they go together. Finally, the pilot correlation is itself uncertain, as the 40-site spread showed, so a power analysis that is sensitive to it should be run over a range of plausible correlations, not at one solved value, and over a range of <code>s</code>, which a 40-site pilot also pins down only loosely.</p>
</section>
<section id="references" class="level2">
<h2 id="references-h" class="anchored" data-anchor-id="references">References</h2>
<p>Aitchison J, Ho CH 1989 Biometrika 76(4):643-653 (<a href="https://doi.org/10.1093/biomet/76.4.643">10.1093/biomet/76.4.643</a>)</p>
<p>Bolker BM 2008 Ecological Models and Data in R (ISBN 9780691125220)</p>
<p>Venables WN, Ripley BD 2002 Modern Applied Statistics with S, 4th edition (ISBN 9780387954578)</p>
</section>
<section id="related-tutorials" class="level2">
<h2 id="related-tutorials-h" class="anchored" data-anchor-id="related-tutorials">Related tutorials</h2>
<ul>
<li><a href="https://tidyecology.com/posts/power-analysis-by-simulation/">Power analysis by simulation in R</a></li>
<li><a href="https://tidyecology.com/posts/probability-distributions-in-r/">Probability distributions in R: d, p, q and r</a></li>
<li><a href="https://tidyecology.com/posts/copulas-for-dependent-ecological-data/">Copulas for dependent ecological data</a></li>
<li><a href="https://tidyecology.com/posts/checking-a-jsdm/">Checking a joint species distribution model</a></li>
</ul>
<details class="te-repro" data-pagefind-ignore="">
<summary>Reproducibility</summary>
<ul>
<li>Code last run: 2026-09-30</li>
<li>R version 4.5.3 (2026-03-11), aarch64-apple-darwin20</li>
<li>Packages: ggplot2 4.0.3, MASS 7.3-66</li>
</ul>
</details>


<!-- -->

</section>

 ]]></description>
  <category>R</category>
  <category>simulation</category>
  <category>statistics</category>
  <category>count data</category>
  <category>ecology tutorial</category>
  <guid isPermaLink="false">https://tidyecology.com/posts/simulating-correlated-variables/</guid>
  <pubDate>Mon, 28 Sep 2026 05:00:00 GMT</pubDate>
  <media:content url="https://tidyecology.com/posts/simulating-correlated-variables/thumbnail.png" medium="image" type="image/png" height="104" width="144"/>
</item>
<item>
  <title>Probability distributions in R: d, p, q and r</title>
  <dc:creator>Tidy Ecology</dc:creator>
  <link>https://tidyecology.com/posts/probability-distributions-in-r/</link>
  <description><![CDATA[ 





<p>A field protocol for a rare orchid says: revisit in June every quadrat that held at least three seedlings in April. The planning team knows from earlier years that seedlings are scattered at random at about 2.5 per quadrat, and wants to know how many of the 120 quadrats will need a second visit. Someone types <code>1 - ppois(3, 2.5)</code> into R, gets an answer, and books the field days. The answer is wrong by almost half, and nothing in R says so.</p>
<p>R handles every probability distribution with four functions that share a stem and differ in their first letter: <code>dpois()</code>, <code>ppois()</code>, <code>qpois()</code> and <code>rpois()</code> for the Poisson, and the same four letters in front of <code>binom</code>, <code>norm</code>, <code>nbinom</code>, <code>gamma</code>, <code>lnorm</code> and the rest. Much of the code on this site uses them, usually without comment. This post explains what each letter returns, measures a trap that is easy to fall into with counts, and then checks three places where R’s parameters are not the ones a textbook or another program may have taught you.</p>
<p><strong>The short answer.</strong> <code>d</code> gives the probability of exactly one value (for a count) or the height of the density curve (for a measurement). <code>p</code> gives the probability of a value at or below a cut-off. <code>q</code> runs <code>p</code> backwards: you give a probability and get the value. <code>r</code> draws random values. For “at least k” on a count, use <code>ppois(k - 1, lambda, lower.tail = FALSE)</code>, never <code>1 - ppois(k, lambda)</code>. And before trusting a distribution you have not used before, draw a large sample with its <code>r</code> function and compare the sample mean and variance with what you expect.</p>
<p>All data here are simulated or come straight from the distributions; every seed is in the code.</p>
<div class="cell">
<div class="code-copy-outer-scaffold"><div class="sourceCode cell-code" id="cb1" style="background: #f1f3f5;"><pre class="sourceCode r code-with-copy"><code class="sourceCode r"><span id="cb1-1"><span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">library</span>(ggplot2)</span>
<span id="cb1-2"></span>
<span id="cb1-3">te_paper  <span class="ot" style="color: #003B4F;
background-color: null;
font-style: inherit;">&lt;-</span> <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"#f5f4ee"</span></span>
<span id="cb1-4">te_ink    <span class="ot" style="color: #003B4F;
background-color: null;
font-style: inherit;">&lt;-</span> <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"#16241d"</span></span>
<span id="cb1-5">te_body   <span class="ot" style="color: #003B4F;
background-color: null;
font-style: inherit;">&lt;-</span> <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"#2c3a31"</span></span>
<span id="cb1-6">te_forest <span class="ot" style="color: #003B4F;
background-color: null;
font-style: inherit;">&lt;-</span> <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"#275139"</span></span>
<span id="cb1-7">te_rust   <span class="ot" style="color: #003B4F;
background-color: null;
font-style: inherit;">&lt;-</span> <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"#b5534e"</span></span>
<span id="cb1-8">te_gold   <span class="ot" style="color: #003B4F;
background-color: null;
font-style: inherit;">&lt;-</span> <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"#c9b458"</span></span>
<span id="cb1-9">te_line   <span class="ot" style="color: #003B4F;
background-color: null;
font-style: inherit;">&lt;-</span> <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"#dad9ca"</span></span>
<span id="cb1-10"></span>
<span id="cb1-11">theme_datasheet <span class="ot" style="color: #003B4F;
background-color: null;
font-style: inherit;">&lt;-</span> <span class="cf" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">function</span>() {</span>
<span id="cb1-12">  <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">theme_minimal</span>(<span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">base_size =</span> <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">12</span>) <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">+</span></span>
<span id="cb1-13">    <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">theme</span>(<span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">plot.background  =</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">element_rect</span>(<span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">fill =</span> te_paper, <span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">colour =</span> <span class="cn" style="color: #8f5902;
background-color: null;
font-style: inherit;">NA</span>),</span>
<span id="cb1-14">          <span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">panel.background =</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">element_rect</span>(<span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">fill =</span> te_paper, <span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">colour =</span> <span class="cn" style="color: #8f5902;
background-color: null;
font-style: inherit;">NA</span>),</span>
<span id="cb1-15">          <span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">panel.grid.major =</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">element_line</span>(<span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">colour =</span> te_line, <span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">linewidth =</span> <span class="fl" style="color: #AD0000;
background-color: null;
font-style: inherit;">0.3</span>),</span>
<span id="cb1-16">          <span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">panel.grid.minor =</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">element_blank</span>(),</span>
<span id="cb1-17">          <span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">text             =</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">element_text</span>(<span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">colour =</span> te_body),</span>
<span id="cb1-18">          <span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">axis.text        =</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">element_text</span>(<span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">colour =</span> te_body),</span>
<span id="cb1-19">          <span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">strip.text       =</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">element_text</span>(<span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">colour =</span> te_ink, <span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">face =</span> <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"bold"</span>))</span>
<span id="cb1-20">}</span></code></pre></div></div>
</div>
<section id="four-letters-one-stem" class="level2">
<h2 id="four-letters-one-stem-h" class="anchored" data-anchor-id="four-letters-one-stem">Four letters, one stem</h2>
<p>Take the orchid seedlings first. If they fall at random with a mean of 2.5 per quadrat, the count in one quadrat follows a Poisson distribution with <code>lambda = 2.5</code>. <code>dpois()</code> gives the probability of each exact count:</p>
<div class="cell">
<div class="code-copy-outer-scaffold"><div class="sourceCode cell-code" id="cb2" style="background: #f1f3f5;"><pre class="sourceCode r code-with-copy"><code class="sourceCode r"><span id="cb2-1">lambda <span class="ot" style="color: #003B4F;
background-color: null;
font-style: inherit;">&lt;-</span> <span class="fl" style="color: #AD0000;
background-color: null;
font-style: inherit;">2.5</span>                       <span class="co" style="color: #5E5E5E;
background-color: null;
font-style: inherit;"># mean seedlings per quadrat</span></span>
<span id="cb2-2"><span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">round</span>(<span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">dpois</span>(<span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">0</span><span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">:</span><span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">7</span>, lambda), <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">4</span>)</span></code></pre></div></div>
<div class="cell-output cell-output-stdout">
<pre><code>[1] 0.0821 0.2052 0.2565 0.2138 0.1336 0.0668 0.0278 0.0099</code></pre>
</div>
<div class="code-copy-outer-scaffold"><div class="sourceCode cell-code" id="cb4" style="background: #f1f3f5;"><pre class="sourceCode r code-with-copy"><code class="sourceCode r"><span id="cb4-1"><span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">sum</span>(<span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">dpois</span>(<span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">0</span><span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">:</span><span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">100</span>, lambda))           <span class="co" style="color: #5E5E5E;
background-color: null;
font-style: inherit;"># all the probabilities add up to one</span></span></code></pre></div></div>
<div class="cell-output cell-output-stdout">
<pre><code>[1] 1</code></pre>
</div>
</div>
<p>An empty quadrat has probability 0.082, a quadrat with exactly two seedlings 0.257. <code>ppois()</code> adds these up from zero to a cut-off, so it answers “at most”:</p>
<div class="cell">
<div class="code-copy-outer-scaffold"><div class="sourceCode cell-code" id="cb6" style="background: #f1f3f5;"><pre class="sourceCode r code-with-copy"><code class="sourceCode r"><span id="cb6-1"><span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">ppois</span>(<span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">2</span>, lambda)                    <span class="co" style="color: #5E5E5E;
background-color: null;
font-style: inherit;"># P(X &lt;= 2)</span></span></code></pre></div></div>
<div class="cell-output cell-output-stdout">
<pre><code>[1] 0.5438131</code></pre>
</div>
<div class="code-copy-outer-scaffold"><div class="sourceCode cell-code" id="cb8" style="background: #f1f3f5;"><pre class="sourceCode r code-with-copy"><code class="sourceCode r"><span id="cb8-1"><span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">sum</span>(<span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">dpois</span>(<span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">0</span><span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">:</span><span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">2</span>, lambda))             <span class="co" style="color: #5E5E5E;
background-color: null;
font-style: inherit;"># the same sum, written out</span></span></code></pre></div></div>
<div class="cell-output cell-output-stdout">
<pre><code>[1] 0.5438131</code></pre>
</div>
<div class="code-copy-outer-scaffold"><div class="sourceCode cell-code" id="cb10" style="background: #f1f3f5;"><pre class="sourceCode r code-with-copy"><code class="sourceCode r"><span id="cb10-1"><span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">stopifnot</span>(<span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">isTRUE</span>(<span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">all.equal</span>(<span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">ppois</span>(<span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">2</span>, lambda), <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">sum</span>(<span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">dpois</span>(<span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">0</span><span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">:</span><span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">2</span>, lambda)))))</span></code></pre></div></div>
</div>
<p>The chance that a quadrat holds at most two seedlings is 0.544. The “at most”, with the cut-off included, is the whole story of the trap in the next section.</p>
<p>The same letters work for any distribution. A newt that is present at a pond is detected on a single visit with probability 0.3, and the pond is visited five times. The number of visits with a detection is binomial, and <code>dbinom(0, ...)</code> is the chance of missing the newt on every visit:</p>
<div class="cell">
<div class="code-copy-outer-scaffold"><div class="sourceCode cell-code" id="cb11" style="background: #f1f3f5;"><pre class="sourceCode r code-with-copy"><code class="sourceCode r"><span id="cb11-1">visits <span class="ot" style="color: #003B4F;
background-color: null;
font-style: inherit;">&lt;-</span> <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">5</span></span>
<span id="cb11-2">p_det  <span class="ot" style="color: #003B4F;
background-color: null;
font-style: inherit;">&lt;-</span> <span class="fl" style="color: #AD0000;
background-color: null;
font-style: inherit;">0.3</span></span>
<span id="cb11-3"><span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">dbinom</span>(<span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">0</span>, <span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">size =</span> visits, <span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">prob =</span> p_det)     <span class="co" style="color: #5E5E5E;
background-color: null;
font-style: inherit;"># never detected in five visits</span></span></code></pre></div></div>
<div class="cell-output cell-output-stdout">
<pre><code>[1] 0.16807</code></pre>
</div>
<div class="code-copy-outer-scaffold"><div class="sourceCode cell-code" id="cb13" style="background: #f1f3f5;"><pre class="sourceCode r code-with-copy"><code class="sourceCode r"><span id="cb13-1"><span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">set.seed</span>(<span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">1014</span>)</span>
<span id="cb13-2">sim_det <span class="ot" style="color: #003B4F;
background-color: null;
font-style: inherit;">&lt;-</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">rbinom</span>(<span class="fl" style="color: #AD0000;
background-color: null;
font-style: inherit;">1e5</span>, <span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">size =</span> visits, <span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">prob =</span> p_det)</span>
<span id="cb13-3"><span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">mean</span>(sim_det <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">==</span> <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">0</span>)                         <span class="co" style="color: #5E5E5E;
background-color: null;
font-style: inherit;"># share of simulated ponds with no detection</span></span></code></pre></div></div>
<div class="cell-output cell-output-stdout">
<pre><code>[1] 0.16804</code></pre>
</div>
</div>
<p>An occupied pond is missed with probability 0.168, and in a hundred thousand simulated ponds 0.168 had no detection (the Monte Carlo standard error of that share, the typical size of the simulation noise, is 0.0012). This is the <code>r</code> letter’s everyday job: produce data from a known model so that you can check a formula, a model fit or a sampling design against it. <a href="https://tidyecology.com/posts/power-analysis-by-simulation/">Power analysis by simulation in R</a> builds a whole study design this way, and <a href="https://tidyecology.com/posts/reproducible-statistical-workflow/">A reproducible statistical workflow in R</a> explains where to put <code>set.seed()</code> so the draws come out the same every time.</p>
<p>For a measurement such as body length, <code>d</code> means something different. Here are adult newts with a mean total length of 0.10 m and a standard deviation of 0.008 m:</p>
<div class="cell">
<div class="code-copy-outer-scaffold"><div class="sourceCode cell-code" id="cb15" style="background: #f1f3f5;"><pre class="sourceCode r code-with-copy"><code class="sourceCode r"><span id="cb15-1"><span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">dnorm</span>(<span class="fl" style="color: #AD0000;
background-color: null;
font-style: inherit;">0.10</span>, <span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">mean =</span> <span class="fl" style="color: #AD0000;
background-color: null;
font-style: inherit;">0.10</span>, <span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">sd =</span> <span class="fl" style="color: #AD0000;
background-color: null;
font-style: inherit;">0.008</span>)                   <span class="co" style="color: #5E5E5E;
background-color: null;
font-style: inherit;"># length in metres</span></span></code></pre></div></div>
<div class="cell-output cell-output-stdout">
<pre><code>[1] 49.86779</code></pre>
</div>
<div class="code-copy-outer-scaffold"><div class="sourceCode cell-code" id="cb17" style="background: #f1f3f5;"><pre class="sourceCode r code-with-copy"><code class="sourceCode r"><span id="cb17-1"><span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">dnorm</span>(<span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">100</span>, <span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">mean =</span> <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">100</span>, <span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">sd =</span> <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">8</span>)                         <span class="co" style="color: #5E5E5E;
background-color: null;
font-style: inherit;"># the same newts in millimetres</span></span></code></pre></div></div>
<div class="cell-output cell-output-stdout">
<pre><code>[1] 0.04986779</code></pre>
</div>
<div class="code-copy-outer-scaffold"><div class="sourceCode cell-code" id="cb19" style="background: #f1f3f5;"><pre class="sourceCode r code-with-copy"><code class="sourceCode r"><span id="cb19-1"><span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">pnorm</span>(<span class="fl" style="color: #AD0000;
background-color: null;
font-style: inherit;">0.11</span>, <span class="fl" style="color: #AD0000;
background-color: null;
font-style: inherit;">0.10</span>, <span class="fl" style="color: #AD0000;
background-color: null;
font-style: inherit;">0.008</span>) <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">-</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">pnorm</span>(<span class="fl" style="color: #AD0000;
background-color: null;
font-style: inherit;">0.09</span>, <span class="fl" style="color: #AD0000;
background-color: null;
font-style: inherit;">0.10</span>, <span class="fl" style="color: #AD0000;
background-color: null;
font-style: inherit;">0.008</span>)    <span class="co" style="color: #5E5E5E;
background-color: null;
font-style: inherit;"># P(0.09 m &lt; length &lt; 0.11 m)</span></span></code></pre></div></div>
<div class="cell-output cell-output-stdout">
<pre><code>[1] 0.7887005</code></pre>
</div>
<div class="code-copy-outer-scaffold"><div class="sourceCode cell-code" id="cb21" style="background: #f1f3f5;"><pre class="sourceCode r code-with-copy"><code class="sourceCode r"><span id="cb21-1"><span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">pnorm</span>(<span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">110</span>, <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">100</span>, <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">8</span>) <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">-</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">pnorm</span>(<span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">90</span>, <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">100</span>, <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">8</span>)                 <span class="co" style="color: #5E5E5E;
background-color: null;
font-style: inherit;"># the same interval in millimetres</span></span></code></pre></div></div>
<div class="cell-output cell-output-stdout">
<pre><code>[1] 0.7887005</code></pre>
</div>
</div>
<p>The first line returns 49.9, which cannot be a probability. For a continuous variable <code>dnorm()</code> returns a density: probability per unit of the measurement, here per metre. A newt length is spread over a few centimetres, so the density per metre is large. Measured in millimetres the same newts give a density of 0.0499, a thousand times smaller, while the probability of a length between 9 and 11 cm is 0.789 in both units. Probabilities for a measurement always come from <code>pnorm()</code> differences, areas under the curve; the probability of any single exact length is zero. <code>qnorm()</code> and its relative <code>qt()</code> turn up whenever a confidence interval is built, which <a href="https://tidyecology.com/posts/standard-errors-confidence-intervals/">Standard errors and confidence intervals in R</a> covers.</p>
</section>
<section id="at-least-k-the-trap-with-counts" class="level2">
<h2 id="at-least-k-the-trap-with-counts-h" class="anchored" data-anchor-id="at-least-k-the-trap-with-counts">At least k: the trap with counts</h2>
<p>Back to the orchid protocol. The team wants P(X &gt;= 3), the chance a quadrat holds three or more seedlings. The habit many people bring from the normal distribution is “the upper tail is one minus <code>p</code>”, and it gives:</p>
<div class="cell">
<div class="code-copy-outer-scaffold"><div class="sourceCode cell-code" id="cb23" style="background: #f1f3f5;"><pre class="sourceCode r code-with-copy"><code class="sourceCode r"><span id="cb23-1">k <span class="ot" style="color: #003B4F;
background-color: null;
font-style: inherit;">&lt;-</span> <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">3</span></span>
<span id="cb23-2">wrong <span class="ot" style="color: #003B4F;
background-color: null;
font-style: inherit;">&lt;-</span> <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">1</span> <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">-</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">ppois</span>(k, lambda)                          <span class="co" style="color: #5E5E5E;
background-color: null;
font-style: inherit;"># P(X &gt; 3), i.e. at least 4</span></span>
<span id="cb23-3">right <span class="ot" style="color: #003B4F;
background-color: null;
font-style: inherit;">&lt;-</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">ppois</span>(k <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">-</span> <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">1</span>, lambda, <span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">lower.tail =</span> <span class="cn" style="color: #8f5902;
background-color: null;
font-style: inherit;">FALSE</span>)      <span class="co" style="color: #5E5E5E;
background-color: null;
font-style: inherit;"># P(X &gt; 2), i.e. at least 3</span></span>
<span id="cb23-4"><span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">c</span>(<span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">wrong =</span> wrong, <span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">right =</span> right)</span></code></pre></div></div>
<div class="cell-output cell-output-stdout">
<pre><code>    wrong     right 
0.2424239 0.4561869 </code></pre>
</div>
</div>
<p><code>ppois(k, lambda)</code> includes k itself, so one minus it is the chance of MORE than k: at least four seedlings, not at least three. The R help page for the Poisson says it in one line: with <code>lower.tail = TRUE</code> (the default) the probabilities are P(X &lt;= x), otherwise P(X &gt; x). To get “at least k” you ask for “more than k - 1”. The next chunk checks both statements and the size of the gap:</p>
<div class="cell">
<div class="code-copy-outer-scaffold"><div class="sourceCode cell-code" id="cb25" style="background: #f1f3f5;"><pre class="sourceCode r code-with-copy"><code class="sourceCode r"><span id="cb25-1"><span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">stopifnot</span>(</span>
<span id="cb25-2">  <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">isTRUE</span>(<span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">all.equal</span>(<span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">ppois</span>(k, lambda), <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">sum</span>(<span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">dpois</span>(<span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">0</span><span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">:</span>k, lambda)))),                    <span class="co" style="color: #5E5E5E;
background-color: null;
font-style: inherit;"># default: P(X &lt;= k)</span></span>
<span id="cb25-3">  <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">isTRUE</span>(<span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">all.equal</span>(<span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">ppois</span>(k, lambda, <span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">lower.tail =</span> <span class="cn" style="color: #8f5902;
background-color: null;
font-style: inherit;">FALSE</span>), <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">1</span> <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">-</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">ppois</span>(k, lambda))),   <span class="co" style="color: #5E5E5E;
background-color: null;
font-style: inherit;"># FALSE: P(X &gt; k)</span></span>
<span id="cb25-4">  <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">isTRUE</span>(<span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">all.equal</span>(right, <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">1</span> <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">-</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">ppois</span>(k <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">-</span> <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">1</span>, lambda))),</span>
<span id="cb25-5">  <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">isTRUE</span>(<span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">all.equal</span>(right <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">-</span> wrong, <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">dpois</span>(k, lambda)))                               <span class="co" style="color: #5E5E5E;
background-color: null;
font-style: inherit;"># the missing bar</span></span>
<span id="cb25-6">)</span>
<span id="cb25-7"><span class="co" style="color: #5E5E5E;
background-color: null;
font-style: inherit;"># relative error of the one-minus version for "at least 6"</span></span>
<span id="cb25-8">rel6 <span class="ot" style="color: #003B4F;
background-color: null;
font-style: inherit;">&lt;-</span> <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">100</span> <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">*</span> (<span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">1</span> <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">-</span> (<span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">1</span> <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">-</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">ppois</span>(<span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">6</span>, lambda)) <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">/</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">ppois</span>(<span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">5</span>, lambda, <span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">lower.tail =</span> <span class="cn" style="color: #8f5902;
background-color: null;
font-style: inherit;">FALSE</span>))</span>
<span id="cb25-9"><span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">stopifnot</span>(rel6 <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">&gt;</span> <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">100</span> <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">*</span> (<span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">1</span> <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">-</span> wrong <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">/</span> right))</span>
<span id="cb25-10"></span>
<span id="cb25-11"><span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">set.seed</span>(<span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">3014</span>)</span>
<span id="cb25-12">seedlings <span class="ot" style="color: #003B4F;
background-color: null;
font-style: inherit;">&lt;-</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">rpois</span>(<span class="fl" style="color: #AD0000;
background-color: null;
font-style: inherit;">1e6</span>, lambda)</span>
<span id="cb25-13">sim_at_least <span class="ot" style="color: #003B4F;
background-color: null;
font-style: inherit;">&lt;-</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">mean</span>(seedlings <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">&gt;=</span> k)</span>
<span id="cb25-14">sim_more     <span class="ot" style="color: #003B4F;
background-color: null;
font-style: inherit;">&lt;-</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">mean</span>(seedlings <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">&gt;</span> k)</span>
<span id="cb25-15">mcse <span class="ot" style="color: #003B4F;
background-color: null;
font-style: inherit;">&lt;-</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">sqrt</span>(sim_at_least <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">*</span> (<span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">1</span> <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">-</span> sim_at_least) <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">/</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">length</span>(seedlings))</span>
<span id="cb25-16"><span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">round</span>(<span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">c</span>(<span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">simulated_at_least =</span> sim_at_least, <span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">simulated_more_than =</span> sim_more, <span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">mc_se =</span> mcse), <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">4</span>)</span></code></pre></div></div>
<div class="cell-output cell-output-stdout">
<pre><code> simulated_at_least simulated_more_than               mc_se 
             0.4560              0.2423              0.0005 </code></pre>
</div>
</div>
<p>The correct chance is 0.456; the one-minus version gives 0.242, 47 per cent too low. A million simulated quadrats settle which is which: 0.456 of them hold at least three seedlings (Monte Carlo standard error 0.0005), and 0.242 hold more than three. The gap between the two answers is exactly the probability of k itself, <code>dpois(3, 2.5)</code> = 0.214: the wrong formula leaves out the bar at three. A Poisson distribution peaks near its mean, so the missing bar, the absolute error, is largest when the threshold is close to the mean count, as it is here. In relative terms the error grows further out: for at least 6 seedlings the one-minus version is 66 per cent too low.</p>
<div class="cell">
<div class="cell-output-display">
<div id="fig-at-least" class="quarto-float quarto-figure quarto-figure-center anchored" alt="Bar chart of Poisson probabilities for 0 to 10 seedlings per quadrat, each bar labelled with its value. Bars for 0, 1 and 2 (0.082, 0.205, 0.257) are pale grey, the bar for exactly 3 (0.214) is red, and the bars for 4 to 10 (0.134 falling to 0.000) are dark green. A legend on top names the three groups, and text at the right reads at least 3 = 0.456 in green and 1 - ppois(3, 2.5) = 0.242 in red.">
<figure class="quarto-float quarto-float-fig figure">
<div aria-describedby="fig-at-least-caption-0ceaefa1-69ba-4598-a22c-09a6ac19f8ca">
<img src="https://tidyecology.com/posts/probability-distributions-in-r/index_files/figure-html/fig-at-least-1.png" class="img-fluid figure-img" alt="Bar chart of Poisson probabilities for 0 to 10 seedlings per quadrat, each bar labelled with its value. Bars for 0, 1 and 2 (0.082, 0.205, 0.257) are pale grey, the bar for exactly 3 (0.214) is red, and the bars for 4 to 10 (0.134 falling to 0.000) are dark green. A legend on top names the three groups, and text at the right reads at least 3 = 0.456 in green and 1 - ppois(3, 2.5) = 0.242 in red." width="720">
</div>
<figcaption class="quarto-float-caption-bottom quarto-float-caption quarto-float-fig" id="fig-at-least-caption-0ceaefa1-69ba-4598-a22c-09a6ac19f8ca">
Figure&nbsp;1: Poisson probabilities for seedlings per quadrat at a mean of 2.5. The correct ‘at least 3’ sums the bars from 3 upwards; one minus ppois(3, 2.5) sums only the bars from 4 upwards and leaves out the tallest bar of the tail, the one at exactly 3.
</figcaption>
</figure>
</div>
</div>
</div>
<p>For the protocol, the expected number of revisits is the number of quadrats times the probability:</p>
<div class="cell">
<div class="code-copy-outer-scaffold"><div class="sourceCode cell-code" id="cb27" style="background: #f1f3f5;"><pre class="sourceCode r code-with-copy"><code class="sourceCode r"><span id="cb27-1">n_quadrats <span class="ot" style="color: #003B4F;
background-color: null;
font-style: inherit;">&lt;-</span> <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">120</span></span>
<span id="cb27-2"><span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">round</span>(<span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">c</span>(<span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">booked_with_wrong =</span> n_quadrats <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">*</span> wrong, <span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">needed =</span> n_quadrats <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">*</span> right), <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">1</span>)</span></code></pre></div></div>
<div class="cell-output cell-output-stdout">
<pre><code>booked_with_wrong            needed 
             29.1              54.7 </code></pre>
</div>
</div>
<p>The team would plan for 29 revisits and meet about 55. The same slip appears in every “at least” with a discrete count: a detection rule, a minimum group size, a threshold number of nests. With the newt data, “call a pond occupied if the newt is detected on at least two of five visits” needs <code>pbinom(1, 5, 0.3, lower.tail = FALSE)</code>:</p>
<div class="cell">
<div class="code-copy-outer-scaffold"><div class="sourceCode cell-code" id="cb29" style="background: #f1f3f5;"><pre class="sourceCode r code-with-copy"><code class="sourceCode r"><span id="cb29-1">occ_wrong <span class="ot" style="color: #003B4F;
background-color: null;
font-style: inherit;">&lt;-</span> <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">1</span> <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">-</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">pbinom</span>(<span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">2</span>, visits, p_det)</span>
<span id="cb29-2">occ_right <span class="ot" style="color: #003B4F;
background-color: null;
font-style: inherit;">&lt;-</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">pbinom</span>(<span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">1</span>, visits, p_det, <span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">lower.tail =</span> <span class="cn" style="color: #8f5902;
background-color: null;
font-style: inherit;">FALSE</span>)</span>
<span id="cb29-3"><span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">c</span>(<span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">wrong =</span> occ_wrong, <span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">right =</span> occ_right)</span></code></pre></div></div>
<div class="cell-output cell-output-stdout">
<pre><code>  wrong   right 
0.16308 0.47178 </code></pre>
</div>
<div class="code-copy-outer-scaffold"><div class="sourceCode cell-code" id="cb31" style="background: #f1f3f5;"><pre class="sourceCode r code-with-copy"><code class="sourceCode r"><span id="cb31-1"><span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">stopifnot</span>(<span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">isTRUE</span>(<span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">all.equal</span>(occ_right <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">-</span> occ_wrong, <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">dbinom</span>(<span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">2</span>, visits, p_det))),</span>
<span id="cb31-2">          <span class="co" style="color: #5E5E5E;
background-color: null;
font-style: inherit;"># the negative binomial follows the same rule</span></span>
<span id="cb31-3">          <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">isTRUE</span>(<span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">all.equal</span>(<span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">pnbinom</span>(<span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">2</span>, <span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">size =</span> <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">2</span>, <span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">mu =</span> <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">3</span>, <span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">lower.tail =</span> <span class="cn" style="color: #8f5902;
background-color: null;
font-style: inherit;">FALSE</span>),</span>
<span id="cb31-4">                           <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">1</span> <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">-</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">sum</span>(<span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">dnbinom</span>(<span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">0</span><span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">:</span><span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">2</span>, <span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">size =</span> <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">2</span>, <span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">mu =</span> <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">3</span>)))))</span></code></pre></div></div>
</div>
<p>An occupied pond passes the rule with probability 0.472; the one-minus version says 0.163, the chance of at least three detections.</p>
<p>For a normal or any other continuous distribution the slip does no harm, because a single value has probability zero and “more than” equals “at least”. That is how the habit forms. With counts it matters every time.</p>
<p><code>lower.tail = FALSE</code> has a second use. For a far tail, <code>1 - ppois()</code> subtracts a number that is almost one from one, and floating-point arithmetic loses the answer:</p>
<div class="cell">
<div class="code-copy-outer-scaffold"><div class="sourceCode cell-code" id="cb32" style="background: #f1f3f5;"><pre class="sourceCode r code-with-copy"><code class="sourceCode r"><span id="cb32-1"><span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">c</span>(<span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">one_minus =</span> <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">1</span> <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">-</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">ppois</span>(<span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">30</span>, lambda), <span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">lower_tail =</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">ppois</span>(<span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">30</span>, lambda, <span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">lower.tail =</span> <span class="cn" style="color: #8f5902;
background-color: null;
font-style: inherit;">FALSE</span>))</span></code></pre></div></div>
<div class="cell-output cell-output-stdout">
<pre><code>  one_minus  lower_tail 
0.00000e+00 2.34756e-23 </code></pre>
</div>
<div class="code-copy-outer-scaffold"><div class="sourceCode cell-code" id="cb34" style="background: #f1f3f5;"><pre class="sourceCode r code-with-copy"><code class="sourceCode r"><span id="cb34-1"><span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">stopifnot</span>(<span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">1</span> <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">-</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">ppois</span>(<span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">30</span>, lambda) <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">==</span> <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">0</span>, <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">ppois</span>(<span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">30</span>, lambda, <span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">lower.tail =</span> <span class="cn" style="color: #8f5902;
background-color: null;
font-style: inherit;">FALSE</span>) <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">&gt;</span> <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">0</span>)</span></code></pre></div></div>
</div>
<p>The one-minus form returns exactly zero, while <code>lower.tail = FALSE</code> returns <img src="https://latex.codecogs.com/png.latex?2.35%20%5Ctimes%2010%5E%7B-23%7D">. A zero probability inside a likelihood becomes minus infinity on the log scale, so for tail probabilities the argument is the safer habit anyway.</p>
</section>
<section id="quantiles-of-a-count-jump-in-steps" class="level2">
<h2 id="quantiles-of-a-count-jump-in-steps-h" class="anchored" data-anchor-id="quantiles-of-a-count-jump-in-steps">Quantiles of a count jump in steps</h2>
<p><code>qpois()</code> runs the other way: give it a probability, get back a count. The help page defines it as the smallest integer x with P(X &lt;= x) &gt;= p.&nbsp;For a count that is not the same as “the value with 95 per cent below it”:</p>
<div class="cell">
<div class="code-copy-outer-scaffold"><div class="sourceCode cell-code" id="cb35" style="background: #f1f3f5;"><pre class="sourceCode r code-with-copy"><code class="sourceCode r"><span id="cb35-1">q95 <span class="ot" style="color: #003B4F;
background-color: null;
font-style: inherit;">&lt;-</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">qpois</span>(<span class="fl" style="color: #AD0000;
background-color: null;
font-style: inherit;">0.95</span>, lambda)</span>
<span id="cb35-2"><span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">round</span>(<span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">c</span>(<span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">q95 =</span> q95, <span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">P_at_most_q95 =</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">ppois</span>(q95, lambda), <span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">P_at_most_one_less =</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">ppois</span>(q95 <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">-</span> <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">1</span>, lambda)), <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">4</span>)</span></code></pre></div></div>
<div class="cell-output cell-output-stdout">
<pre><code>               q95      P_at_most_q95 P_at_most_one_less 
            5.0000             0.9580             0.8912 </code></pre>
</div>
<div class="code-copy-outer-scaffold"><div class="sourceCode cell-code" id="cb37" style="background: #f1f3f5;"><pre class="sourceCode r code-with-copy"><code class="sourceCode r"><span id="cb37-1"><span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">stopifnot</span>(<span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">ppois</span>(q95, lambda) <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">&gt;=</span> <span class="fl" style="color: #AD0000;
background-color: null;
font-style: inherit;">0.95</span>, <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">ppois</span>(q95 <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">-</span> <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">1</span>, lambda) <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">&lt;</span> <span class="fl" style="color: #AD0000;
background-color: null;
font-style: inherit;">0.95</span>,</span>
<span id="cb37-2">          <span class="co" style="color: #5E5E5E;
background-color: null;
font-style: inherit;"># a central 90 per cent interval from qpois() covers at least 0.90</span></span>
<span id="cb37-3">          <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">ppois</span>(q95, lambda) <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">-</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">ppois</span>(<span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">qpois</span>(<span class="fl" style="color: #AD0000;
background-color: null;
font-style: inherit;">0.05</span>, lambda) <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">-</span> <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">1</span>, lambda) <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">&gt;=</span> <span class="fl" style="color: #AD0000;
background-color: null;
font-style: inherit;">0.90</span>)</span></code></pre></div></div>
</div>
<p>The 95th percentile of seedlings per quadrat is 5, but P(X &lt;= 5) is 0.958, not 0.95; one seedling lower, P(X &lt;= 4) is only 0.891. No count sits at exactly 0.95, because the cumulative probability jumps from one step to the next, and <code>qpois()</code> returns the first step that reaches the target. An interval built from <code>qpois()</code> or <code>qnbinom()</code> quantiles, as in the prediction band of <a href="https://tidyecology.com/posts/glm-count-data-abundance/">Poisson and negative binomial GLMs in R</a>, therefore covers at least its nominal share of the fitted distribution, and often more (estimation error in the fitted mean is a separate matter). If the exact coverage matters, report <code>ppois()</code> at the returned value next to it.</p>
<div class="cell">
<div class="cell-output-display">
<div id="fig-quantile" class="quarto-float quarto-figure quarto-figure-center anchored" alt="Step plot of the cumulative Poisson probability P(X <= x) for 0 to 9 seedlings: dark green points with horizontal steps rising from 0.08 at zero to almost 1. A dashed red line marks the 0.95 target. A gold point at 4 sits below the line and is labelled P(X <= 4) = 0.891; a red point at 5 sits just above it and is labelled qpois(0.95, 2.5) = 5, P(X <= 5) = 0.958.">
<figure class="quarto-float quarto-float-fig figure">
<div aria-describedby="fig-quantile-caption-0ceaefa1-69ba-4598-a22c-09a6ac19f8ca">
<img src="https://tidyecology.com/posts/probability-distributions-in-r/index_files/figure-html/fig-quantile-1.png" class="img-fluid figure-img" alt="Step plot of the cumulative Poisson probability P(X <= x) for 0 to 9 seedlings: dark green points with horizontal steps rising from 0.08 at zero to almost 1. A dashed red line marks the 0.95 target. A gold point at 4 sits below the line and is labelled P(X <= 4) = 0.891; a red point at 5 sits just above it and is labelled qpois(0.95, 2.5) = 5, P(X <= 5) = 0.958." width="720">
</div>
<figcaption class="quarto-float-caption-bottom quarto-float-caption quarto-float-fig" id="fig-quantile-caption-0ceaefa1-69ba-4598-a22c-09a6ac19f8ca">
Figure&nbsp;2: Cumulative Poisson probability for seedlings per quadrat at a mean of 2.5. The dashed line is the 0.95 target. qpois(0.95, 2.5) returns the first count whose step reaches the line, and the probability at that count is above 0.95.
</figcaption>
</figure>
</div>
</div>
</div>
</section>
<section id="parameters-that-differ-from-the-textbook" class="level2">
<h2 id="parameters-that-differ-from-the-textbook-h" class="anchored" data-anchor-id="parameters-that-differ-from-the-textbook">Parameters that differ from the textbook</h2>
<p>The functions agree on their letters; they do not all agree with other software on their parameters (Bolker 2008, chapter 4, sets out these parameterisations for ecologists). Three cases catch ecologists often enough to check by simulation, each with a hundred thousand draws.</p>
<p><strong>Negative binomial.</strong> <code>rnbinom()</code> takes either <code>size</code> and <code>prob</code> or <code>size</code> and <code>mu</code>. In the <code>prob</code> form the help page describes the number of failures before <code>size</code> successes, with mean size (1 - prob) / prob; <code>prob</code> is not the probability of anything you counted in the field. The <code>mu</code> form, the one ecologists use for aggregated counts, sets the mean directly, and the variance is mu + mu^2 / size, so <code>size</code> is the aggregation parameter k (small <code>size</code>, strong clumping; how badly k is estimated from few samples is the subject of <a href="https://tidyecology.com/posts/negative-binomial-k-from-small-samples/">Negative binomial k from small host samples</a>). The two forms describe the same distribution when prob = size / (size + mu):</p>
<div class="cell">
<div class="code-copy-outer-scaffold"><div class="sourceCode cell-code" id="cb38" style="background: #f1f3f5;"><pre class="sourceCode r code-with-copy"><code class="sourceCode r"><span id="cb38-1">nb_size <span class="ot" style="color: #003B4F;
background-color: null;
font-style: inherit;">&lt;-</span> <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">2</span>; nb_mu <span class="ot" style="color: #003B4F;
background-color: null;
font-style: inherit;">&lt;-</span> <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">3</span></span>
<span id="cb38-2">nb_prob <span class="ot" style="color: #003B4F;
background-color: null;
font-style: inherit;">&lt;-</span> nb_size <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">/</span> (nb_size <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">+</span> nb_mu)</span>
<span id="cb38-3"><span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">set.seed</span>(<span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">2014</span>)</span>
<span id="cb38-4">draws_prob <span class="ot" style="color: #003B4F;
background-color: null;
font-style: inherit;">&lt;-</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">rnbinom</span>(<span class="fl" style="color: #AD0000;
background-color: null;
font-style: inherit;">1e5</span>, <span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">size =</span> nb_size, <span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">prob =</span> nb_prob)</span>
<span id="cb38-5">draws_mu   <span class="ot" style="color: #003B4F;
background-color: null;
font-style: inherit;">&lt;-</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">rnbinom</span>(<span class="fl" style="color: #AD0000;
background-color: null;
font-style: inherit;">1e5</span>, <span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">size =</span> nb_size, <span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">mu =</span> nb_mu)</span>
<span id="cb38-6">nb_check <span class="ot" style="color: #003B4F;
background-color: null;
font-style: inherit;">&lt;-</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">rbind</span>(</span>
<span id="cb38-7">  <span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">stated_prob_form =</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">c</span>(<span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">mean =</span> nb_size <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">*</span> (<span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">1</span> <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">-</span> nb_prob) <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">/</span> nb_prob, <span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">var =</span> nb_size <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">*</span> (<span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">1</span> <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">-</span> nb_prob) <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">/</span> nb_prob<span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">^</span><span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">2</span>),</span>
<span id="cb38-8">  <span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">simulated_prob   =</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">c</span>(<span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">mean</span>(draws_prob), <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">var</span>(draws_prob)),</span>
<span id="cb38-9">  <span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">stated_mu_form   =</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">c</span>(nb_mu, nb_mu <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">+</span> nb_mu<span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">^</span><span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">2</span> <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">/</span> nb_size),</span>
<span id="cb38-10">  <span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">simulated_mu     =</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">c</span>(<span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">mean</span>(draws_mu), <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">var</span>(draws_mu)))</span>
<span id="cb38-11"><span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">round</span>(nb_check, <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">3</span>)</span></code></pre></div></div>
<div class="cell-output cell-output-stdout">
<pre><code>                  mean   var
stated_prob_form 3.000 7.500
simulated_prob   3.005 7.465
stated_mu_form   3.000 7.500
simulated_mu     3.001 7.491</code></pre>
</div>
<div class="code-copy-outer-scaffold"><div class="sourceCode cell-code" id="cb40" style="background: #f1f3f5;"><pre class="sourceCode r code-with-copy"><code class="sourceCode r"><span id="cb40-1"><span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">stopifnot</span>(<span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">isTRUE</span>(<span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">all.equal</span>(nb_check[<span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"stated_prob_form"</span>, ], nb_check[<span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"stated_mu_form"</span>, ], <span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">check.attributes =</span> <span class="cn" style="color: #8f5902;
background-color: null;
font-style: inherit;">FALSE</span>)),</span>
<span id="cb40-2">          <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">isTRUE</span>(<span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">all.equal</span>(<span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">dnbinom</span>(<span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">0</span><span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">:</span><span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">20</span>, <span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">size =</span> nb_size, <span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">prob =</span> nb_prob),</span>
<span id="cb40-3">                           <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">dnbinom</span>(<span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">0</span><span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">:</span><span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">20</span>, <span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">size =</span> nb_size, <span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">mu =</span> nb_mu))))</span></code></pre></div></div>
</div>
<p>With <code>size = 2</code>, <code>prob = 0.4</code> in one form and <code>mu = 3</code> in the other, both help-page formulas give a mean of 3.0 and a variance of 7.5. The <code>prob</code> draws average 3.005 with variance 7.47, and the <code>mu</code> draws 3.001 with variance 7.49. Some texts and programs count successes instead of failures, or write the variance as a linear rather than quadratic function of the mean (Linden and Mantyniemi 2011 give a negative binomial with two overdispersion parameters that covers these different mean-variance relationships for ecological counts), so a k or a p copied from elsewhere may mean something else in R.</p>
<p><strong>Gamma.</strong> <code>rgamma()</code> has a <code>rate</code> and a <code>scale</code>, one the inverse of the other, and the third position in the argument list belongs to <code>rate</code>. Code written as <code>rgamma(n, 2, 0.5)</code> by someone who thinks in shape and scale gets a rate of 0.5, which is a scale of 2:</p>
<div class="cell">
<div class="code-copy-outer-scaffold"><div class="sourceCode cell-code" id="cb41" style="background: #f1f3f5;"><pre class="sourceCode r code-with-copy"><code class="sourceCode r"><span id="cb41-1"><span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">stopifnot</span>(<span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">identical</span>(<span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">names</span>(<span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">formals</span>(rgamma))[<span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">1</span><span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">:</span><span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">4</span>], <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">c</span>(<span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"n"</span>, <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"shape"</span>, <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"rate"</span>, <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"scale"</span>)))</span>
<span id="cb41-2"><span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">set.seed</span>(<span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">4014</span>)</span>
<span id="cb41-3">g_positional <span class="ot" style="color: #003B4F;
background-color: null;
font-style: inherit;">&lt;-</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">rgamma</span>(<span class="fl" style="color: #AD0000;
background-color: null;
font-style: inherit;">1e5</span>, <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">2</span>, <span class="fl" style="color: #AD0000;
background-color: null;
font-style: inherit;">0.5</span>)                   <span class="co" style="color: #5E5E5E;
background-color: null;
font-style: inherit;"># read by R as shape = 2, rate = 0.5</span></span>
<span id="cb41-4">g_scale      <span class="ot" style="color: #003B4F;
background-color: null;
font-style: inherit;">&lt;-</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">rgamma</span>(<span class="fl" style="color: #AD0000;
background-color: null;
font-style: inherit;">1e5</span>, <span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">shape =</span> <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">2</span>, <span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">scale =</span> <span class="fl" style="color: #AD0000;
background-color: null;
font-style: inherit;">0.5</span>)   <span class="co" style="color: #5E5E5E;
background-color: null;
font-style: inherit;"># what a shape-scale reader meant</span></span>
<span id="cb41-5">gamma_check <span class="ot" style="color: #003B4F;
background-color: null;
font-style: inherit;">&lt;-</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">rbind</span>(</span>
<span id="cb41-6">  <span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">positional =</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">c</span>(<span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">stated_mean =</span> <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">2</span> <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">/</span> <span class="fl" style="color: #AD0000;
background-color: null;
font-style: inherit;">0.5</span>, <span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">mean =</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">mean</span>(g_positional), <span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">stated_var =</span> <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">2</span> <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">/</span> <span class="fl" style="color: #AD0000;
background-color: null;
font-style: inherit;">0.5</span><span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">^</span><span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">2</span>, <span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">var =</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">var</span>(g_positional)),</span>
<span id="cb41-7">  <span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">scale_0.5  =</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">c</span>(<span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">2</span> <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">*</span> <span class="fl" style="color: #AD0000;
background-color: null;
font-style: inherit;">0.5</span>, <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">mean</span>(g_scale), <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">2</span> <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">*</span> <span class="fl" style="color: #AD0000;
background-color: null;
font-style: inherit;">0.5</span><span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">^</span><span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">2</span>, <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">var</span>(g_scale)))</span>
<span id="cb41-8"><span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">round</span>(gamma_check, <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">3</span>)</span></code></pre></div></div>
<div class="cell-output cell-output-stdout">
<pre><code>           stated_mean  mean stated_var   var
positional           4 4.004        8.0 8.035
scale_0.5            1 1.002        0.5 0.498</code></pre>
</div>
</div>
<p>The mean is shape times scale, so the positional call averages 4.00 and the named <code>scale = 0.5</code> call 1.00: a fourfold difference from one unnamed argument. Naming every parameter (<code>shape =</code>, <code>rate =</code> or <code>scale =</code>) removes the question.</p>
<p><strong>Lognormal.</strong> <code>rlnorm(n, meanlog, sdlog)</code> takes the mean and standard deviation of the LOG of the variable. <code>exp(meanlog)</code> is the median, not the mean; the mean is exp(meanlog + sdlog^2 / 2):</p>
<div class="cell">
<div class="code-copy-outer-scaffold"><div class="sourceCode cell-code" id="cb43" style="background: #f1f3f5;"><pre class="sourceCode r code-with-copy"><code class="sourceCode r"><span id="cb43-1"><span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">set.seed</span>(<span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">5014</span>)</span>
<span id="cb43-2">ml <span class="ot" style="color: #003B4F;
background-color: null;
font-style: inherit;">&lt;-</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">log</span>(<span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">10</span>); sl <span class="ot" style="color: #003B4F;
background-color: null;
font-style: inherit;">&lt;-</span> <span class="fl" style="color: #AD0000;
background-color: null;
font-style: inherit;">0.8</span></span>
<span id="cb43-3">lengths_ln <span class="ot" style="color: #003B4F;
background-color: null;
font-style: inherit;">&lt;-</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">rlnorm</span>(<span class="fl" style="color: #AD0000;
background-color: null;
font-style: inherit;">1e5</span>, <span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">meanlog =</span> ml, <span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">sdlog =</span> sl)</span>
<span id="cb43-4"><span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">round</span>(<span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">c</span>(<span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">exp_meanlog =</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">exp</span>(ml), <span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">sim_median =</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">median</span>(lengths_ln),</span>
<span id="cb43-5">        <span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">stated_mean =</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">exp</span>(ml <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">+</span> sl<span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">^</span><span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">2</span> <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">/</span> <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">2</span>), <span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">sim_mean =</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">mean</span>(lengths_ln)), <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">3</span>)</span></code></pre></div></div>
<div class="cell-output cell-output-stdout">
<pre><code>exp_meanlog  sim_median stated_mean    sim_mean 
     10.000       9.947      13.771      13.698 </code></pre>
</div>
</div>
<p>With <code>meanlog = log(10)</code> and <code>sdlog = 0.8</code>, the draws have a median of 9.95 and a mean of 13.70 against a stated mean of 13.77. What this does to predictions from a model fitted on the log scale is the subject of <a href="https://tidyecology.com/posts/back-transforming-a-log-model/">Back-transforming a log-scale model</a>.</p>
<p>The check in all three cases is the same few lines: draw a hundred thousand values, and compare <code>mean()</code> and <code>var()</code> (or the median and mean, for the lognormal) with the formula on the help page. It takes a second and it settles what the parameters mean in the version of R you are running.</p>
</section>
<section id="what-to-check-in-your-own-data" class="level2">
<h2 id="what-to-check-in-your-own-data-h" class="anchored" data-anchor-id="what-to-check-in-your-own-data">What to check in your own data</h2>
<p>Every time you write “at least” with a count, look for a <code>- 1</code> or a <code>lower.tail = FALSE</code> with <code>k - 1</code>. If you find <code>1 - ppois(k, ...)</code>, <code>1 - pbinom(k, ...)</code> or <code>1 - pnbinom(k, ...)</code>, you are computing “more than k”.</p>
<p>When a threshold rule, a detection rule or a power calculation rests on a tail probability, check it against a simulation with the matching <code>r</code> function: <code>mean(rpois(1e6, lambda) &gt;= k)</code> takes a moment and catches the off-by-one immediately.</p>
<p>When you report a quantile or an interval for a count, add the actual probability at the returned value with the <code>p</code> function, since it will not be exactly the nominal one.</p>
<p>Name the parameters of every <code>r</code>, <code>d</code>, <code>p</code> and <code>q</code> call for distributions with more than one parameterisation (<code>size</code>, <code>prob</code>, <code>mu</code>, <code>shape</code>, <code>rate</code>, <code>scale</code>), and when you take a parameter value from a paper or another program, find out which form it used before you plug it in.</p>
</section>
<section id="honest-limits" class="level2">
<h2 id="honest-limits-h" class="anchored" data-anchor-id="honest-limits">Honest limits</h2>
<p>The trap is measured for the Poisson and the binomial, and the lower-tail rule is checked once for the negative binomial; the other discrete distributions in R document the same P(X &lt;= x) convention, but the post does not test each of them. The post covers six families and three parameterisation traps and leaves out many others (the Weibull, the beta, the truncated and zero-inflated forms that need extra packages). The simulation checks confirm means, variances and one median, not the full shape of a distribution. And a correct probability is only as good as the model under it: real seedlings are rarely scattered as a Poisson process, and if they are clumped the at-least-three share is different again.</p>
</section>
<section id="references" class="level2">
<h2 id="references-h" class="anchored" data-anchor-id="references">References</h2>
<p>Bolker BM 2008 Ecological Models and Data in R, chapter 4 (ISBN 978-0-691-12522-0)</p>
<p>Linden A, Mantyniemi S 2011 Ecology 92(7):1414-1421 (<a href="https://doi.org/10.1890/10-1831.1">10.1890/10-1831.1</a>)</p>
<p>R Core Team 2024 R documentation: The Poisson distribution (https://stat.ethz.ch/R-manual/R-devel/library/stats/html/Poisson.html)</p>
<p>R Core Team 2024 R documentation: The negative binomial distribution (https://stat.ethz.ch/R-manual/R-devel/library/stats/html/NegBinomial.html)</p>
<p>R Core Team 2024 R documentation: The gamma distribution (https://stat.ethz.ch/R-manual/R-devel/library/stats/html/GammaDist.html)</p>
</section>
<section id="related-tutorials" class="level2">
<h2 id="related-tutorials-h" class="anchored" data-anchor-id="related-tutorials">Related tutorials</h2>
<ul>
<li><a href="https://tidyecology.com/posts/power-analysis-by-simulation/">Power analysis by simulation in R</a></li>
<li><a href="https://tidyecology.com/posts/glm-count-data-abundance/">Poisson and negative binomial GLMs in R</a></li>
<li><a href="https://tidyecology.com/posts/standard-errors-confidence-intervals/">Standard errors and confidence intervals in R</a></li>
<li><a href="https://tidyecology.com/posts/simulating-correlated-variables/">Simulating correlated variables in R</a></li>
</ul>
<details class="te-repro" data-pagefind-ignore="">
<summary>Reproducibility</summary>
<ul>
<li>Code last run: 2026-09-30</li>
<li>R version 4.5.3 (2026-03-11), aarch64-apple-darwin20</li>
<li>Packages: ggplot2 4.0.3</li>
</ul>
</details>


<!-- -->

</section>

 ]]></description>
  <category>R</category>
  <category>statistics</category>
  <category>count data</category>
  <category>simulation</category>
  <category>ecology tutorial</category>
  <guid isPermaLink="false">https://tidyecology.com/posts/probability-distributions-in-r/</guid>
  <pubDate>Sun, 27 Sep 2026 11:00:00 GMT</pubDate>
  <media:content url="https://tidyecology.com/posts/probability-distributions-in-r/thumbnail.png" medium="image" type="image/png" height="104" width="144"/>
</item>
<item>
  <title>Repeating an analysis for every site in R</title>
  <dc:creator>Tidy Ecology</dc:creator>
  <link>https://tidyecology.com/posts/repeating-an-analysis-for-every-site/</link>
  <description><![CDATA[ 





<p>Thirty sites in a monitoring scheme, ten years of counts at each, and a request for the trend at every site. The first version of the script fits the model for site 1, then the block is copied and the 1 becomes a 2. By site 12 one of the copies has a typo in it, and nothing says so. Why copies drift apart, and what it costs, is measured in <a href="https://tidyecology.com/posts/turning-your-code-into-a-package/">Turning your code into an R package</a>. This post is about the step before that: writing the analysis once and running it for every site.</p>
<p>Running it is the easy part. R has several ways to repeat a function over groups, and the differences that matter here are not about speed but about what each one does when a site is unusual. That is where the plausible wrong numbers come from: a result that changes shape because one site had a tie, a loop that runs even when there is nothing to loop over, and a summary that quietly leaves out the sites where the model failed. Each of those is shown below on one simulated survey, measured, and then fixed.</p>
<p>Speed is a separate question with its own post, <a href="https://tidyecology.com/posts/speeding-up-analysis-code/">Speeding up your analysis code</a>; here every loop is quick, and the question is only whether its answer is right. If all you need is one number per group, such as a mean, <a href="https://tidyecology.com/posts/grouped-summaries-in-r/">Summarising ecological data by group</a> covers <code>group_by()</code> and <code>summarise()</code>.</p>
<section id="the-short-answer" class="level2">
<h2 id="the-short-answer-h" class="anchored" data-anchor-id="the-short-answer">The short answer</h2>
<p>Write a function that does the analysis for one site and returns one row, or one number. Run it on a single site and read the result. Then split the data by site and apply the function to every piece with <code>lapply()</code> or <code>purrr::map()</code>, and bind the rows together. When each site returns one number, use <code>vapply()</code> or <code>purrr::map_dbl()</code> instead of <code>sapply()</code>, because they stop when a site returns something else. Loop over <code>seq_along(x)</code>, never <code>1:length(x)</code>. And when a site can fail, keep it in the output as <code>NA</code> with its name, so the failures can be counted and looked at before anything is averaged.</p>
</section>
<section id="the-survey" class="level2">
<h2 id="the-survey-h" class="anchored" data-anchor-id="the-survey">The survey</h2>
<p>The data are simulated, so that we know the true trend at every site and can score each answer against it. Each site enters the scheme in 2015 with its own expected count and then changes by its own fixed rate per year. The counts are Poisson around that expectation. In your own data you never see the <code>true_trend</code> column; here it is the answer key.</p>
<div class="cell">
<div class="code-copy-outer-scaffold"><div class="sourceCode cell-code" id="cb1" style="background: #f1f3f5;"><pre class="sourceCode r code-with-copy"><code class="sourceCode r"><span id="cb1-1"><span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">library</span>(dplyr)</span>
<span id="cb1-2"><span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">library</span>(purrr)</span>
<span id="cb1-3"><span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">library</span>(ggplot2)</span></code></pre></div></div>
</div>
<div class="cell">
<div class="code-copy-outer-scaffold"><div class="sourceCode cell-code" id="cb2" style="background: #f1f3f5;"><pre class="sourceCode r code-with-copy"><code class="sourceCode r"><span id="cb2-1"><span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">set.seed</span>(<span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">2026</span>)</span>
<span id="cb2-2">n_site <span class="ot" style="color: #003B4F;
background-color: null;
font-style: inherit;">&lt;-</span> <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">30</span></span>
<span id="cb2-3">years  <span class="ot" style="color: #003B4F;
background-color: null;
font-style: inherit;">&lt;-</span> <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">2015</span><span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">:</span><span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">2024</span></span>
<span id="cb2-4">sites <span class="ot" style="color: #003B4F;
background-color: null;
font-style: inherit;">&lt;-</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">data.frame</span>(</span>
<span id="cb2-5">  <span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">site       =</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">sprintf</span>(<span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"S%02d"</span>, <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">seq_len</span>(n_site)),</span>
<span id="cb2-6">  <span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">region     =</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">rep</span>(<span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">c</span>(<span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"north"</span>, <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"south"</span>), <span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">each =</span> n_site <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">/</span> <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">2</span>),</span>
<span id="cb2-7">  <span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">count_2015 =</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">exp</span>(<span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">rnorm</span>(n_site, <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">log</span>(<span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">10</span>), <span class="fl" style="color: #AD0000;
background-color: null;
font-style: inherit;">0.7</span>)),  <span class="co" style="color: #5E5E5E;
background-color: null;
font-style: inherit;"># expected count in the first year</span></span>
<span id="cb2-8">  <span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">true_trend =</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">rnorm</span>(n_site, <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">-</span><span class="fl" style="color: #AD0000;
background-color: null;
font-style: inherit;">0.03</span>, <span class="fl" style="color: #AD0000;
background-color: null;
font-style: inherit;">0.08</span>)         <span class="co" style="color: #5E5E5E;
background-color: null;
font-style: inherit;"># change per year, log scale</span></span>
<span id="cb2-9">)</span>
<span id="cb2-10">survey <span class="ot" style="color: #003B4F;
background-color: null;
font-style: inherit;">&lt;-</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">expand.grid</span>(<span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">year =</span> years, <span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">site =</span> sites<span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">$</span>site, <span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">stringsAsFactors =</span> <span class="cn" style="color: #8f5902;
background-color: null;
font-style: inherit;">FALSE</span>) <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">|&gt;</span></span>
<span id="cb2-11">  <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">left_join</span>(sites, <span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">by =</span> <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"site"</span>) <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">|&gt;</span></span>
<span id="cb2-12">  <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">mutate</span>(<span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">count =</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">rpois</span>(<span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">n</span>(), count_2015 <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">*</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">exp</span>(true_trend <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">*</span> (year <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">-</span> <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">2015</span>)))) <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">|&gt;</span></span>
<span id="cb2-13">  <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">select</span>(site, region, year, count)</span>
<span id="cb2-14"></span>
<span id="cb2-15"><span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">head</span>(survey, <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">3</span>)</span></code></pre></div></div>
<div class="cell-output cell-output-stdout">
<pre><code>  site region year count
1  S01  north 2015    13
2  S01  north 2016    14
3  S01  north 2017    11</code></pre>
</div>
<div class="code-copy-outer-scaffold"><div class="sourceCode cell-code" id="cb4" style="background: #f1f3f5;"><pre class="sourceCode r code-with-copy"><code class="sourceCode r"><span id="cb4-1"><span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">nrow</span>(survey)</span></code></pre></div></div>
<div class="cell-output cell-output-stdout">
<pre><code>[1] 300</code></pre>
</div>
</div>
<p>300 rows: 30 sites, 10 years each, one count per visit.</p>
</section>
<section id="one-site-first-then-every-site" class="level2">
<h2 id="one-site-first-then-every-site-h" class="anchored" data-anchor-id="one-site-first-then-every-site">One site first, then every site</h2>
<p>The analysis for one site is a linear regression of count on year, and the number we want from it is the slope: the change in individuals per year. Write it as a function of one site’s rows, and make it return a one-row data frame, so that the rows from all sites stack into a table.</p>
<div class="cell">
<div class="code-copy-outer-scaffold"><div class="sourceCode cell-code" id="cb6" style="background: #f1f3f5;"><pre class="sourceCode r code-with-copy"><code class="sourceCode r"><span id="cb6-1">site_trend <span class="ot" style="color: #003B4F;
background-color: null;
font-style: inherit;">&lt;-</span> <span class="cf" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">function</span>(d) {</span>
<span id="cb6-2">  fit <span class="ot" style="color: #003B4F;
background-color: null;
font-style: inherit;">&lt;-</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">lm</span>(count <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">~</span> year, <span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">data =</span> d)</span>
<span id="cb6-3">  <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">data.frame</span>(<span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">site =</span> d<span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">$</span>site[<span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">1</span>], <span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">n_years =</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">nrow</span>(d), <span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">slope =</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">coef</span>(fit)[[<span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"year"</span>]])</span>
<span id="cb6-4">}</span>
<span id="cb6-5">by_site <span class="ot" style="color: #003B4F;
background-color: null;
font-style: inherit;">&lt;-</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">split</span>(survey, survey<span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">$</span>site)</span>
<span id="cb6-6"><span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">site_trend</span>(by_site[[<span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"S01"</span>]])</span></code></pre></div></div>
<div class="cell-output cell-output-stdout">
<pre><code>  site n_years     slope
1  S01      10 -0.969697</code></pre>
</div>
</div>
<p><code>split()</code> turns the table into a list with one data frame per site, named by site. Checking the function on one element of that list, and comparing the answer with what you expect from a plot of that site, is the step that is worth the time. After that, repeating it is one line, and there are three common ways to write that line.</p>
<div class="cell">
<div class="code-copy-outer-scaffold"><div class="sourceCode cell-code" id="cb8" style="background: #f1f3f5;"><pre class="sourceCode r code-with-copy"><code class="sourceCode r"><span id="cb8-1"><span class="co" style="color: #5E5E5E;
background-color: null;
font-style: inherit;"># base R: apply to every piece, then stack the rows</span></span>
<span id="cb8-2">trends <span class="ot" style="color: #003B4F;
background-color: null;
font-style: inherit;">&lt;-</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">do.call</span>(rbind, <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">lapply</span>(by_site, site_trend))</span>
<span id="cb8-3"><span class="co" style="color: #5E5E5E;
background-color: null;
font-style: inherit;"># purrr: the same, with a binding function that expects data frames</span></span>
<span id="cb8-4">trends_purrr <span class="ot" style="color: #003B4F;
background-color: null;
font-style: inherit;">&lt;-</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">map</span>(by_site, site_trend) <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">|&gt;</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">list_rbind</span>()</span>
<span id="cb8-5"><span class="co" style="color: #5E5E5E;
background-color: null;
font-style: inherit;"># dplyr: fine when the result is one number per site</span></span>
<span id="cb8-6">trends_dplyr <span class="ot" style="color: #003B4F;
background-color: null;
font-style: inherit;">&lt;-</span> survey <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">|&gt;</span></span>
<span id="cb8-7">  <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">group_by</span>(site) <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">|&gt;</span></span>
<span id="cb8-8">  <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">summarise</span>(<span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">slope =</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">coef</span>(<span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">lm</span>(count <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">~</span> year))[[<span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"year"</span>]])</span>
<span id="cb8-9"></span>
<span id="cb8-10"><span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">stopifnot</span>(<span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">all.equal</span>(trends<span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">$</span>slope, trends_purrr<span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">$</span>slope),</span>
<span id="cb8-11">          <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">all.equal</span>(trends<span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">$</span>slope, trends_dplyr<span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">$</span>slope))</span>
<span id="cb8-12"><span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">head</span>(trends_purrr, <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">4</span>)</span></code></pre></div></div>
<div class="cell-output cell-output-stdout">
<pre><code>  site n_years      slope
1  S01      10 -0.9696970
2  S02      10 -0.2363636
3  S03      10 -0.9393939
4  S04      10  0.2787879</code></pre>
</div>
</div>
<p>All three give the same 30 slopes, and the <code>stopifnot()</code> line checks that they do. The slopes run from -2.59 to 3.21 individuals per year. Which of the three to use is mostly taste. The <code>lapply()</code> and <code>map()</code> versions scale to anything the function returns, including a whole model object; the <code>summarise()</code> version is the shortest when one number per site is all you need.</p>
</section>
<section id="sapply-decides-the-shape-for-you" class="level2">
<h2 id="sapply-decides-the-shape-for-you-h" class="anchored" data-anchor-id="sapply-decides-the-shape-for-you">sapply() decides the shape for you</h2>
<p>A second question for the same data: in which year was each site at its peak? The obvious function returns the year, or years, with the highest count.</p>
<div class="cell">
<div class="code-copy-outer-scaffold"><div class="sourceCode cell-code" id="cb10" style="background: #f1f3f5;"><pre class="sourceCode r code-with-copy"><code class="sourceCode r"><span id="cb10-1">peak_year <span class="ot" style="color: #003B4F;
background-color: null;
font-style: inherit;">&lt;-</span> <span class="cf" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">function</span>(d) d<span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">$</span>year[d<span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">$</span>count <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">==</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">max</span>(d<span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">$</span>count)]</span>
<span id="cb10-2"><span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">class</span>(<span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">sapply</span>(by_site[<span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">1</span><span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">:</span><span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">5</span>], peak_year))</span></code></pre></div></div>
<div class="cell-output cell-output-stdout">
<pre><code>[1] "integer"</code></pre>
</div>
<div class="code-copy-outer-scaffold"><div class="sourceCode cell-code" id="cb12" style="background: #f1f3f5;"><pre class="sourceCode r code-with-copy"><code class="sourceCode r"><span id="cb12-1"><span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">class</span>(<span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">sapply</span>(by_site, <span class="cf" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">function</span>(d) <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">range</span>(d<span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">$</span>count)))</span></code></pre></div></div>
<div class="cell-output cell-output-stdout">
<pre><code>[1] "matrix" "array" </code></pre>
</div>
<div class="code-copy-outer-scaffold"><div class="sourceCode cell-code" id="cb14" style="background: #f1f3f5;"><pre class="sourceCode r code-with-copy"><code class="sourceCode r"><span id="cb14-1">peak <span class="ot" style="color: #003B4F;
background-color: null;
font-style: inherit;">&lt;-</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">sapply</span>(by_site, peak_year)</span>
<span id="cb14-2"><span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">class</span>(peak)</span></code></pre></div></div>
<div class="cell-output cell-output-stdout">
<pre><code>[1] "list"</code></pre>
</div>
<div class="code-copy-outer-scaffold"><div class="sourceCode cell-code" id="cb16" style="background: #f1f3f5;"><pre class="sourceCode r code-with-copy"><code class="sourceCode r"><span id="cb16-1"><span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">lengths</span>(peak)[<span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">lengths</span>(peak) <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">&gt;</span> <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">1</span>]</span></code></pre></div></div>
<div class="cell-output cell-output-stdout">
<pre><code>S15 S17 
  2   2 </code></pre>
</div>
</div>
<p><code>sapply()</code> looks at what came back and chooses a shape. For the first five sites every answer had length one, and the result was a plain integer vector. For a function that returns two numbers per site, such as <code>range()</code>, it builds a matrix. For all 30 sites the result is a list, because 2 sites (S15 and S17) had the same highest count in two years. The same line of code gives a different kind of object depending on the data it meets, and the code after it was written for one of those kinds.</p>
<p>Sometimes the next line fails, which is the good outcome. Sometimes it does not:</p>
<div class="cell">
<div class="code-copy-outer-scaffold"><div class="sourceCode cell-code" id="cb18" style="background: #f1f3f5;"><pre class="sourceCode r code-with-copy"><code class="sourceCode r"><span id="cb18-1"><span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">length</span>(<span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">unlist</span>(peak))</span></code></pre></div></div>
<div class="cell-output cell-output-stdout">
<pre><code>[1] 32</code></pre>
</div>
<div class="code-copy-outer-scaffold"><div class="sourceCode cell-code" id="cb20" style="background: #f1f3f5;"><pre class="sourceCode r code-with-copy"><code class="sourceCode r"><span id="cb20-1"><span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">mean</span>(<span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">unlist</span>(peak))</span></code></pre></div></div>
<div class="cell-output cell-output-stdout">
<pre><code>[1] 2018.812</code></pre>
</div>
</div>
<p><code>unlist()</code> flattens the list into 32 years for 30 sites, and the mean runs without a message. The tied sites count twice, and nothing in the output says so. This is why Wickham (2019, section 9.2.1) advises keeping <code>sapply()</code> out of scripts that run unattended.</p>
<p><code>vapply()</code> and <code>map_dbl()</code> are told in advance what each result must look like, and they refuse anything else:</p>
<div class="cell">
<div class="code-copy-outer-scaffold"><div class="sourceCode cell-code" id="cb22" style="background: #f1f3f5;"><pre class="sourceCode r code-with-copy"><code class="sourceCode r"><span id="cb22-1">err_v <span class="ot" style="color: #003B4F;
background-color: null;
font-style: inherit;">&lt;-</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">tryCatch</span>(<span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">vapply</span>(by_site, peak_year, <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">numeric</span>(<span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">1</span>)), <span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">error =</span> <span class="cf" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">function</span>(e) e)</span>
<span id="cb22-2"><span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">conditionMessage</span>(err_v)</span></code></pre></div></div>
<div class="cell-output cell-output-stdout">
<pre><code>[1] "values must be length 1,\n but FUN(X[[15]]) result is length 2"</code></pre>
</div>
<div class="code-copy-outer-scaffold"><div class="sourceCode cell-code" id="cb24" style="background: #f1f3f5;"><pre class="sourceCode r code-with-copy"><code class="sourceCode r"><span id="cb24-1">err <span class="ot" style="color: #003B4F;
background-color: null;
font-style: inherit;">&lt;-</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">tryCatch</span>(<span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">map_dbl</span>(by_site, peak_year), <span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">error =</span> <span class="cf" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">function</span>(e) e)</span>
<span id="cb24-2">err<span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">$</span>name</span></code></pre></div></div>
<div class="cell-output cell-output-stdout">
<pre><code>[1] "S15"</code></pre>
</div>
<div class="code-copy-outer-scaffold"><div class="sourceCode cell-code" id="cb26" style="background: #f1f3f5;"><pre class="sourceCode r code-with-copy"><code class="sourceCode r"><span id="cb26-1"><span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">conditionMessage</span>(err<span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">$</span>parent)</span></code></pre></div></div>
<div class="cell-output cell-output-stdout">
<pre><code>[1] "Result must be length 1, not 2."</code></pre>
</div>
</div>
<p>Both stop at the first tied site, and both say which one it was: <code>vapply()</code> by its position in the list, <code>map_dbl()</code> by position and by name (S15). The error is not the problem to solve; it is the message that your function has no rule for ties. Give it one, for example the first year the peak was reached, and the strict version runs:</p>
<div class="cell">
<div class="code-copy-outer-scaffold"><div class="sourceCode cell-code" id="cb28" style="background: #f1f3f5;"><pre class="sourceCode r code-with-copy"><code class="sourceCode r"><span id="cb28-1">first_peak <span class="ot" style="color: #003B4F;
background-color: null;
font-style: inherit;">&lt;-</span> <span class="cf" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">function</span>(d) d<span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">$</span>year[<span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">which.max</span>(d<span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">$</span>count)]</span>
<span id="cb28-2">peak_fixed <span class="ot" style="color: #003B4F;
background-color: null;
font-style: inherit;">&lt;-</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">vapply</span>(by_site, first_peak, <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">numeric</span>(<span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">1</span>))</span>
<span id="cb28-3"><span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">length</span>(peak_fixed)</span></code></pre></div></div>
<div class="cell-output cell-output-stdout">
<pre><code>[1] 30</code></pre>
</div>
</div>
<p>Now there are 30 years for 30 sites, and the next time the data change shape, the line stops instead of guessing.</p>
</section>
<section id="a-loop-that-runs-over-nothing" class="level2">
<h2 id="a-loop-that-runs-over-nothing-h" class="anchored" data-anchor-id="a-loop-that-runs-over-nothing">A loop that runs over nothing</h2>
<p><code>for</code> loops are fine in R, and for a first script they are often clearer than <code>lapply()</code>. The trap is in how the loop counts. Suppose the analysis is restricted to one region, and the region is typed with a capital letter that the data do not use:</p>
<div class="cell">
<div class="code-copy-outer-scaffold"><div class="sourceCode cell-code" id="cb30" style="background: #f1f3f5;"><pre class="sourceCode r code-with-copy"><code class="sourceCode r"><span id="cb30-1">north <span class="ot" style="color: #003B4F;
background-color: null;
font-style: inherit;">&lt;-</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">unique</span>(survey<span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">$</span>site[survey<span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">$</span>region <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">==</span> <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"North"</span>])</span>
<span id="cb30-2"><span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">length</span>(north)</span></code></pre></div></div>
<div class="cell-output cell-output-stdout">
<pre><code>[1] 0</code></pre>
</div>
<div class="code-copy-outer-scaffold"><div class="sourceCode cell-code" id="cb32" style="background: #f1f3f5;"><pre class="sourceCode r code-with-copy"><code class="sourceCode r"><span id="cb32-1"><span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">1</span><span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">:</span><span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">length</span>(north)</span></code></pre></div></div>
<div class="cell-output cell-output-stdout">
<pre><code>[1] 1 0</code></pre>
</div>
<div class="code-copy-outer-scaffold"><div class="sourceCode cell-code" id="cb34" style="background: #f1f3f5;"><pre class="sourceCode r code-with-copy"><code class="sourceCode r"><span id="cb34-1">totals <span class="ot" style="color: #003B4F;
background-color: null;
font-style: inherit;">&lt;-</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">numeric</span>(<span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">0</span>)</span>
<span id="cb34-2"><span class="cf" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">for</span> (i <span class="cf" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">in</span> <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">1</span><span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">:</span><span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">length</span>(north)) {</span>
<span id="cb34-3">  totals[i] <span class="ot" style="color: #003B4F;
background-color: null;
font-style: inherit;">&lt;-</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">sum</span>(survey<span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">$</span>count[survey<span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">$</span>site <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">==</span> north[i]], <span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">na.rm =</span> <span class="cn" style="color: #8f5902;
background-color: null;
font-style: inherit;">TRUE</span>)</span>
<span id="cb34-4">}</span>
<span id="cb34-5">totals</span></code></pre></div></div>
<div class="cell-output cell-output-stdout">
<pre><code>[1] 0</code></pre>
</div>
</div>
<p>The filter matched no site, so there is nothing to total, and yet <code>totals</code> has 1 element, a total of 0 individuals. <code>1:length(north)</code> is <code>1:0</code>, which counts down to the vector <code>c(1, 0)</code>, so the loop ran twice. On the first pass <code>north[1]</code> is <code>NA</code>, every comparison with it is <code>NA</code>, and <code>sum(..., na.rm = TRUE)</code> of nothing but <code>NA</code> is zero. On the second pass it assigned to position zero, which R ignores. The result looks like a site where nothing was counted.</p>
<div class="cell">
<div class="code-copy-outer-scaffold"><div class="sourceCode cell-code" id="cb36" style="background: #f1f3f5;"><pre class="sourceCode r code-with-copy"><code class="sourceCode r"><span id="cb36-1">totals <span class="ot" style="color: #003B4F;
background-color: null;
font-style: inherit;">&lt;-</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">numeric</span>(<span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">0</span>)</span>
<span id="cb36-2"><span class="cf" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">for</span> (i <span class="cf" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">in</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">seq_along</span>(north)) {</span>
<span id="cb36-3">  totals[i] <span class="ot" style="color: #003B4F;
background-color: null;
font-style: inherit;">&lt;-</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">sum</span>(survey<span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">$</span>count[survey<span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">$</span>site <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">==</span> north[i]], <span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">na.rm =</span> <span class="cn" style="color: #8f5902;
background-color: null;
font-style: inherit;">TRUE</span>)</span>
<span id="cb36-4">}</span>
<span id="cb36-5"><span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">length</span>(totals)</span></code></pre></div></div>
<div class="cell-output cell-output-stdout">
<pre><code>[1] 0</code></pre>
</div>
</div>
<p><code>seq_along(north)</code> is empty when <code>north</code> is empty, so the loop body never runs and the result has length 0; Wickham (2019, section 5.3.1) lists <code>1:length(x)</code> among the common loop pitfalls for this reason. Better still, say what you expect before the loop starts: <code>stopifnot(length(north) &gt; 0)</code> turns the typo into an error on the line where it happened. Why a check at the top is worth its lines is the subject of <a href="https://tidyecology.com/posts/debugging-and-defensive-code/">Debugging and defensive R code</a>.</p>
</section>
<section id="when-one-site-fails" class="level2">
<h2 id="when-one-site-fails-h" class="anchored" data-anchor-id="when-one-site-fails">When one site fails</h2>
<p>The trend in individuals per year is hard to compare between a site with 5 individuals and one with 50. A common next step is to fit the log of the count, so that the slope becomes a proportional change, and to report it as per cent change per year.</p>
<div class="cell">
<div class="code-copy-outer-scaffold"><div class="sourceCode cell-code" id="cb38" style="background: #f1f3f5;"><pre class="sourceCode r code-with-copy"><code class="sourceCode r"><span id="cb38-1">pct_trend <span class="ot" style="color: #003B4F;
background-color: null;
font-style: inherit;">&lt;-</span> <span class="cf" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">function</span>(d) {</span>
<span id="cb38-2">  fit <span class="ot" style="color: #003B4F;
background-color: null;
font-style: inherit;">&lt;-</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">lm</span>(<span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">log</span>(count) <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">~</span> year, <span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">data =</span> d)</span>
<span id="cb38-3">  <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">100</span> <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">*</span> (<span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">exp</span>(<span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">coef</span>(fit)[[<span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"year"</span>]]) <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">-</span> <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">1</span>)</span>
<span id="cb38-4">}</span>
<span id="cb38-5"><span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">pct_trend</span>(by_site[[<span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"S01"</span>]])</span></code></pre></div></div>
<div class="cell-output cell-output-stdout">
<pre><code>[1] -13.05201</code></pre>
</div>
</div>
<p>It works on site 1. It does not work on every site, because the log of a zero count is minus infinity and <code>lm()</code> stops with an error. In a loop, the first failing site stops everything:</p>
<div class="cell">
<div class="code-copy-outer-scaffold"><div class="sourceCode cell-code" id="cb40" style="background: #f1f3f5;"><pre class="sourceCode r code-with-copy"><code class="sourceCode r"><span id="cb40-1">pct_loop <span class="ot" style="color: #003B4F;
background-color: null;
font-style: inherit;">&lt;-</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">setNames</span>(<span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">rep</span>(<span class="cn" style="color: #8f5902;
background-color: null;
font-style: inherit;">NA_real_</span>, n_site), <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">names</span>(by_site))</span>
<span id="cb40-2">err_loop <span class="ot" style="color: #003B4F;
background-color: null;
font-style: inherit;">&lt;-</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">tryCatch</span>(</span>
<span id="cb40-3">  <span class="cf" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">for</span> (i <span class="cf" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">in</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">seq_along</span>(by_site)) pct_loop[i] <span class="ot" style="color: #003B4F;
background-color: null;
font-style: inherit;">&lt;-</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">pct_trend</span>(by_site[[i]]),</span>
<span id="cb40-4">  <span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">error =</span> <span class="cf" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">function</span>(e) e)</span>
<span id="cb40-5"><span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">conditionMessage</span>(err_loop)</span></code></pre></div></div>
<div class="cell-output cell-output-stdout">
<pre><code>[1] "NA/NaN/Inf in 'y'"</code></pre>
</div>
<div class="code-copy-outer-scaffold"><div class="sourceCode cell-code" id="cb42" style="background: #f1f3f5;"><pre class="sourceCode r code-with-copy"><code class="sourceCode r"><span id="cb42-1"><span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">sum</span>(<span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">!</span><span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">is.na</span>(pct_loop))</span></code></pre></div></div>
<div class="cell-output cell-output-stdout">
<pre><code>[1] 5</code></pre>
</div>
</div>
<p>The loop filled 5 sites and then stopped at S06, the first site with a zero count. <code>lapply()</code> is worse in one respect: it returns nothing at all, so the results for the sites before the failure are gone too. Both at least stop, and you know something went wrong.</p>
<p>The usual next move is to catch the error and carry on. <code>purrr::possibly()</code> wraps a function so that an error returns a value of your choice instead. What that value is decides whether the failed sites stay visible.</p>
<div class="cell">
<div class="code-copy-outer-scaffold"><div class="sourceCode cell-code" id="cb44" style="background: #f1f3f5;"><pre class="sourceCode r code-with-copy"><code class="sourceCode r"><span id="cb44-1">pct_dropped <span class="ot" style="color: #003B4F;
background-color: null;
font-style: inherit;">&lt;-</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">map</span>(by_site, <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">possibly</span>(pct_trend)) <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">|&gt;</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">list_c</span>()</span>
<span id="cb44-2"><span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">length</span>(pct_dropped)</span></code></pre></div></div>
<div class="cell-output cell-output-stdout">
<pre><code>[1] 24</code></pre>
</div>
<div class="code-copy-outer-scaffold"><div class="sourceCode cell-code" id="cb46" style="background: #f1f3f5;"><pre class="sourceCode r code-with-copy"><code class="sourceCode r"><span id="cb46-1"><span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">names</span>(pct_dropped)</span></code></pre></div></div>
<div class="cell-output cell-output-stdout">
<pre><code>NULL</code></pre>
</div>
<div class="code-copy-outer-scaffold"><div class="sourceCode cell-code" id="cb48" style="background: #f1f3f5;"><pre class="sourceCode r code-with-copy"><code class="sourceCode r"><span id="cb48-1">pct <span class="ot" style="color: #003B4F;
background-color: null;
font-style: inherit;">&lt;-</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">map_dbl</span>(by_site, <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">possibly</span>(pct_trend, <span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">otherwise =</span> <span class="cn" style="color: #8f5902;
background-color: null;
font-style: inherit;">NA_real_</span>))</span>
<span id="cb48-2"><span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">length</span>(pct)</span></code></pre></div></div>
<div class="cell-output cell-output-stdout">
<pre><code>[1] 30</code></pre>
</div>
<div class="code-copy-outer-scaffold"><div class="sourceCode cell-code" id="cb50" style="background: #f1f3f5;"><pre class="sourceCode r code-with-copy"><code class="sourceCode r"><span id="cb50-1"><span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">names</span>(pct)[<span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">is.na</span>(pct)]</span></code></pre></div></div>
<div class="cell-output cell-output-stdout">
<pre><code>[1] "S06" "S08" "S13" "S15" "S21" "S23"</code></pre>
</div>
</div>
<p>The first version uses the default of <code>possibly()</code>, which returns <code>NULL</code> on an error, and <code>list_c()</code> drops the <code>NULL</code> elements, and it never keeps the outer names, so the site names go too. The result is 24 numbers with no names, and nothing tells you that 6 sites are missing, or which. The second version returns <code>NA</code> on an error, and <code>map_dbl()</code> keeps one named value per site: 24 trends and 6 <code>NA</code> values, with the failed sites listed by name. The same holds in base R: <code>tryCatch(pct_trend(d), error = function(e) NA_real_)</code> inside <code>vapply()</code> does the same job.</p>
</section>
<section id="the-failed-sites-are-not-a-random-sample" class="level2">
<h2 id="the-failed-sites-are-not-a-random-sample-h" class="anchored" data-anchor-id="the-failed-sites-are-not-a-random-sample">The failed sites are not a random sample</h2>
<p>A named <code>NA</code> does more than keep the count right. It lets you ask what the failed sites have in common, and here the answer matters. A site fails when it has a zero count in at least one year. In a year with an expected count of <code>mu</code> individuals, the chance of a Poisson count of zero is <code>exp(-mu)</code>: less than one in ten thousand when <code>mu</code> is 10, 2 per cent when it is 4 and 37 per cent when it is 1. So a site reaches zero when it starts small or when it declines. The simulated survey has the answer key, so we can compare the true trends of the two groups.</p>
<div class="cell">
<div class="code-copy-outer-scaffold"><div class="sourceCode cell-code" id="cb52" style="background: #f1f3f5;"><pre class="sourceCode r code-with-copy"><code class="sourceCode r"><span id="cb52-1">scored <span class="ot" style="color: #003B4F;
background-color: null;
font-style: inherit;">&lt;-</span> sites <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">|&gt;</span></span>
<span id="cb52-2">  <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">mutate</span>(<span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">estimate =</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">unname</span>(pct[site]),</span>
<span id="cb52-3">         <span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">status =</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">if_else</span>(<span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">is.na</span>(estimate), <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"failed"</span>, <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"fitted"</span>),</span>
<span id="cb52-4">         <span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">true_pct =</span> <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">100</span> <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">*</span> (<span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">exp</span>(true_trend) <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">-</span> <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">1</span>))</span>
<span id="cb52-5">scored <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">|&gt;</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">group_by</span>(status) <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">|&gt;</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">summarise</span>(<span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">sites =</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">n</span>(), <span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">mean_true_pct =</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">mean</span>(true_pct))</span></code></pre></div></div>
<div class="cell-output cell-output-stdout">
<pre><code># A tibble: 2 × 3
  status sites mean_true_pct
  &lt;chr&gt;  &lt;int&gt;         &lt;dbl&gt;
1 failed     6         -7.62
2 fitted    24         -2.99</code></pre>
</div>
<div class="code-copy-outer-scaffold"><div class="sourceCode cell-code" id="cb54" style="background: #f1f3f5;"><pre class="sourceCode r code-with-copy"><code class="sourceCode r"><span id="cb54-1">truth_all  <span class="ot" style="color: #003B4F;
background-color: null;
font-style: inherit;">&lt;-</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">mean</span>(scored<span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">$</span>true_pct)</span>
<span id="cb54-2">report_fit <span class="ot" style="color: #003B4F;
background-color: null;
font-style: inherit;">&lt;-</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">mean</span>(scored<span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">$</span>estimate, <span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">na.rm =</span> <span class="cn" style="color: #8f5902;
background-color: null;
font-style: inherit;">TRUE</span>)</span>
<span id="cb54-3"><span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">c</span>(<span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">true_mean_all_sites =</span> truth_all, <span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">reported_mean =</span> report_fit)</span></code></pre></div></div>
<div class="cell-output cell-output-stdout">
<pre><code>true_mean_all_sites       reported_mean 
          -3.917224           -3.444762 </code></pre>
</div>
</div>
<p>The 6 sites that failed were declining by 7.6 per cent per year on average, against 3.0 per cent for the sites that were fitted. The mean of the reported trends is -3.4 per cent per year; the true mean over all 30 sites is -3.9. 5 of the 6 failed sites were declining. The other one, S06, was increasing but started from an expected count of 1.7 individuals, low enough for a zero in the early years. The summary made the scheme look healthier than it is, because the model failed mostly at sites where the species was declining fast.</p>
<div class="cell">
<div class="cell-output-display">
<div id="fig-failed" class="quarto-float quarto-figure quarto-figure-center anchored" alt="Dot plot of the 30 sites on the horizontal axis, ordered by true trend from about minus 12 to plus 9 per cent per year on the vertical axis. Green dots are fitted sites and red dots are failed sites. Five red dots sit among the steepest declines, at positions 2, 3, 7, 8 and 9, and one sits near the top at position 29. A solid horizontal line for the mean reported by the fitted sites lies just above a dashed line for the true mean of all sites, both between minus 3 and minus 4.">
<figure class="quarto-float quarto-float-fig figure">
<div aria-describedby="fig-failed-caption-0ceaefa1-69ba-4598-a22c-09a6ac19f8ca">
<img src="https://tidyecology.com/posts/repeating-an-analysis-for-every-site/index_files/figure-html/fig-failed-1.png" class="img-fluid figure-img" alt="Dot plot of the 30 sites on the horizontal axis, ordered by true trend from about minus 12 to plus 9 per cent per year on the vertical axis. Green dots are fitted sites and red dots are failed sites. Five red dots sit among the steepest declines, at positions 2, 3, 7, 8 and 9, and one sits near the top at position 29. A solid horizontal line for the mean reported by the fitted sites lies just above a dashed line for the true mean of all sites, both between minus 3 and minus 4." width="672">
</div>
<figcaption class="quarto-float-caption-bottom quarto-float-caption quarto-float-fig" id="fig-failed-caption-0ceaefa1-69ba-4598-a22c-09a6ac19f8ca">
Figure&nbsp;1: True trend of each of the 30 simulated sites, ordered from steepest decline to strongest increase. Sites where the log-count model failed are in red; most of them sit among the steepest declines. The dashed line is the true mean over all sites and the solid line is the mean of the trends that the fitted sites reported.
</figcaption>
</figure>
</div>
</div>
</div>
<p>One survey is one draw, and its gap could be luck. For this failure the average gap can be worked out without simulating whole surveys. A site is fitted only if all ten of its counts are above zero, and the chance of that is the product of <code>1 - exp(-mu)</code> over the ten years. Weight each site’s true trend by that chance, and the weighted mean is the mean over the sites that would be fitted. The chunk below does this for a large sample of sites drawn from the same design; <code>draw_sites()</code> is the design, written once so that the simulation further down can reuse it.</p>
<div class="cell">
<div class="code-copy-outer-scaffold"><div class="sourceCode cell-code" id="cb56" style="background: #f1f3f5;"><pre class="sourceCode r code-with-copy"><code class="sourceCode r"><span id="cb56-1">draw_sites <span class="ot" style="color: #003B4F;
background-color: null;
font-style: inherit;">&lt;-</span> <span class="cf" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">function</span>(n, anchor_year) {</span>
<span id="cb56-2">  level <span class="ot" style="color: #003B4F;
background-color: null;
font-style: inherit;">&lt;-</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">exp</span>(<span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">rnorm</span>(n, <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">log</span>(<span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">10</span>), <span class="fl" style="color: #AD0000;
background-color: null;
font-style: inherit;">0.7</span>))   <span class="co" style="color: #5E5E5E;
background-color: null;
font-style: inherit;"># expected count in anchor_year</span></span>
<span id="cb56-3">  trend <span class="ot" style="color: #003B4F;
background-color: null;
font-style: inherit;">&lt;-</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">rnorm</span>(n, <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">-</span><span class="fl" style="color: #AD0000;
background-color: null;
font-style: inherit;">0.03</span>, <span class="fl" style="color: #AD0000;
background-color: null;
font-style: inherit;">0.08</span>)</span>
<span id="cb56-4">  <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">list</span>(<span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">mu =</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">exp</span>(<span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">outer</span>(years <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">-</span> anchor_year, trend)) <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">*</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">rep</span>(level, <span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">each =</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">length</span>(years)),</span>
<span id="cb56-5">       <span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">true_pct =</span> <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">100</span> <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">*</span> (<span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">exp</span>(trend) <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">-</span> <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">1</span>))</span>
<span id="cb56-6">}</span>
<span id="cb56-7">expected_shift <span class="ot" style="color: #003B4F;
background-color: null;
font-style: inherit;">&lt;-</span> <span class="cf" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">function</span>(anchor_year, <span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">n =</span> <span class="fl" style="color: #AD0000;
background-color: null;
font-style: inherit;">1e5</span>) {</span>
<span id="cb56-8">  s <span class="ot" style="color: #003B4F;
background-color: null;
font-style: inherit;">&lt;-</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">draw_sites</span>(n, anchor_year)</span>
<span id="cb56-9">  p_fit <span class="ot" style="color: #003B4F;
background-color: null;
font-style: inherit;">&lt;-</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">apply</span>(<span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">1</span> <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">-</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">exp</span>(<span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">-</span>s<span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">$</span>mu), <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">2</span>, prod)   <span class="co" style="color: #5E5E5E;
background-color: null;
font-style: inherit;"># chance of no zero in ten years</span></span>
<span id="cb56-10">  <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">c</span>(<span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">failed =</span> n_site <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">*</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">mean</span>(<span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">1</span> <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">-</span> p_fit),</span>
<span id="cb56-11">    <span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">shift  =</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">weighted.mean</span>(s<span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">$</span>true_pct, p_fit) <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">-</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">mean</span>(s<span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">$</span>true_pct))</span>
<span id="cb56-12">}</span>
<span id="cb56-13"><span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">set.seed</span>(<span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">1</span>); expect_start <span class="ot" style="color: #003B4F;
background-color: null;
font-style: inherit;">&lt;-</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">expected_shift</span>(<span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">anchor_year =</span> <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">2015</span>)</span>
<span id="cb56-14">expect_start</span></code></pre></div></div>
<div class="cell-output cell-output-stdout">
<pre><code>  failed    shift 
3.373400 0.781275 </code></pre>
</div>
</div>
<p>The design predicts 3.4 failed sites out of 30 in an average survey, and a shift of 0.78 percentage points per year in the mean true trend once they are dropped. That shift is a property of the design, not something a simulation has to discover. What a simulation adds is how much it varies from one survey to the next. The chunk below runs 2000 surveys and uses the closed form of the regression slope instead of <code>lm()</code>, which gives the same number much faster; the first <code>stopifnot()</code> line checks that on site 1, and the last one checks the simulation against the prediction.</p>
<div class="cell">
<div class="code-copy-outer-scaffold"><div class="sourceCode cell-code" id="cb58" style="background: #f1f3f5;"><pre class="sourceCode r code-with-copy"><code class="sourceCode r"><span id="cb58-1">slope_fast <span class="ot" style="color: #003B4F;
background-color: null;
font-style: inherit;">&lt;-</span> <span class="cf" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">function</span>(y, x) <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">sum</span>((x <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">-</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">mean</span>(x)) <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">*</span> (y <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">-</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">mean</span>(y))) <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">/</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">sum</span>((x <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">-</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">mean</span>(x))<span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">^</span><span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">2</span>)</span>
<span id="cb58-2"><span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">stopifnot</span>(<span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">all.equal</span>(<span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">slope_fast</span>(<span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">log</span>(by_site[[<span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"S01"</span>]]<span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">$</span>count), years),</span>
<span id="cb58-3">                    <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">coef</span>(<span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">lm</span>(<span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">log</span>(count) <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">~</span> year, by_site[[<span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"S01"</span>]]))[[<span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"year"</span>]]))</span>
<span id="cb58-4">one_survey <span class="ot" style="color: #003B4F;
background-color: null;
font-style: inherit;">&lt;-</span> <span class="cf" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">function</span>(anchor_year) {</span>
<span id="cb58-5">  s <span class="ot" style="color: #003B4F;
background-color: null;
font-style: inherit;">&lt;-</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">draw_sites</span>(n_site, anchor_year)</span>
<span id="cb58-6">  counts <span class="ot" style="color: #003B4F;
background-color: null;
font-style: inherit;">&lt;-</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">matrix</span>(<span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">rpois</span>(<span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">length</span>(s<span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">$</span>mu), s<span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">$</span>mu), <span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">nrow =</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">length</span>(years))</span>
<span id="cb58-7">  fails <span class="ot" style="color: #003B4F;
background-color: null;
font-style: inherit;">&lt;-</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">colSums</span>(counts <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">==</span> <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">0</span>) <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">&gt;</span> <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">0</span></span>
<span id="cb58-8">  est_pct <span class="ot" style="color: #003B4F;
background-color: null;
font-style: inherit;">&lt;-</span> <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">100</span> <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">*</span> (<span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">exp</span>(<span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">apply</span>(<span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">log</span>(counts[, <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">!</span>fails, <span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">drop =</span> <span class="cn" style="color: #8f5902;
background-color: null;
font-style: inherit;">FALSE</span>]), <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">2</span>,</span>
<span id="cb58-9">                              slope_fast, <span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">x =</span> years)) <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">-</span> <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">1</span>)</span>
<span id="cb58-10">  <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">c</span>(<span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">selection =</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">mean</span>(s<span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">$</span>true_pct[<span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">!</span>fails]) <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">-</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">mean</span>(s<span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">$</span>true_pct),</span>
<span id="cb58-11">    <span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">reported  =</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">mean</span>(est_pct) <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">-</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">mean</span>(s<span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">$</span>true_pct),</span>
<span id="cb58-12">    <span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">n_failed  =</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">sum</span>(fails), <span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">true_mean =</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">mean</span>(s<span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">$</span>true_pct))</span>
<span id="cb58-13">}</span>
<span id="cb58-14"><span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">set.seed</span>(<span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">99</span>); n_rep <span class="ot" style="color: #003B4F;
background-color: null;
font-style: inherit;">&lt;-</span> <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">2000</span></span>
<span id="cb58-15">gap <span class="ot" style="color: #003B4F;
background-color: null;
font-style: inherit;">&lt;-</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">replicate</span>(n_rep, <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">one_survey</span>(<span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">anchor_year =</span> <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">2015</span>))</span>
<span id="cb58-16">mc_se <span class="ot" style="color: #003B4F;
background-color: null;
font-style: inherit;">&lt;-</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">apply</span>(gap, <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">1</span>, sd) <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">/</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">sqrt</span>(n_rep)</span>
<span id="cb58-17"><span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">round</span>(<span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">rbind</span>(<span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">mean =</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">rowMeans</span>(gap), <span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">mc_se =</span> mc_se), <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">3</span>)</span></code></pre></div></div>
<div class="cell-output cell-output-stdout">
<pre><code>      selection reported n_failed true_mean
mean      0.770    0.827    3.328    -2.647
mc_se     0.014    0.023    0.039     0.031</code></pre>
</div>
<div class="code-copy-outer-scaffold"><div class="sourceCode cell-code" id="cb60" style="background: #f1f3f5;"><pre class="sourceCode r code-with-copy"><code class="sourceCode r"><span id="cb60-1"><span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">mean</span>(gap[<span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"selection"</span>, ] <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">&gt;</span> <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">0</span>)</span></code></pre></div></div>
<div class="cell-output cell-output-stdout">
<pre><code>[1] 0.8985</code></pre>
</div>
<div class="code-copy-outer-scaffold"><div class="sourceCode cell-code" id="cb62" style="background: #f1f3f5;"><pre class="sourceCode r code-with-copy"><code class="sourceCode r"><span id="cb62-1"><span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">stopifnot</span>(<span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">abs</span>(<span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">mean</span>(gap[<span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"selection"</span>, ]) <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">-</span> expect_start[[<span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"shift"</span>]]) <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">&lt;</span> <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">3</span> <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">*</span> mc_se[[<span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"selection"</span>]])</span></code></pre></div></div>
</div>
<p>The simulated surveys agree with the prediction: an average of 3.3 sites failed, and dropping them raised the mean trend by 0.77 percentage points per year (Monte Carlo standard error 0.014). The shift was upward in 90 per cent of the surveys, so a single survey usually shows it, though not every time. The mean of the reported estimates sat 0.83 points above the truth (standard error 0.023). The true mean decline averaged 2.65 per cent per year, so dropping the failed sites alone hid 29 per cent of it, without an error or a warning anywhere in the script.</p>
<p>Flagging the failures does not remove that shift; it makes it visible. Adding one before taking the log, <code>log(count + 1)</code>, makes the error go away but not the problem, because the trend it reports then depends on the constant you added. The fix for this particular failure is a model that accepts zero counts, such as a Poisson GLM, and <a href="https://tidyecology.com/posts/glm-count-data-abundance/">Poisson and negative binomial GLMs in R</a> shows how. With <code>glm(count ~ year, family = poisson)</code> in place of the log-count regression, every site returns a trend:</p>
<div class="cell">
<div class="code-copy-outer-scaffold"><div class="sourceCode cell-code" id="cb63" style="background: #f1f3f5;"><pre class="sourceCode r code-with-copy"><code class="sourceCode r"><span id="cb63-1">glm_pct <span class="ot" style="color: #003B4F;
background-color: null;
font-style: inherit;">&lt;-</span> <span class="cf" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">function</span>(d) {</span>
<span id="cb63-2">  fit <span class="ot" style="color: #003B4F;
background-color: null;
font-style: inherit;">&lt;-</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">glm</span>(count <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">~</span> year, <span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">family =</span> poisson, <span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">data =</span> d)</span>
<span id="cb63-3">  <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">100</span> <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">*</span> (<span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">exp</span>(<span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">coef</span>(fit)[[<span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"year"</span>]]) <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">-</span> <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">1</span>)</span>
<span id="cb63-4">}</span>
<span id="cb63-5">pct_glm <span class="ot" style="color: #003B4F;
background-color: null;
font-style: inherit;">&lt;-</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">map_dbl</span>(by_site, <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">possibly</span>(glm_pct, <span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">otherwise =</span> <span class="cn" style="color: #8f5902;
background-color: null;
font-style: inherit;">NA_real_</span>))</span>
<span id="cb63-6"><span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">c</span>(<span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">sites_fitted =</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">sum</span>(<span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">!</span><span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">is.na</span>(pct_glm)), <span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">mean_trend =</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">mean</span>(pct_glm))</span></code></pre></div></div>
<div class="cell-output cell-output-stdout">
<pre><code>sites_fitted   mean_trend 
   30.000000    -4.508713 </code></pre>
</div>
</div>
<p>All 30 sites are fitted, and the mean trend is -4.5 per cent per year against the true -3.9. In this survey the estimate misses on the other side, and one survey cannot say which method is closer on average. What changed is that no site is missing from the mean, so there is no selection left to lean it one way.</p>
</section>
<section id="what-to-check-in-your-own-data" class="level2">
<h2 id="what-to-check-in-your-own-data-h" class="anchored" data-anchor-id="what-to-check-in-your-own-data">What to check in your own data</h2>
<p>Before trusting a per-site table, count its rows and compare the count with the number of sites you surveyed. <code>stopifnot(NROW(result) == length(unique(data$site)))</code> is one line, and it catches the dropped sites, the tied sites counted twice and the empty filter. Write <code>NROW()</code>, in capitals: it also counts the elements of a plain vector, where <code>nrow()</code> returns <code>NULL</code>, the comparison gives <code>logical(0)</code> and <code>stopifnot()</code> quietly passes.</p>
<p>Run the function on the site you would least like to analyse by hand: the one with the fewest visits, the most zeros or a single year of data. If it gives a sensible answer there, the loop over the easy sites is unlikely to surprise you. Writing that check down as a test is covered in <a href="https://tidyecology.com/posts/testing-your-analysis-code/">Testing your analysis code</a>.</p>
<p>When a site fails, keep it as a named <code>NA</code> and look at the failed sites as a group before averaging anything. Compare their counts, their number of years and their habitat with the sites that were fitted. If the failures lean one way, the summary leans the other way.</p>
<p>Where a result should be one number per site, say so with <code>vapply(..., numeric(1))</code> or <code>map_dbl()</code>, so that a site that breaks the rule stops the script instead of reshaping the output.</p>
</section>
<section id="honest-limits" class="level2">
<h2 id="honest-limits-h" class="anchored" data-anchor-id="honest-limits">Honest limits</h2>
<p>The direction of the shift comes from how the survey was simulated: each site entered the scheme at its own abundance and then followed its own trend, so the declining sites were the ones most likely to reach zero. That is a common way for monitoring schemes to start, but it is a choice. The chunk below repeats the calculation with each site’s abundance fixed at the middle of the period instead, so that a declining site and an increasing one reach their lowest count equally far from the middle.</p>
<div class="cell">
<div class="code-copy-outer-scaffold"><div class="sourceCode cell-code" id="cb65" style="background: #f1f3f5;"><pre class="sourceCode r code-with-copy"><code class="sourceCode r"><span id="cb65-1"><span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">set.seed</span>(<span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">1</span>); expect_mid <span class="ot" style="color: #003B4F;
background-color: null;
font-style: inherit;">&lt;-</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">expected_shift</span>(<span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">anchor_year =</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">mean</span>(years))</span>
<span id="cb65-2"><span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">rbind</span>(<span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">start =</span> expect_start, <span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">middle =</span> expect_mid)</span></code></pre></div></div>
<div class="cell-output cell-output-stdout">
<pre><code>         failed      shift
start  3.373400 0.78127503
middle 1.996755 0.06180194</code></pre>
</div>
<div class="code-copy-outer-scaffold"><div class="sourceCode cell-code" id="cb67" style="background: #f1f3f5;"><pre class="sourceCode r code-with-copy"><code class="sourceCode r"><span id="cb67-1"><span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">stopifnot</span>(expect_mid[[<span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"shift"</span>]] <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">&gt;</span> <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">0</span>, expect_mid[[<span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"shift"</span>]] <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">&lt;</span> expect_start[[<span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"shift"</span>]] <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">/</span> <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">10</span>)</span></code></pre></div></div>
</div>
<p>With that design 2.0 sites fail in an average survey, and dropping them shifts the mean trend by 0.06 percentage points per year: less than a tenth of the 0.78 when the sites were anchored at the start, though still above zero. It stays positive because the average site in this design is declining, so among the steepest trends, the ones most likely to reach zero at one end of the period, declines outnumber increases. The general lesson does not depend on the design: failures are rarely a random subset, so their direction has to be looked at, not assumed.</p>
</section>
<section id="references" class="level2">
<h2 id="references-h" class="anchored" data-anchor-id="references">References</h2>
<ul>
<li>R Core Team 2024 R documentation: <a href="https://stat.ethz.ch/R-manual/R-devel/library/base/html/lapply.html">lapply, sapply and vapply</a> and <a href="https://stat.ethz.ch/R-manual/R-devel/library/base/html/seq.html">seq_along</a>.</li>
<li>Wickham H, Henry L 2023 purrr package documentation: <a href="https://purrr.tidyverse.org/reference/map.html">map() and map_dbl()</a>, <a href="https://purrr.tidyverse.org/reference/possibly.html">possibly()</a> and <a href="https://purrr.tidyverse.org/reference/list_c.html">list_c()</a>.</li>
<li>Wickham H, Francois R, Henry L, Muller K, Vaughan D 2023 dplyr 1.1.4 package documentation: <a href="https://dplyr.tidyverse.org/reference/group_by.html">group_by()</a> and <a href="https://dplyr.tidyverse.org/reference/summarise.html">summarise()</a>.</li>
<li>Wickham H 2019 Advanced R, 2nd edition, Chapman and Hall/CRC (ISBN 978-0-8153-8457-1; DOI 10.1201/9781351201315): section 5.3.1 on loop pitfalls and section 9.2.1 on <code>sapply()</code> and <code>vapply()</code>.</li>
</ul>
</section>
<section id="related-tutorials" class="level2">
<h2 id="related-tutorials-h" class="anchored" data-anchor-id="related-tutorials">Related tutorials</h2>
<ul>
<li><a href="https://tidyecology.com/posts/grouped-summaries-in-r/">Summarising ecological data by group</a></li>
<li><a href="https://tidyecology.com/posts/debugging-and-defensive-code/">Debugging and defensive R code</a></li>
<li><a href="https://tidyecology.com/posts/testing-your-analysis-code/">Testing your analysis code</a></li>
<li><a href="https://tidyecology.com/posts/turning-your-code-into-a-package/">Turning your code into an R package</a></li>
</ul>
<details class="te-repro" data-pagefind-ignore="">
<summary>Reproducibility</summary>
<ul>
<li>Code last run: 2026-09-30</li>
<li>R version 4.5.3 (2026-03-11), aarch64-apple-darwin20</li>
<li>Packages: dplyr 1.2.1, ggplot2 4.0.3, purrr 1.2.2</li>
</ul>
</details>


<!-- -->

</section>

 ]]></description>
  <category>R</category>
  <category>data wrangling</category>
  <category>dplyr</category>
  <category>ecology tutorial</category>
  <guid isPermaLink="false">https://tidyecology.com/posts/repeating-an-analysis-for-every-site/</guid>
  <pubDate>Sun, 27 Sep 2026 10:00:00 GMT</pubDate>
  <media:content url="https://tidyecology.com/posts/repeating-an-analysis-for-every-site/thumbnail.png" medium="image" type="image/png" height="104" width="144"/>
</item>
<item>
  <title>ggplot2 facets: fixed or free axis scales</title>
  <dc:creator>Tidy Ecology</dc:creator>
  <link>https://tidyecology.com/posts/fixed-or-free-scales-in-facets/</link>
  <description><![CDATA[ 





<p><em>Corrected 14 October 2026: the few simulated surveys in which Mill Pond’s line rises were counted among those in which North Marsh’s line is drawn less than twice as steep as Mill Pond’s, and left out of those in which it is drawn at least as many times as steep as in the figure; both shares now compare the sizes of the two moves and change slightly.</em></p>
<p>Six wetlands have been counted for wintering teal every January since 2013, and the counts go into one figure with a panel per site. The biggest site holds around five hundred birds, the smallest a handful. With the <code>facet_wrap()</code> default the small sites are flat lines along the bottom of their panels, so the analyst adds <code>scales = "free_y"</code>, and now every site fills its panel and every trend line has room to look steep. Some of these sites lost most of their birds and some lost almost none. Which figure is telling the truth?</p>
<p><a href="https://tidyecology.com/posts/your-first-ggplot/">Your first ggplot</a> mentions <code>facet_wrap()</code> in one line; this post is about its <code>scales</code> argument. It measures what each setting does to the trend lines a reader compares, using the same idea as the truncated-axis check in <a href="https://tidyecology.com/posts/checking-a-figure/">Checking a figure</a>: read the drawn axis range back out of the built plot and turn “looks steep” into a number.</p>
<p><strong>The short answer.</strong> Keep the default, <code>scales = "fixed"</code>, when the reader should compare the panels on one axis. When the sites differ so much in size that the small ones flatten out, <code>scales = "free_y"</code> is not the cure: it stretches every panel to fit its own data, so the height of a line no longer says how much the site changed but how clearly the change stands out from that site’s own noise. If the question is which sites changed most, put that quantity on the y axis (a count divided by the site’s starting level) and keep the scales fixed. Free scales are for panels that show different things.</p>
<p>The data are simulated; the seed is in the code.</p>
<div class="cell">
<div class="code-copy-outer-scaffold"><div class="sourceCode cell-code" id="cb1" style="background: #f1f3f5;"><pre class="sourceCode r code-with-copy"><code class="sourceCode r"><span id="cb1-1"><span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">library</span>(ggplot2)</span>
<span id="cb1-2"></span>
<span id="cb1-3">te_paper  <span class="ot" style="color: #003B4F;
background-color: null;
font-style: inherit;">&lt;-</span> <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"#f5f4ee"</span></span>
<span id="cb1-4">te_ink    <span class="ot" style="color: #003B4F;
background-color: null;
font-style: inherit;">&lt;-</span> <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"#16241d"</span></span>
<span id="cb1-5">te_body   <span class="ot" style="color: #003B4F;
background-color: null;
font-style: inherit;">&lt;-</span> <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"#2c3a31"</span></span>
<span id="cb1-6">te_forest <span class="ot" style="color: #003B4F;
background-color: null;
font-style: inherit;">&lt;-</span> <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"#275139"</span></span>
<span id="cb1-7">te_rust   <span class="ot" style="color: #003B4F;
background-color: null;
font-style: inherit;">&lt;-</span> <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"#b5534e"</span></span>
<span id="cb1-8">te_gold   <span class="ot" style="color: #003B4F;
background-color: null;
font-style: inherit;">&lt;-</span> <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"#c9b458"</span></span>
<span id="cb1-9">te_line   <span class="ot" style="color: #003B4F;
background-color: null;
font-style: inherit;">&lt;-</span> <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"#dad9ca"</span></span>
<span id="cb1-10"></span>
<span id="cb1-11">theme_datasheet <span class="ot" style="color: #003B4F;
background-color: null;
font-style: inherit;">&lt;-</span> <span class="cf" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">function</span>() {</span>
<span id="cb1-12">  <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">theme_minimal</span>(<span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">base_size =</span> <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">12</span>) <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">+</span></span>
<span id="cb1-13">    <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">theme</span>(<span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">plot.background  =</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">element_rect</span>(<span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">fill =</span> te_paper, <span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">colour =</span> <span class="cn" style="color: #8f5902;
background-color: null;
font-style: inherit;">NA</span>),</span>
<span id="cb1-14">          <span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">panel.background =</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">element_rect</span>(<span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">fill =</span> te_paper, <span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">colour =</span> <span class="cn" style="color: #8f5902;
background-color: null;
font-style: inherit;">NA</span>),</span>
<span id="cb1-15">          <span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">panel.grid.major =</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">element_line</span>(<span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">colour =</span> te_line, <span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">linewidth =</span> <span class="fl" style="color: #AD0000;
background-color: null;
font-style: inherit;">0.3</span>),</span>
<span id="cb1-16">          <span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">panel.grid.minor =</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">element_blank</span>(),</span>
<span id="cb1-17">          <span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">text             =</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">element_text</span>(<span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">colour =</span> te_body),</span>
<span id="cb1-18">          <span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">axis.text        =</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">element_text</span>(<span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">colour =</span> te_body),</span>
<span id="cb1-19">          <span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">strip.text       =</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">element_text</span>(<span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">colour =</span> te_ink, <span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">face =</span> <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"bold"</span>))</span>
<span id="cb1-20">}</span></code></pre></div></div>
</div>
<section id="twelve-winters-at-six-sites" class="level2">
<h2 id="twelve-winters-at-six-sites-h" class="anchored" data-anchor-id="twelve-winters-at-six-sites">Twelve winters at six sites</h2>
<p>Each site gets an expected count in the first winter and a true change over the twelve winters, and the expected count moves between the two at a constant rate. The observed counts are Poisson draws around it. The design constants were fixed before any plot was drawn: the starting sizes span two orders of magnitude, one site is flat, one increases, and the declines run from 10 to 70 per cent, with the smallest decline at the largest site.</p>
<div class="cell">
<div class="code-copy-outer-scaffold"><div class="sourceCode cell-code" id="cb2" style="background: #f1f3f5;"><pre class="sourceCode r code-with-copy"><code class="sourceCode r"><span id="cb2-1"><span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">set.seed</span>(<span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">1015</span>)</span>
<span id="cb2-2">sites <span class="ot" style="color: #003B4F;
background-color: null;
font-style: inherit;">&lt;-</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">data.frame</span>(</span>
<span id="cb2-3">  <span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">site   =</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">c</span>(<span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"Mill Pond"</span>, <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"Reed Bed"</span>, <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"Fen Edge"</span>, <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"Gravel Pit"</span>, <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"North Marsh"</span>, <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"Ditch Meadow"</span>),</span>
<span id="cb2-4">  <span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">start  =</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">c</span>(<span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">520</span>, <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">180</span>, <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">90</span>, <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">40</span>, <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">20</span>, <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">6</span>),                <span class="co" style="color: #5E5E5E;
background-color: null;
font-style: inherit;"># expected count in 2013</span></span>
<span id="cb2-5">  <span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">change =</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">c</span>(<span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">-</span><span class="fl" style="color: #AD0000;
background-color: null;
font-style: inherit;">0.10</span>, <span class="fl" style="color: #AD0000;
background-color: null;
font-style: inherit;">0.00</span>, <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">-</span><span class="fl" style="color: #AD0000;
background-color: null;
font-style: inherit;">0.40</span>, <span class="fl" style="color: #AD0000;
background-color: null;
font-style: inherit;">0.30</span>, <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">-</span><span class="fl" style="color: #AD0000;
background-color: null;
font-style: inherit;">0.70</span>, <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">-</span><span class="fl" style="color: #AD0000;
background-color: null;
font-style: inherit;">0.20</span>)) <span class="co" style="color: #5E5E5E;
background-color: null;
font-style: inherit;"># true change, 2013 to 2024</span></span>
<span id="cb2-6">years <span class="ot" style="color: #003B4F;
background-color: null;
font-style: inherit;">&lt;-</span> <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">2013</span><span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">:</span><span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">2024</span></span>
<span id="cb2-7"></span>
<span id="cb2-8">teal <span class="ot" style="color: #003B4F;
background-color: null;
font-style: inherit;">&lt;-</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">expand.grid</span>(<span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">year =</span> years, <span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">site =</span> sites<span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">$</span>site, <span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">stringsAsFactors =</span> <span class="cn" style="color: #8f5902;
background-color: null;
font-style: inherit;">FALSE</span>)</span>
<span id="cb2-9">teal <span class="ot" style="color: #003B4F;
background-color: null;
font-style: inherit;">&lt;-</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">merge</span>(teal, sites, <span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">by =</span> <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"site"</span>)</span>
<span id="cb2-10">teal <span class="ot" style="color: #003B4F;
background-color: null;
font-style: inherit;">&lt;-</span> teal[<span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">order</span>(teal<span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">$</span>site, teal<span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">$</span>year), ]</span>
<span id="cb2-11">teal<span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">$</span>expected <span class="ot" style="color: #003B4F;
background-color: null;
font-style: inherit;">&lt;-</span> teal<span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">$</span>start <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">*</span> (<span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">1</span> <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">+</span> teal<span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">$</span>change)<span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">^</span>((teal<span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">$</span>year <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">-</span> <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">2013</span>) <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">/</span> <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">11</span>)</span>
<span id="cb2-12">teal<span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">$</span>count <span class="ot" style="color: #003B4F;
background-color: null;
font-style: inherit;">&lt;-</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">rpois</span>(<span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">nrow</span>(teal), teal<span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">$</span>expected)</span>
<span id="cb2-13">teal<span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">$</span>site <span class="ot" style="color: #003B4F;
background-color: null;
font-style: inherit;">&lt;-</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">factor</span>(teal<span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">$</span>site, <span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">levels =</span> sites<span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">$</span>site)    <span class="co" style="color: #5E5E5E;
background-color: null;
font-style: inherit;"># panel order = level order</span></span>
<span id="cb2-14"></span>
<span id="cb2-15"><span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">head</span>(teal[, <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">c</span>(<span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"site"</span>, <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"year"</span>, <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"count"</span>)], <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">3</span>)</span></code></pre></div></div>
<div class="cell-output cell-output-stdout">
<pre><code>          site year count
1 Ditch Meadow 2013     8
2 Ditch Meadow 2014     2
3 Ditch Meadow 2015     6</code></pre>
</div>
</div>
<p>A trend line per site comes from one Poisson GLM with a separate intercept and slope for each site, the log-linear trend that <a href="https://tidyecology.com/posts/population-trend-estimation/">Estimating population trends in R</a> fits one site at a time. Its fitted values give the line to draw and the fitted change over the series:</p>
<div class="cell">
<div class="code-copy-outer-scaffold"><div class="sourceCode cell-code" id="cb4" style="background: #f1f3f5;"><pre class="sourceCode r code-with-copy"><code class="sourceCode r"><span id="cb4-1">fit <span class="ot" style="color: #003B4F;
background-color: null;
font-style: inherit;">&lt;-</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">glm</span>(count <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">~</span> site <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">*</span> year, <span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">family =</span> poisson, <span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">data =</span> teal)</span>
<span id="cb4-2">teal<span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">$</span>fitted <span class="ot" style="color: #003B4F;
background-color: null;
font-style: inherit;">&lt;-</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">fitted</span>(fit)</span>
<span id="cb4-3"></span>
<span id="cb4-4">first <span class="ot" style="color: #003B4F;
background-color: null;
font-style: inherit;">&lt;-</span> teal[teal<span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">$</span>year <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">==</span> <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">2013</span>, ]</span>
<span id="cb4-5">last  <span class="ot" style="color: #003B4F;
background-color: null;
font-style: inherit;">&lt;-</span> teal[teal<span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">$</span>year <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">==</span> <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">2024</span>, ]</span>
<span id="cb4-6">fitted_change <span class="ot" style="color: #003B4F;
background-color: null;
font-style: inherit;">&lt;-</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">setNames</span>(last<span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">$</span>fitted <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">/</span> first<span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">$</span>fitted <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">-</span> <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">1</span>, <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">as.character</span>(first<span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">$</span>site))</span>
<span id="cb4-7"><span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">round</span>(<span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">rbind</span>(<span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">true =</span> sites<span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">$</span>change, <span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">fitted =</span> fitted_change[sites<span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">$</span>site]), <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">3</span>)</span></code></pre></div></div>
<div class="cell-output cell-output-stdout">
<pre><code>       Mill Pond Reed Bed Fen Edge Gravel Pit North Marsh Ditch Meadow
true      -0.100    0.000   -0.400      0.300      -0.700       -0.200
fitted    -0.045   -0.058   -0.398      0.203      -0.628       -0.233</code></pre>
</div>
</div>
<p>The fitted changes are not the true ones: twelve counts per site carry sampling noise, and the flat Reed Bed comes out at -5.8 per cent, Mill Pond at -4.5 per cent against its true -10 per cent. No figure can do better than the fitted line; the question here is whether the figure shows the fitted line’s change faithfully.</p>
</section>
<section id="what-the-scales-argument-does" class="level2">
<h2 id="what-the-scales-argument-does-h" class="anchored" data-anchor-id="what-the-scales-argument-does">What the scales argument does</h2>
<p>The three plots below differ in one argument:</p>
<div class="cell">
<div class="code-copy-outer-scaffold"><div class="sourceCode cell-code" id="cb6" style="background: #f1f3f5;"><pre class="sourceCode r code-with-copy"><code class="sourceCode r"><span id="cb6-1">p_counts <span class="ot" style="color: #003B4F;
background-color: null;
font-style: inherit;">&lt;-</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">ggplot</span>(teal, <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">aes</span>(year, count)) <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">+</span></span>
<span id="cb6-2">  <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">geom_point</span>(<span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">colour =</span> te_forest, <span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">alpha =</span> <span class="fl" style="color: #AD0000;
background-color: null;
font-style: inherit;">0.6</span>, <span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">size =</span> <span class="fl" style="color: #AD0000;
background-color: null;
font-style: inherit;">1.6</span>) <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">+</span></span>
<span id="cb6-3">  <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">geom_line</span>(<span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">aes</span>(<span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">y =</span> fitted), <span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">colour =</span> te_rust, <span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">linewidth =</span> <span class="fl" style="color: #AD0000;
background-color: null;
font-style: inherit;">0.9</span>) <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">+</span></span>
<span id="cb6-4">  <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">scale_x_continuous</span>(<span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">breaks =</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">c</span>(<span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">2014</span>, <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">2018</span>, <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">2022</span>)) <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">+</span></span>
<span id="cb6-5">  <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">labs</span>(<span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">x =</span> <span class="cn" style="color: #8f5902;
background-color: null;
font-style: inherit;">NULL</span>, <span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">y =</span> <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"teal counted"</span>) <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">+</span></span>
<span id="cb6-6">  <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">theme_datasheet</span>()</span>
<span id="cb6-7"></span>
<span id="cb6-8">p_fixed <span class="ot" style="color: #003B4F;
background-color: null;
font-style: inherit;">&lt;-</span> p_counts <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">+</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">facet_wrap</span>(<span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">~</span> site)                     <span class="co" style="color: #5E5E5E;
background-color: null;
font-style: inherit;"># the default: scales = "fixed"</span></span>
<span id="cb6-9">p_free  <span class="ot" style="color: #003B4F;
background-color: null;
font-style: inherit;">&lt;-</span> p_counts <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">+</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">facet_wrap</span>(<span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">~</span> site, <span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">scales =</span> <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"free_y"</span>)  <span class="co" style="color: #5E5E5E;
background-color: null;
font-style: inherit;"># each panel its own y range</span></span>
<span id="cb6-10">p_both  <span class="ot" style="color: #003B4F;
background-color: null;
font-style: inherit;">&lt;-</span> p_counts <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">+</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">facet_wrap</span>(<span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">~</span> site, <span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">scales =</span> <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"free"</span>)    <span class="co" style="color: #5E5E5E;
background-color: null;
font-style: inherit;"># x and y both free</span></span></code></pre></div></div>
</div>
<p>With <code>"fixed"</code>, every panel shares one y axis, wide enough for the largest count at any site. With <code>"free_y"</code>, each panel’s y axis runs over that panel’s own data, and the x axis stays shared. <code>"free"</code> frees both; here every site has the same twelve years, so it looks like <code>"free_y"</code>. Faceting is one component of the layered grammar that ggplot2 implements (Wickham 2010), and the ggplot2 book covers faceting and its scale options (Wickham 2016). The help page states the default, and the next chunk checks it and the two range rules against the built plots. <code>ggplot_build()</code> returns everything ggplot2 computed before drawing, including each panel’s y range after the default expansion, which pads a continuous axis by 5 per cent of its span at each end:</p>
<div class="cell">
<div class="code-copy-outer-scaffold"><div class="sourceCode cell-code" id="cb7" style="background: #f1f3f5;"><pre class="sourceCode r code-with-copy"><code class="sourceCode r"><span id="cb7-1">panel_ranges <span class="ot" style="color: #003B4F;
background-color: null;
font-style: inherit;">&lt;-</span> <span class="cf" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">function</span>(p) {</span>
<span id="cb7-2">  built <span class="ot" style="color: #003B4F;
background-color: null;
font-style: inherit;">&lt;-</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">ggplot_build</span>(p)</span>
<span id="cb7-3">  lay <span class="ot" style="color: #003B4F;
background-color: null;
font-style: inherit;">&lt;-</span> built<span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">$</span>layout<span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">$</span>layout                           <span class="co" style="color: #5E5E5E;
background-color: null;
font-style: inherit;"># one row per panel</span></span>
<span id="cb7-4">  ranges <span class="ot" style="color: #003B4F;
background-color: null;
font-style: inherit;">&lt;-</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">t</span>(<span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">sapply</span>(built<span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">$</span>layout<span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">$</span>panel_params, <span class="cf" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">function</span>(pp) pp<span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">$</span>y.range))</span>
<span id="cb7-5">  <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">rownames</span>(ranges) <span class="ot" style="color: #003B4F;
background-color: null;
font-style: inherit;">&lt;-</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">as.character</span>(lay<span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">$</span>site[<span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">order</span>(<span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">as.integer</span>(lay<span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">$</span>PANEL))])</span>
<span id="cb7-6">  ranges</span>
<span id="cb7-7">}</span>
<span id="cb7-8">pad <span class="ot" style="color: #003B4F;
background-color: null;
font-style: inherit;">&lt;-</span> <span class="cf" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">function</span>(r) r <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">+</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">c</span>(<span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">-</span><span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">1</span>, <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">1</span>) <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">*</span> <span class="fl" style="color: #AD0000;
background-color: null;
font-style: inherit;">0.05</span> <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">*</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">diff</span>(r)       <span class="co" style="color: #5E5E5E;
background-color: null;
font-style: inherit;"># the default expansion</span></span>
<span id="cb7-9"></span>
<span id="cb7-10"><span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">stopifnot</span>(<span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">identical</span>(<span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">formals</span>(facet_wrap)<span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">$</span>scales, <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"fixed"</span>))    <span class="co" style="color: #5E5E5E;
background-color: null;
font-style: inherit;"># the default</span></span>
<span id="cb7-11"></span>
<span id="cb7-12"><span class="co" style="color: #5E5E5E;
background-color: null;
font-style: inherit;"># fixed: every panel gets the range of all the data</span></span>
<span id="cb7-13">fixed_ranges <span class="ot" style="color: #003B4F;
background-color: null;
font-style: inherit;">&lt;-</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">panel_ranges</span>(p_fixed)</span>
<span id="cb7-14">all_data <span class="ot" style="color: #003B4F;
background-color: null;
font-style: inherit;">&lt;-</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">range</span>(teal<span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">$</span>count, teal<span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">$</span>fitted)</span>
<span id="cb7-15"><span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">stopifnot</span>(<span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">all</span>(<span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">apply</span>(fixed_ranges, <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">1</span>, <span class="cf" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">function</span>(r) <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">isTRUE</span>(<span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">all.equal</span>(r, <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">pad</span>(all_data))))))</span>
<span id="cb7-16"></span>
<span id="cb7-17"><span class="co" style="color: #5E5E5E;
background-color: null;
font-style: inherit;"># free_y: each panel gets the range of its own points and line</span></span>
<span id="cb7-18">free_ranges <span class="ot" style="color: #003B4F;
background-color: null;
font-style: inherit;">&lt;-</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">panel_ranges</span>(p_free)</span>
<span id="cb7-19"><span class="cf" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">for</span> (s <span class="cf" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">in</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">levels</span>(teal<span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">$</span>site)) {</span>
<span id="cb7-20">  own <span class="ot" style="color: #003B4F;
background-color: null;
font-style: inherit;">&lt;-</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">range</span>(teal<span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">$</span>count[teal<span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">$</span>site <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">==</span> s], teal<span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">$</span>fitted[teal<span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">$</span>site <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">==</span> s])</span>
<span id="cb7-21">  <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">stopifnot</span>(<span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">isTRUE</span>(<span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">all.equal</span>(free_ranges[s, ], <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">pad</span>(own), <span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">check.attributes =</span> <span class="cn" style="color: #8f5902;
background-color: null;
font-style: inherit;">FALSE</span>)))</span>
<span id="cb7-22">}</span>
<span id="cb7-23"></span>
<span id="cb7-24"><span class="co" style="color: #5E5E5E;
background-color: null;
font-style: inherit;"># free_y leaves x shared; panels follow the factor levels</span></span>
<span id="cb7-25">built_free <span class="ot" style="color: #003B4F;
background-color: null;
font-style: inherit;">&lt;-</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">ggplot_build</span>(p_free)</span>
<span id="cb7-26">x_ranges <span class="ot" style="color: #003B4F;
background-color: null;
font-style: inherit;">&lt;-</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">sapply</span>(built_free<span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">$</span>layout<span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">$</span>panel_params, <span class="cf" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">function</span>(pp) pp<span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">$</span>x.range)</span>
<span id="cb7-27"><span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">stopifnot</span>(<span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">all</span>(x_ranges <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">==</span> x_ranges[, <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">1</span>]),</span>
<span id="cb7-28">          <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">identical</span>(<span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">as.character</span>(built_free<span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">$</span>layout<span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">$</span>layout<span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">$</span>site), <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">levels</span>(teal<span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">$</span>site)))</span>
<span id="cb7-29"></span>
<span id="cb7-30"><span class="co" style="color: #5E5E5E;
background-color: null;
font-style: inherit;"># free: with the same years at every site, it matches free_y here</span></span>
<span id="cb7-31">both_x <span class="ot" style="color: #003B4F;
background-color: null;
font-style: inherit;">&lt;-</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">sapply</span>(<span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">ggplot_build</span>(p_both)<span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">$</span>layout<span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">$</span>panel_params, <span class="cf" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">function</span>(pp) pp<span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">$</span>x.range)</span>
<span id="cb7-32"><span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">stopifnot</span>(<span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">isTRUE</span>(<span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">all.equal</span>(<span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">panel_ranges</span>(p_both), free_ranges)), <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">all</span>(both_x <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">==</span> x_ranges))</span>
<span id="cb7-33"><span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">round</span>(<span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">cbind</span>(fixed_ranges[, <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">2</span>], free_ranges), <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">1</span>)</span></code></pre></div></div>
<div class="cell-output cell-output-stdout">
<pre><code>              [,1]  [,2]  [,3]
Mill Pond    575.4 436.7 553.3
Reed Bed     575.4 164.1 205.9
Fen Edge     575.4  38.5  92.4
Gravel Pit   575.4  35.8  62.2
North Marsh  575.4   2.1  20.9
Ditch Meadow 575.4   0.6   8.3</code></pre>
</div>
</div>
<p>Under the default, every panel runs up to 575 birds; under <code>"free_y"</code>, Ditch Meadow’s panel stops at 8.3. The panels come out in the order of the factor levels, which is set here by hand; <a href="https://tidyecology.com/posts/factor-levels-in-r/">Factor levels in R</a> covers how.</p>
</section>
<section id="measuring-what-the-eye-compares" class="level2">
<h2 id="measuring-what-the-eye-compares-h" class="anchored" data-anchor-id="measuring-what-the-eye-compares">Measuring what the eye compares</h2>
<p>A reader looking at the facets compares how far each trend line falls or rises across its panel. That can be measured: the change of the fitted line from 2013 to 2024, divided by the height of the panel it is drawn in. A value of -0.5 means the line falls through half the panel. The function reads the panel heights from the built plot, so it measures exactly what is drawn:</p>
<div class="cell">
<div class="code-copy-outer-scaffold"><div class="sourceCode cell-code" id="cb9" style="background: #f1f3f5;"><pre class="sourceCode r code-with-copy"><code class="sourceCode r"><span id="cb9-1">line_move <span class="ot" style="color: #003B4F;
background-color: null;
font-style: inherit;">&lt;-</span> <span class="cf" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">function</span>(p, yvar) {</span>
<span id="cb9-2">  ranges <span class="ot" style="color: #003B4F;
background-color: null;
font-style: inherit;">&lt;-</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">panel_ranges</span>(p)</span>
<span id="cb9-3">  heights <span class="ot" style="color: #003B4F;
background-color: null;
font-style: inherit;">&lt;-</span> ranges[, <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">2</span>] <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">-</span> ranges[, <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">1</span>]</span>
<span id="cb9-4">  move <span class="ot" style="color: #003B4F;
background-color: null;
font-style: inherit;">&lt;-</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">setNames</span>(last[[yvar]] <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">-</span> first[[yvar]], <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">as.character</span>(first<span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">$</span>site))</span>
<span id="cb9-5">  (move <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">/</span> heights[<span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">names</span>(move)])[<span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">levels</span>(teal<span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">$</span>site)]</span>
<span id="cb9-6">}</span>
<span id="cb9-7"></span>
<span id="cb9-8">moves <span class="ot" style="color: #003B4F;
background-color: null;
font-style: inherit;">&lt;-</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">data.frame</span>(<span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">true_change   =</span> sites<span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">$</span>change,</span>
<span id="cb9-9">                    <span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">fitted_change =</span> fitted_change[sites<span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">$</span>site],</span>
<span id="cb9-10">                    <span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">fixed         =</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">line_move</span>(p_fixed, <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"fitted"</span>),</span>
<span id="cb9-11">                    <span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">free_y        =</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">line_move</span>(p_free, <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"fitted"</span>),</span>
<span id="cb9-12">                    <span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">row.names     =</span> sites<span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">$</span>site)</span>
<span id="cb9-13"><span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">round</span>(moves, <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">3</span>)</span></code></pre></div></div>
<div class="cell-output cell-output-stdout">
<pre><code>             true_change fitted_change  fixed free_y
Mill Pond           -0.1        -0.045 -0.037 -0.191
Reed Bed             0.0        -0.058 -0.018 -0.259
Fen Edge            -0.4        -0.398 -0.057 -0.640
Gravel Pit           0.3         0.203  0.014  0.328
North Marsh         -0.7        -0.628 -0.019 -0.595
Ditch Meadow        -0.2        -0.233 -0.002 -0.135</code></pre>
</div>
<div class="code-copy-outer-scaffold"><div class="sourceCode cell-code" id="cb11" style="background: #f1f3f5;"><pre class="sourceCode r code-with-copy"><code class="sourceCode r"><span id="cb11-1">rank_fixed <span class="ot" style="color: #003B4F;
background-color: null;
font-style: inherit;">&lt;-</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">cor</span>(moves<span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">$</span>fixed,  moves<span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">$</span>true_change, <span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">method =</span> <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"spearman"</span>)</span>
<span id="cb11-2">rank_free  <span class="ot" style="color: #003B4F;
background-color: null;
font-style: inherit;">&lt;-</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">cor</span>(moves<span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">$</span>free_y, moves<span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">$</span>true_change, <span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">method =</span> <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"spearman"</span>)</span>
<span id="cb11-3">steep_free <span class="ot" style="color: #003B4F;
background-color: null;
font-style: inherit;">&lt;-</span> moves[<span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"North Marsh"</span>, <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"free_y"</span>] <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">/</span> moves[<span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"Mill Pond"</span>, <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"free_y"</span>]</span>
<span id="cb11-4">steep_fit  <span class="ot" style="color: #003B4F;
background-color: null;
font-style: inherit;">&lt;-</span> moves[<span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"North Marsh"</span>, <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"fitted_change"</span>] <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">/</span> moves[<span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"Mill Pond"</span>, <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"fitted_change"</span>]</span>
<span id="cb11-5"><span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">round</span>(<span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">c</span>(<span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">rank_fixed =</span> rank_fixed, <span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">rank_free =</span> rank_free, <span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">steep_free =</span> steep_free), <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">2</span>)</span></code></pre></div></div>
<div class="cell-output cell-output-stdout">
<pre><code>rank_fixed  rank_free steep_free 
      0.60       0.71       3.11 </code></pre>
</div>
</div>
<div class="cell">
<div class="cell-output-display">
<div id="fig-free-y" class="quarto-float quarto-figure quarto-figure-center anchored" alt="Six panels of simulated teal counts from 2013 to 2024, each with its own y axis: Mill Pond runs from about 440 to 550, Reed Bed 165 to 205, Fen Edge 40 to 90, Gravel Pit 37 to 61, North Marsh 3 to 20 and Ditch Meadow 1 to 8. Each panel has green points and a red fitted trend line. The strips read: Mill Pond true -10%, line falls 19% of panel; Reed Bed true +0%, line falls 26%; Fen Edge true -40%, line falls 64%; Gravel Pit true +30%, line rises 33%; North Marsh true -70%, line falls 60%; Ditch Meadow true -20%, line falls 13%. The Fen Edge and North Marsh lines look about equally steep.">
<figure class="quarto-float quarto-float-fig figure">
<div aria-describedby="fig-free-y-caption-0ceaefa1-69ba-4598-a22c-09a6ac19f8ca">
<img src="https://tidyecology.com/posts/fixed-or-free-scales-in-facets/index_files/figure-html/fig-free-y-1.png" class="img-fluid figure-img" alt="Six panels of simulated teal counts from 2013 to 2024, each with its own y axis: Mill Pond runs from about 440 to 550, Reed Bed 165 to 205, Fen Edge 40 to 90, Gravel Pit 37 to 61, North Marsh 3 to 20 and Ditch Meadow 1 to 8. Each panel has green points and a red fitted trend line. The strips read: Mill Pond true -10%, line falls 19% of panel; Reed Bed true +0%, line falls 26%; Fen Edge true -40%, line falls 64%; Gravel Pit true +30%, line rises 33%; North Marsh true -70%, line falls 60%; Ditch Meadow true -20%, line falls 13%. The Fen Edge and North Marsh lines look about equally steep." width="720">
</div>
<figcaption class="quarto-float-caption-bottom quarto-float-caption quarto-float-fig" id="fig-free-y-caption-0ceaefa1-69ba-4598-a22c-09a6ac19f8ca">
Figure&nbsp;1: Simulated teal counts at six sites with a fitted log-linear trend per site, drawn with free y scales in facet_wrap(). Each strip gives the true change built into the simulation and how far the fitted line moves as a share of its own panel height.
</figcaption>
</figure>
</div>
</div>
</div>
<p>Under <code>"free_y"</code> two very different declines are drawn alike. North Marsh, which lost 70 per cent of its birds by design, has a line that falls 60 per cent of its panel; Fen Edge (true -40 per cent) falls 64 per cent, slightly more. Mill Pond (true -10 per cent) falls 19 per cent, so North Marsh’s line is drawn 3.1 times as steep as Mill Pond’s, while its fitted change is 14.0 times as large. And Reed Bed, flat by design, gets a line that falls 26 per cent of its panel, more than Mill Pond’s: a fitted change of -5.8 per cent stretched to fill the space.</p>
<p>The default errs the other way. With one axis up to 575 birds, every line barely moves (none by more than 6 per cent of the panel), and the order follows birds, not per cent: North Marsh’s falls 1.9 per cent of the panel and Ditch Meadow’s 0.2 per cent, while Mill Pond’s falls 3.7 per cent. On the fixed axis the 10 per cent decline at the big site is drawn steeper than the 70 per cent decline at the small one.</p>
<p>The rank correlation between the drawn move and the true change is 0.71 under <code>"free_y"</code> and 0.60 under the default (1 would be a perfect ordering). So <code>"free_y"</code> keeps the rough order of the sites, but not the size of the differences between them. One simulated data set could be a lucky or an unlucky one, so the next chunk repeats the design on fresh data a thousand times. It computes the panel ranges with the rule the guard chunk checked, instead of building a thousand plots:</p>
<div class="cell">
<div class="code-copy-outer-scaffold"><div class="sourceCode cell-code" id="cb13" style="background: #f1f3f5;"><pre class="sourceCode r code-with-copy"><code class="sourceCode r"><span id="cb13-1">one_survey <span class="ot" style="color: #003B4F;
background-color: null;
font-style: inherit;">&lt;-</span> <span class="cf" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">function</span>() {</span>
<span id="cb13-2">  per_site <span class="ot" style="color: #003B4F;
background-color: null;
font-style: inherit;">&lt;-</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">t</span>(<span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">sapply</span>(<span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">seq_len</span>(<span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">nrow</span>(sites)), <span class="cf" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">function</span>(i) {</span>
<span id="cb13-3">    mu <span class="ot" style="color: #003B4F;
background-color: null;
font-style: inherit;">&lt;-</span> sites<span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">$</span>start[i] <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">*</span> (<span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">1</span> <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">+</span> sites<span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">$</span>change[i])<span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">^</span>((years <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">-</span> <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">2013</span>) <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">/</span> <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">11</span>)</span>
<span id="cb13-4">    y  <span class="ot" style="color: #003B4F;
background-color: null;
font-style: inherit;">&lt;-</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">rpois</span>(<span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">length</span>(years), mu)</span>
<span id="cb13-5">    f  <span class="ot" style="color: #003B4F;
background-color: null;
font-style: inherit;">&lt;-</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">fitted</span>(<span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">glm</span>(y <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">~</span> years, <span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">family =</span> poisson))</span>
<span id="cb13-6">    <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">c</span>(<span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">first =</span> f[[<span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">1</span>]], <span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">last =</span> f[[<span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">length</span>(f)]], <span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">low =</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">min</span>(y, f), <span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">high =</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">max</span>(y, f),</span>
<span id="cb13-7">      <span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">ilow =</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">min</span>(y, f) <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">/</span> f[[<span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">1</span>]], <span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">ihigh =</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">max</span>(y, f) <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">/</span> f[[<span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">1</span>]])</span>
<span id="cb13-8">  }))</span>
<span id="cb13-9">  change <span class="ot" style="color: #003B4F;
background-color: null;
font-style: inherit;">&lt;-</span> per_site[, <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"last"</span>] <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">-</span> per_site[, <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"first"</span>]</span>
<span id="cb13-10">  free   <span class="ot" style="color: #003B4F;
background-color: null;
font-style: inherit;">&lt;-</span> change <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">/</span> (<span class="fl" style="color: #AD0000;
background-color: null;
font-style: inherit;">1.1</span> <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">*</span> (per_site[, <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"high"</span>] <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">-</span> per_site[, <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"low"</span>]))</span>
<span id="cb13-11">  fixed  <span class="ot" style="color: #003B4F;
background-color: null;
font-style: inherit;">&lt;-</span> change <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">/</span> (<span class="fl" style="color: #AD0000;
background-color: null;
font-style: inherit;">1.1</span> <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">*</span> (<span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">max</span>(per_site[, <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"high"</span>]) <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">-</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">min</span>(per_site[, <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"low"</span>])))</span>
<span id="cb13-12">  index  <span class="ot" style="color: #003B4F;
background-color: null;
font-style: inherit;">&lt;-</span> (per_site[, <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"last"</span>] <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">/</span> per_site[, <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"first"</span>] <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">-</span> <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">1</span>) <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">/</span></span>
<span id="cb13-13">            (<span class="fl" style="color: #AD0000;
background-color: null;
font-style: inherit;">1.1</span> <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">*</span> (<span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">max</span>(per_site[, <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"ihigh"</span>]) <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">-</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">min</span>(per_site[, <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"ilow"</span>])))</span>
<span id="cb13-14">  <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">c</span>(<span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">fixed =</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">cor</span>(fixed, sites<span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">$</span>change, <span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">method =</span> <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"spearman"</span>),</span>
<span id="cb13-15">    <span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">free_y =</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">cor</span>(free, sites<span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">$</span>change, <span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">method =</span> <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"spearman"</span>),</span>
<span id="cb13-16">    <span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">index =</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">cor</span>(index, sites<span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">$</span>change, <span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">method =</span> <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"spearman"</span>),</span>
<span id="cb13-17">    <span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">steep_free =</span> free[<span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">5</span>] <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">/</span> free[<span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">1</span>], <span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">f =</span> free)          <span class="co" style="color: #5E5E5E;
background-color: null;
font-style: inherit;"># f1 to f6: each panel's drawn move</span></span>
<span id="cb13-18">}</span>
<span id="cb13-19"></span>
<span id="cb13-20"><span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">set.seed</span>(<span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">2015</span>)</span>
<span id="cb13-21">reps <span class="ot" style="color: #003B4F;
background-color: null;
font-style: inherit;">&lt;-</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">replicate</span>(<span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">1000</span>, <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">one_survey</span>())</span>
<span id="cb13-22">rank_medians <span class="ot" style="color: #003B4F;
background-color: null;
font-style: inherit;">&lt;-</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">apply</span>(reps[<span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">1</span><span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">:</span><span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">3</span>, ], <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">1</span>, median)</span>
<span id="cb13-23">under_two <span class="ot" style="color: #003B4F;
background-color: null;
font-style: inherit;">&lt;-</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">mean</span>(<span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">abs</span>(reps[<span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"steep_free"</span>, ]) <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">&lt;</span> <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">2</span>)</span>
<span id="cb13-24">under_two_mcse <span class="ot" style="color: #003B4F;
background-color: null;
font-style: inherit;">&lt;-</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">sqrt</span>(under_two <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">*</span> (<span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">1</span> <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">-</span> under_two) <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">/</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">ncol</span>(reps))</span>
<span id="cb13-25">as_steep <span class="ot" style="color: #003B4F;
background-color: null;
font-style: inherit;">&lt;-</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">mean</span>(<span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">abs</span>(reps[<span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"steep_free"</span>, ]) <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">&gt;=</span> steep_free)   <span class="co" style="color: #5E5E5E;
background-color: null;
font-style: inherit;"># as kind as the data set above</span></span>
<span id="cb13-26">free_reps <span class="ot" style="color: #003B4F;
background-color: null;
font-style: inherit;">&lt;-</span> reps[<span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">paste0</span>(<span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"f"</span>, <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">1</span><span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">:</span><span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">6</span>), ]</span>
<span id="cb13-27"><span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">rownames</span>(free_reps) <span class="ot" style="color: #003B4F;
background-color: null;
font-style: inherit;">&lt;-</span> sites<span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">$</span>site</span>
<span id="cb13-28">typical_move <span class="ot" style="color: #003B4F;
background-color: null;
font-style: inherit;">&lt;-</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">apply</span>(free_reps, <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">1</span>, median)</span>
<span id="cb13-29">nm_less_steep <span class="ot" style="color: #003B4F;
background-color: null;
font-style: inherit;">&lt;-</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">mean</span>(free_reps[<span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"North Marsh"</span>, ] <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">&gt;</span> free_reps[<span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"Mill Pond"</span>, ])</span>
<span id="cb13-30"><span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">round</span>(<span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">c</span>(rank_medians, <span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">steep_free_median =</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">median</span>(reps[<span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"steep_free"</span>, ]),</span>
<span id="cb13-31">        <span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">share_under_2 =</span> under_two, <span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">mc_se =</span> under_two_mcse, <span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">as_steep =</span> as_steep,</span>
<span id="cb13-32">        <span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">nm_less_steep =</span> nm_less_steep), <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">3</span>)</span></code></pre></div></div>
<div class="cell-output cell-output-stdout">
<pre><code>            fixed            free_y             index steep_free_median 
            0.543             0.829             0.943             1.300 
    share_under_2             mc_se          as_steep     nm_less_steep 
            0.831             0.012             0.048             0.194 </code></pre>
</div>
<div class="code-copy-outer-scaffold"><div class="sourceCode cell-code" id="cb15" style="background: #f1f3f5;"><pre class="sourceCode r code-with-copy"><code class="sourceCode r"><span id="cb15-1"><span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">round</span>(typical_move, <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">2</span>)</span></code></pre></div></div>
<div class="cell-output cell-output-stdout">
<pre><code>   Mill Pond     Reed Bed     Fen Edge   Gravel Pit  North Marsh Ditch Meadow 
       -0.55        -0.01        -0.71         0.44        -0.71        -0.17 </code></pre>
</div>
</div>
<p>Over a thousand simulated surveys the median rank correlation is 0.83 under <code>"free_y"</code> and 0.54 under the default: the order survives a free scale better than a fixed one. The sizes do not. The median ratio of North Marsh’s drawn fall to Mill Pond’s under <code>"free_y"</code> is 1.3, against a true ratio of 7, and in 83 per cent of surveys (Monte Carlo standard error 1.2 percentage points) the site that lost 70 per cent is drawn less than twice as steep as the site that lost 10; in 19 per cent it is drawn less steep. The figure above is a mild case for <code>"free_y"</code>. In a typical survey Mill Pond’s line falls 55 per cent of its panel, not the 19 per cent in the figure, while North Marsh’s falls 71 and Fen Edge’s 71; only 4.8 per cent of the surveys drew North Marsh’s line at least 3.1 times as steep as Mill Pond’s.</p>
<p>The reason is in the range rule checked above. A free panel runs from the lowest to the highest value at that site, so its height is the site’s change plus its year-to-year noise, and the share of the panel the line takes up depends on how large the change is compared with that noise. A Poisson count has a standard deviation equal to the square root of its mean:</p>
<div class="cell">
<div class="code-copy-outer-scaffold"><div class="sourceCode cell-code" id="cb17" style="background: #f1f3f5;"><pre class="sourceCode r code-with-copy"><code class="sourceCode r"><span id="cb17-1">change_birds <span class="ot" style="color: #003B4F;
background-color: null;
font-style: inherit;">&lt;-</span> sites<span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">$</span>start <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">*</span> sites<span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">$</span>change   <span class="co" style="color: #5E5E5E;
background-color: null;
font-style: inherit;"># true change in birds, 2013 to 2024</span></span>
<span id="cb17-2">noise_sd     <span class="ot" style="color: #003B4F;
background-color: null;
font-style: inherit;">&lt;-</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">sqrt</span>(sites<span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">$</span>start)            <span class="co" style="color: #5E5E5E;
background-color: null;
font-style: inherit;"># Poisson SD at the 2013 count</span></span>
<span id="cb17-3"><span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">names</span>(change_birds) <span class="ot" style="color: #003B4F;
background-color: null;
font-style: inherit;">&lt;-</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">names</span>(noise_sd) <span class="ot" style="color: #003B4F;
background-color: null;
font-style: inherit;">&lt;-</span> sites<span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">$</span>site</span>
<span id="cb17-4">in_noise_units <span class="ot" style="color: #003B4F;
background-color: null;
font-style: inherit;">&lt;-</span> change_birds <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">/</span> noise_sd</span>
<span id="cb17-5"><span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">round</span>(<span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">rbind</span>(change_birds, noise_sd, in_noise_units), <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">2</span>)</span></code></pre></div></div>
<div class="cell-output cell-output-stdout">
<pre><code>               Mill Pond Reed Bed Fen Edge Gravel Pit North Marsh Ditch Meadow
change_birds      -52.00     0.00   -36.00      12.00      -14.00        -1.20
noise_sd           22.80    13.42     9.49       6.32        4.47         2.45
in_noise_units     -2.28     0.00    -3.79       1.90       -3.13        -0.49</code></pre>
</div>
<div class="code-copy-outer-scaffold"><div class="sourceCode cell-code" id="cb19" style="background: #f1f3f5;"><pre class="sourceCode r code-with-copy"><code class="sourceCode r"><span id="cb19-1"><span class="co" style="color: #5E5E5E;
background-color: null;
font-style: inherit;"># which ranking does the drawn move under free_y follow, over the thousand surveys?</span></span>
<span id="cb19-2">rank_noise <span class="ot" style="color: #003B4F;
background-color: null;
font-style: inherit;">&lt;-</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">median</span>(<span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">apply</span>(free_reps, <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">2</span>, cor, <span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">y =</span> in_noise_units, <span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">method =</span> <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"spearman"</span>))</span>
<span id="cb19-3">rank_true  <span class="ot" style="color: #003B4F;
background-color: null;
font-style: inherit;">&lt;-</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">median</span>(<span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">apply</span>(free_reps, <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">2</span>, cor, <span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">y =</span> sites<span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">$</span>change, <span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">method =</span> <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"spearman"</span>))</span>
<span id="cb19-4"><span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">round</span>(<span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">c</span>(<span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">rank_noise =</span> rank_noise, <span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">rank_true =</span> rank_true), <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">2</span>)</span></code></pre></div></div>
<div class="cell-output cell-output-stdout">
<pre><code>rank_noise  rank_true 
      0.94       0.83 </code></pre>
</div>
<div class="code-copy-outer-scaffold"><div class="sourceCode cell-code" id="cb21" style="background: #f1f3f5;"><pre class="sourceCode r code-with-copy"><code class="sourceCode r"><span id="cb21-1"><span class="co" style="color: #5E5E5E;
background-color: null;
font-style: inherit;"># the ceiling: a line can never cross more than 1/1.1 of its own free panel</span></span>
<span id="cb21-2"><span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">stopifnot</span>(<span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">all</span>(<span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">abs</span>(moves<span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">$</span>free_y) <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">&lt;=</span> <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">1</span> <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">/</span> <span class="fl" style="color: #AD0000;
background-color: null;
font-style: inherit;">1.1</span>),</span>
<span id="cb21-3">          <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">all</span>(<span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">abs</span>(free_reps) <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">&lt;=</span> <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">1</span> <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">/</span> <span class="fl" style="color: #AD0000;
background-color: null;
font-style: inherit;">1.1</span> <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">+</span> <span class="fl" style="color: #AD0000;
background-color: null;
font-style: inherit;">1e-12</span>))</span></code></pre></div></div>
</div>
<p>At Mill Pond a 10 per cent decline is 52 birds against a standard deviation of 22.8 at the 2013 count, or 2.3 standard deviations. At North Marsh a 70 per cent decline is 14 birds against 4.5, or 3.1 standard deviations. Ranked by the change in standard deviations, the sites line up with their drawn lines better than when ranked by the true change: over the thousand surveys the median rank correlation with the drawn move is 0.94, against 0.83 for the true change.</p>
<p>The sizes are squeezed for a second reason, which needs no simulation. A free panel’s range is set by the points and the fitted line together, so both ends of the line lie inside it, and the default expansion makes the panel 1.1 times that range. A line can therefore never move more than 1/1.1 of its panel, 91 per cent, however large the change; the <code>stopifnot()</code> at the end of the chunk checks this for the figure and for all 6000 simulated panels. A decline that is large against its noise already uses up much of the room under that ceiling, and a still larger one has little left to add: in the typical survey North Marsh (true -70 per cent) falls 71 per cent of its panel and Fen Edge (true -40 per cent) 71 per cent, out of a possible 91. What the eye reads off a free panel is the change measured against the site’s own noise, squeezed under a fixed ceiling, not the change in birds or in per cent. Cleveland and McGill (1984) found that readers judge positions along a common scale more accurately than positions along separate scales that are not aligned; free panels go one step further and give each panel a different scale as well.</p>
</section>
<section id="the-fix-put-the-comparison-on-the-y-axis" class="level2">
<h2 id="the-fix-put-the-comparison-on-the-y-axis-h" class="anchored" data-anchor-id="the-fix-put-the-comparison-on-the-y-axis">The fix: put the comparison on the y axis</h2>
<p>If the question is “which site changed most, relative to its size”, the y axis should carry that quantity, and then one shared axis is what makes the panels comparable. Dividing each count by the site’s fitted 2013 value turns every series into an index that starts near 1; <code>ave()</code> does it within each site in one line. <code>scales</code> stays at its default:</p>
<div class="cell">
<div class="code-copy-outer-scaffold"><div class="sourceCode cell-code" id="cb22" style="background: #f1f3f5;"><pre class="sourceCode r code-with-copy"><code class="sourceCode r"><span id="cb22-1">teal<span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">$</span>first_fit <span class="ot" style="color: #003B4F;
background-color: null;
font-style: inherit;">&lt;-</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">ave</span>(teal<span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">$</span>fitted, teal<span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">$</span>site, <span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">FUN =</span> <span class="cf" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">function</span>(v) v[<span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">1</span>])</span>
<span id="cb22-2">teal<span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">$</span>index     <span class="ot" style="color: #003B4F;
background-color: null;
font-style: inherit;">&lt;-</span> teal<span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">$</span>count <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">/</span> teal<span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">$</span>first_fit</span>
<span id="cb22-3">teal<span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">$</span>index_fit <span class="ot" style="color: #003B4F;
background-color: null;
font-style: inherit;">&lt;-</span> teal<span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">$</span>fitted <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">/</span> teal<span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">$</span>first_fit</span>
<span id="cb22-4">first <span class="ot" style="color: #003B4F;
background-color: null;
font-style: inherit;">&lt;-</span> teal[teal<span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">$</span>year <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">==</span> <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">2013</span>, ]</span>
<span id="cb22-5">last  <span class="ot" style="color: #003B4F;
background-color: null;
font-style: inherit;">&lt;-</span> teal[teal<span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">$</span>year <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">==</span> <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">2024</span>, ]</span>
<span id="cb22-6"></span>
<span id="cb22-7">p_index <span class="ot" style="color: #003B4F;
background-color: null;
font-style: inherit;">&lt;-</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">ggplot</span>(teal, <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">aes</span>(year, index)) <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">+</span></span>
<span id="cb22-8">  <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">geom_hline</span>(<span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">yintercept =</span> <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">1</span>, <span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">colour =</span> te_line, <span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">linewidth =</span> <span class="fl" style="color: #AD0000;
background-color: null;
font-style: inherit;">0.8</span>) <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">+</span></span>
<span id="cb22-9">  <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">geom_point</span>(<span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">colour =</span> te_forest, <span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">alpha =</span> <span class="fl" style="color: #AD0000;
background-color: null;
font-style: inherit;">0.6</span>, <span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">size =</span> <span class="fl" style="color: #AD0000;
background-color: null;
font-style: inherit;">1.6</span>) <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">+</span></span>
<span id="cb22-10">  <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">geom_line</span>(<span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">aes</span>(<span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">y =</span> index_fit), <span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">colour =</span> te_rust, <span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">linewidth =</span> <span class="fl" style="color: #AD0000;
background-color: null;
font-style: inherit;">0.9</span>) <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">+</span></span>
<span id="cb22-11">  <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">scale_x_continuous</span>(<span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">breaks =</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">c</span>(<span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">2014</span>, <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">2018</span>, <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">2022</span>)) <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">+</span></span>
<span id="cb22-12">  <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">facet_wrap</span>(<span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">~</span> site) <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">+</span></span>
<span id="cb22-13">  <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">labs</span>(<span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">x =</span> <span class="cn" style="color: #8f5902;
background-color: null;
font-style: inherit;">NULL</span>, <span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">y =</span> <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"count / fitted 2013 count"</span>) <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">+</span></span>
<span id="cb22-14">  <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">theme_datasheet</span>()</span>
<span id="cb22-15"></span>
<span id="cb22-16">moves<span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">$</span>index <span class="ot" style="color: #003B4F;
background-color: null;
font-style: inherit;">&lt;-</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">line_move</span>(p_index, <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"index_fit"</span>)</span>
<span id="cb22-17">index_height <span class="ot" style="color: #003B4F;
background-color: null;
font-style: inherit;">&lt;-</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">diff</span>(<span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">panel_ranges</span>(p_index)[<span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">1</span>, ])</span>
<span id="cb22-18"><span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">stopifnot</span>(<span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">isTRUE</span>(<span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">all.equal</span>(moves<span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">$</span>index <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">*</span> index_height, moves<span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">$</span>fitted_change)))</span>
<span id="cb22-19">rank_index <span class="ot" style="color: #003B4F;
background-color: null;
font-style: inherit;">&lt;-</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">cor</span>(moves<span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">$</span>index, moves<span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">$</span>true_change, <span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">method =</span> <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"spearman"</span>)</span>
<span id="cb22-20">index_top <span class="ot" style="color: #003B4F;
background-color: null;
font-style: inherit;">&lt;-</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">names</span>(<span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">which.max</span>(<span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">tapply</span>(teal<span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">$</span>index, teal<span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">$</span>site, max)))   <span class="co" style="color: #5E5E5E;
background-color: null;
font-style: inherit;"># who sets the top</span></span>
<span id="cb22-21"><span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">stopifnot</span>(index_top <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">==</span> sites<span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">$</span>site[<span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">which.min</span>(sites<span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">$</span>start)])          <span class="co" style="color: #5E5E5E;
background-color: null;
font-style: inherit;"># the smallest site</span></span>
<span id="cb22-22"><span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">round</span>(moves[, <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">c</span>(<span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"true_change"</span>, <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"fitted_change"</span>, <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"index"</span>)], <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">3</span>)</span></code></pre></div></div>
<div class="cell-output cell-output-stdout">
<pre><code>             true_change fitted_change  index
Mill Pond           -0.1        -0.045 -0.025
Reed Bed             0.0        -0.058 -0.032
Fen Edge            -0.4        -0.398 -0.223
Gravel Pit           0.3         0.203  0.113
North Marsh         -0.7        -0.628 -0.351
Ditch Meadow        -0.2        -0.233 -0.130</code></pre>
</div>
</div>
<div class="cell">
<div class="cell-output-display">
<div id="fig-index" class="quarto-float quarto-figure quarto-figure-center anchored" alt="The same six sites on one shared y axis of count divided by the fitted 2013 count, running from about 0.2 to 1.8, with a grey line at 1 in each panel. The red lines of Mill Pond and Reed Bed stay almost on the grey line (each falls 3% of panel), Fen Edge falls to about 0.6 (22%), Gravel Pit rises to about 1.2 (11%), North Marsh falls to under 0.4 (35%) and Ditch Meadow falls to under 0.8 (13%), with its points scattered from about 0.2 to 1.8.">
<figure class="quarto-float quarto-float-fig figure">
<div aria-describedby="fig-index-caption-0ceaefa1-69ba-4598-a22c-09a6ac19f8ca">
<img src="https://tidyecology.com/posts/fixed-or-free-scales-in-facets/index_files/figure-html/fig-index-1.png" class="img-fluid figure-img" alt="The same six sites on one shared y axis of count divided by the fitted 2013 count, running from about 0.2 to 1.8, with a grey line at 1 in each panel. The red lines of Mill Pond and Reed Bed stay almost on the grey line (each falls 3% of panel), Fen Edge falls to about 0.6 (22%), Gravel Pit rises to about 1.2 (11%), North Marsh falls to under 0.4 (35%) and Ditch Meadow falls to under 0.8 (13%), with its points scattered from about 0.2 to 1.8." width="720">
</div>
<figcaption class="quarto-float-caption-bottom quarto-float-caption quarto-float-fig" id="fig-index-caption-0ceaefa1-69ba-4598-a22c-09a6ac19f8ca">
Figure&nbsp;2: The same simulated counts divided by each site’s fitted 2013 value and drawn with the default fixed scales. The grey line marks no change. The strips give the true change and how far the fitted line now moves as a share of the common panel height.
</figcaption>
</figure>
</div>
</div>
</div>
<p>On the index scale every panel has the same height, 1.79 index units, so the drawn move of each line is its fitted change divided by one common number; the check in the chunk confirms it. North Marsh’s line now falls 35 per cent of the panel and Mill Pond’s 3 per cent, and the rank correlation with the true change is 0.94 (median over the thousand surveys: 0.94). What is left of the disagreement with the true changes is the sampling noise in the fitted trends, and every version of the figure carries that. The common height comes from the extremes of all six series, and the highest point of all, an index value of 1.79, is Ditch Meadow’s: the smallest site has the noisiest index.</p>
<p>A log axis with fixed scales does a similar job, because equal ratios become equal distances:</p>
<div class="cell">
<div class="code-copy-outer-scaffold"><div class="sourceCode cell-code" id="cb24" style="background: #f1f3f5;"><pre class="sourceCode r code-with-copy"><code class="sourceCode r"><span id="cb24-1">p_log <span class="ot" style="color: #003B4F;
background-color: null;
font-style: inherit;">&lt;-</span> p_fixed <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">+</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">scale_y_log10</span>()</span>
<span id="cb24-2">log_height <span class="ot" style="color: #003B4F;
background-color: null;
font-style: inherit;">&lt;-</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">diff</span>(<span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">panel_ranges</span>(p_log)[<span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">1</span>, ])           <span class="co" style="color: #5E5E5E;
background-color: null;
font-style: inherit;"># in log10 units</span></span>
<span id="cb24-3">log_change <span class="ot" style="color: #003B4F;
background-color: null;
font-style: inherit;">&lt;-</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">setNames</span>(<span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">log10</span>(last<span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">$</span>fitted) <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">-</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">log10</span>(first<span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">$</span>fitted), <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">as.character</span>(first<span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">$</span>site))</span>
<span id="cb24-4">moves<span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">$</span>log10 <span class="ot" style="color: #003B4F;
background-color: null;
font-style: inherit;">&lt;-</span> log_change[<span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">levels</span>(teal<span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">$</span>site)] <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">/</span> log_height</span>
<span id="cb24-5">rank_log <span class="ot" style="color: #003B4F;
background-color: null;
font-style: inherit;">&lt;-</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">cor</span>(moves<span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">$</span>log10, moves<span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">$</span>true_change, <span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">method =</span> <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"spearman"</span>)</span>
<span id="cb24-6"></span>
<span id="cb24-7"><span class="co" style="color: #5E5E5E;
background-color: null;
font-style: inherit;"># a zero count on a log axis</span></span>
<span id="cb24-8">zero_plot <span class="ot" style="color: #003B4F;
background-color: null;
font-style: inherit;">&lt;-</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">ggplot</span>(<span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">data.frame</span>(<span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">year =</span> <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">1</span><span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">:</span><span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">3</span>, <span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">count =</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">c</span>(<span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">3</span>, <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">0</span>, <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">2</span>)), <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">aes</span>(year, count)) <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">+</span></span>
<span id="cb24-9">  <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">geom_point</span>() <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">+</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">scale_y_log10</span>()</span>
<span id="cb24-10">zero_warn <span class="ot" style="color: #003B4F;
background-color: null;
font-style: inherit;">&lt;-</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">character</span>(<span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">0</span>)</span>
<span id="cb24-11">zero_built <span class="ot" style="color: #003B4F;
background-color: null;
font-style: inherit;">&lt;-</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">withCallingHandlers</span>(<span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">ggplot_build</span>(zero_plot), <span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">warning =</span> <span class="cf" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">function</span>(w) {</span>
<span id="cb24-12">  zero_warn <span class="ot" style="color: #003B4F;
background-color: null;
font-style: inherit;">&lt;&lt;-</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">c</span>(zero_warn, <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">conditionMessage</span>(w)); <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">invokeRestart</span>(<span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"muffleWarning"</span>) })</span>
<span id="cb24-13">zero_grob <span class="ot" style="color: #003B4F;
background-color: null;
font-style: inherit;">&lt;-</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">suppressWarnings</span>(<span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">ggplotGrob</span>(zero_plot))</span>
<span id="cb24-14">zero_panel <span class="ot" style="color: #003B4F;
background-color: null;
font-style: inherit;">&lt;-</span> zero_grob<span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">$</span>grobs[[<span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">which</span>(zero_grob<span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">$</span>layout<span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">$</span>name <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">==</span> <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"panel"</span>)]]</span>
<span id="cb24-15">zero_points <span class="ot" style="color: #003B4F;
background-color: null;
font-style: inherit;">&lt;-</span> zero_panel<span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">$</span>children[[<span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">grep</span>(<span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"point"</span>, <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">names</span>(zero_panel<span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">$</span>children))]]</span>
<span id="cb24-16"><span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">stopifnot</span>(<span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">is.infinite</span>(<span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">log10</span>(<span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">0</span>)), <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">any</span>(<span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">grepl</span>(<span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"introduced infinite values"</span>, zero_warn)),</span>
<span id="cb24-17">          <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">is.infinite</span>(zero_built<span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">$</span>data[[<span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">1</span>]]<span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">$</span>y[<span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">2</span>]),                  <span class="co" style="color: #5E5E5E;
background-color: null;
font-style: inherit;"># the zero became -Inf</span></span>
<span id="cb24-18">          <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">isTRUE</span>(<span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">all.equal</span>(<span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">as.numeric</span>(zero_points<span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">$</span>y)[<span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">2</span>], <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">0</span>)))      <span class="co" style="color: #5E5E5E;
background-color: null;
font-style: inherit;"># drawn on the bottom edge</span></span>
<span id="cb24-19"><span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">c</span>(<span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">rank_log =</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">round</span>(rank_log, <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">2</span>), <span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">zero_count_in_data =</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">sum</span>(teal<span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">$</span>count <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">==</span> <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">0</span>))</span></code></pre></div></div>
<div class="cell-output cell-output-stdout">
<pre><code>          rank_log zero_count_in_data 
              0.94               0.00 </code></pre>
</div>
</div>
<p>The rank correlation on the log axis is 0.94. The catch is zero counts: <code>log10(0)</code> is <code>-Inf</code>, ggplot2 warns that the transformation introduced infinite values, and the point is then drawn on the bottom edge of the panel, where it looks like a small count rather than no birds at all. These simulated data happen to contain no zeros; real series from small sites often do. Either plot <code>count + 1</code> and say so in the axis label, or use the index, which handles a zero like any other value. How a log scale changes what a fitted mean means is a separate question, covered in <a href="https://tidyecology.com/posts/back-transforming-a-log-model/">Back-transforming a log-scale model</a>.</p>
</section>
<section id="when-a-free-scale-is-the-right-choice" class="level2">
<h2 id="when-a-free-scale-is-the-right-choice-h" class="anchored" data-anchor-id="when-a-free-scale-is-the-right-choice">When a free scale is the right choice</h2>
<p>Free scales answer a different question: what does each panel look like on its own? That is the right question when the panels show different variables or units, say January temperature, rainfall and water level at one site, where comparing heights across panels means nothing anyway. It is also the right question when the reader should look at the shape of each series (the timing of a peak, a change of direction) and not its size. In both cases say in the caption that the y axes differ, and keep the tick labels, so a reader who does compare panels can see why they should not.</p>
</section>
<section id="what-to-check-in-your-own-data" class="level2">
<h2 id="what-to-check-in-your-own-data-h" class="anchored" data-anchor-id="what-to-check-in-your-own-data">What to check in your own data</h2>
<p>Before choosing a setting, write down the comparison the figure is for. If it is “which site has more”, the default fixed scale is the honest one, even with small sites squashed; if it is “which site changed more”, plot an index or use a log axis with fixed scales.</p>
<p>When you see <code>scales = "free_y"</code> in your code or someone else’s, look at the y axis labels of two panels side by side. If one panel spans 500 birds and the other 25, a line of the same slope means a twentyfold difference in birds.</p>
<p>For a figure that will be read quickly, compute the fitted change per group as a number and check sizes, not only order. Take two groups, divide the drawn move of one by the drawn move of the other, and set that against the ratio of their fitted changes; under <code>"free_y"</code> the order can survive while the ratio does not, as it failed here. The <code>line_move()</code> function above can be adapted to any faceted plot with a fitted column. On an index axis, look at which group sets the shared height: if one very small site stretches it for everyone, show that site separately or leave it out and say so.</p>
<p>If you use a log axis, count the zeros first with <code>sum(x == 0)</code>. Any zero will sit on the bottom edge of its panel and look like a small count.</p>
</section>
<section id="references" class="level2">
<h2 id="references-h" class="anchored" data-anchor-id="references">References</h2>
<p>Cleveland WS, McGill R 1984 Journal of the American Statistical Association 79(387):531-554 (<a href="https://doi.org/10.1080/01621459.1984.10478080">10.1080/01621459.1984.10478080</a>)</p>
<p>Wickham H 2010 Journal of Computational and Graphical Statistics 19(1):3-28 (<a href="https://doi.org/10.1198/jcgs.2009.07098">10.1198/jcgs.2009.07098</a>)</p>
<p>Wickham H 2016 ggplot2: Elegant Graphics for Data Analysis, 2nd edition, Springer (ISBN 978-3-319-24275-0)</p>
</section>
<section id="related-tutorials" class="level2">
<h2 id="related-tutorials-h" class="anchored" data-anchor-id="related-tutorials">Related tutorials</h2>
<ul>
<li><a href="https://tidyecology.com/posts/your-first-ggplot/">Your first ggplot: data, aes and geom</a></li>
<li><a href="https://tidyecology.com/posts/checking-a-figure/">Checking a figure</a></li>
<li><a href="https://tidyecology.com/posts/factor-levels-in-r/">Factor levels in R: reference groups and empty sites</a></li>
<li><a href="https://tidyecology.com/posts/population-trend-estimation/">Estimating population trends in R</a></li>
</ul>
<details class="te-repro" data-pagefind-ignore="">
<summary>Reproducibility</summary>
<ul>
<li>Code last run: 2026-10-15</li>
<li>R version 4.5.3 (2026-03-11), aarch64-apple-darwin20</li>
<li>Packages: ggplot2 4.0.3</li>
</ul>
</details>


<!-- -->

</section>

 ]]></description>
  <category>R</category>
  <category>ggplot2</category>
  <category>data visualisation</category>
  <category>monitoring</category>
  <category>ecology tutorial</category>
  <guid isPermaLink="false">https://tidyecology.com/posts/fixed-or-free-scales-in-facets/</guid>
  <pubDate>Sun, 27 Sep 2026 09:00:00 GMT</pubDate>
  <media:content url="https://tidyecology.com/posts/fixed-or-free-scales-in-facets/thumbnail.png" medium="image" type="image/png" height="104" width="144"/>
</item>
<item>
  <title>Missing values in summaries: na.rm and false zeros</title>
  <dc:creator>Tidy Ecology</dc:creator>
  <link>https://tidyecology.com/posts/missing-values-in-summaries/</link>
  <description><![CDATA[ 





<p>A butterfly transect has been walked once a month from April to September since 2005. The volunteer count for each walk goes into a table with one row per year and one column per month, and a month nobody walked is left blank. The yearly total is <code>sum()</code> of the row, and for some years <code>sum()</code> returns <code>NA</code>. Adding <code>na.rm = TRUE</code> makes the <code>NA</code>s go away, the totals plot nicely, and the trend line through them falls year after year. Is the population declining?</p>
<p><a href="https://tidyecology.com/posts/reading-field-data-into-r/">Reading field data into R</a> shows how a blank cell arrives in R as <code>NA</code> and what writing zeros over it does to a diversity index. <a href="https://tidyecology.com/posts/qgis-null-and-r-na/">QGIS NULL and R NA: what survives the trip</a> compares <code>mean()</code> with and without <code>na.rm</code> against the QGIS aggregates, which skip NULL silently. <a href="https://tidyecology.com/posts/testing-your-analysis-code/">Testing your analysis code</a> puts <code>na.rm = TRUE</code> inside a richness function, <code>sum(x &gt; 0, na.rm = TRUE)</code>, watches it flatten a gradient, and writes the test that catches it. This post is about the summary functions themselves: what each one returns when values are missing, and what <code>na.rm = TRUE</code> does to a yearly total when the number of visits changes from year to year.</p>
<p><strong>The short answer.</strong> <code>na.rm = TRUE</code> removes the missing values before the summary is computed; it does not fill them in. For <code>mean()</code> that means averaging the months that were walked, which is usually what you want. For <code>sum()</code> it means every unwalked month contributes nothing, exactly as if it had been walked and no butterflies were seen, and a year in which nobody walked at all gets a total of zero. A yearly total built that way follows the number of walks. Summarise per walked month instead, or fit the model to the monthly counts, with a term for the month, and let the missing months drop out, and keep the number of walked months beside every yearly figure.</p>
<p>The data below are simulated; the seed is in the code.</p>
<div class="cell">
<div class="code-copy-outer-scaffold"><div class="sourceCode cell-code" id="cb1" style="background: #f1f3f5;"><pre class="sourceCode r code-with-copy"><code class="sourceCode r"><span id="cb1-1"><span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">library</span>(ggplot2)</span>
<span id="cb1-2"></span>
<span id="cb1-3">te_paper  <span class="ot" style="color: #003B4F;
background-color: null;
font-style: inherit;">&lt;-</span> <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"#f5f4ee"</span></span>
<span id="cb1-4">te_ink    <span class="ot" style="color: #003B4F;
background-color: null;
font-style: inherit;">&lt;-</span> <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"#16241d"</span></span>
<span id="cb1-5">te_body   <span class="ot" style="color: #003B4F;
background-color: null;
font-style: inherit;">&lt;-</span> <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"#2c3a31"</span></span>
<span id="cb1-6">te_forest <span class="ot" style="color: #003B4F;
background-color: null;
font-style: inherit;">&lt;-</span> <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"#275139"</span></span>
<span id="cb1-7">te_rust   <span class="ot" style="color: #003B4F;
background-color: null;
font-style: inherit;">&lt;-</span> <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"#b5534e"</span></span>
<span id="cb1-8">te_gold   <span class="ot" style="color: #003B4F;
background-color: null;
font-style: inherit;">&lt;-</span> <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"#c9b458"</span></span>
<span id="cb1-9">te_line   <span class="ot" style="color: #003B4F;
background-color: null;
font-style: inherit;">&lt;-</span> <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"#dad9ca"</span></span>
<span id="cb1-10"></span>
<span id="cb1-11">theme_datasheet <span class="ot" style="color: #003B4F;
background-color: null;
font-style: inherit;">&lt;-</span> <span class="cf" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">function</span>() {</span>
<span id="cb1-12">  <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">theme_minimal</span>(<span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">base_size =</span> <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">12</span>) <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">+</span></span>
<span id="cb1-13">    <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">theme</span>(<span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">plot.background  =</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">element_rect</span>(<span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">fill =</span> te_paper, <span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">colour =</span> <span class="cn" style="color: #8f5902;
background-color: null;
font-style: inherit;">NA</span>),</span>
<span id="cb1-14">          <span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">panel.background =</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">element_rect</span>(<span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">fill =</span> te_paper, <span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">colour =</span> <span class="cn" style="color: #8f5902;
background-color: null;
font-style: inherit;">NA</span>),</span>
<span id="cb1-15">          <span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">panel.grid.major =</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">element_line</span>(<span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">colour =</span> te_line, <span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">linewidth =</span> <span class="fl" style="color: #AD0000;
background-color: null;
font-style: inherit;">0.3</span>),</span>
<span id="cb1-16">          <span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">panel.grid.minor =</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">element_blank</span>(),</span>
<span id="cb1-17">          <span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">text             =</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">element_text</span>(<span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">colour =</span> te_body),</span>
<span id="cb1-18">          <span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">axis.text        =</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">element_text</span>(<span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">colour =</span> te_body),</span>
<span id="cb1-19">          <span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">legend.position  =</span> <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"top"</span>)</span>
<span id="cb1-20">}</span></code></pre></div></div>
</div>
<section id="what-each-summary-does-with-na" class="level2">
<h2 id="what-each-summary-does-with-na-h" class="anchored" data-anchor-id="what-each-summary-does-with-na">What each summary does with NA</h2>
<p>Take one year’s six monthly counts with one month not walked, and a year with no walks at all:</p>
<div class="cell">
<div class="code-copy-outer-scaffold"><div class="sourceCode cell-code" id="cb2" style="background: #f1f3f5;"><pre class="sourceCode r code-with-copy"><code class="sourceCode r"><span id="cb2-1">one_gap    <span class="ot" style="color: #003B4F;
background-color: null;
font-style: inherit;">&lt;-</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">c</span>(<span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">8</span>, <span class="cn" style="color: #8f5902;
background-color: null;
font-style: inherit;">NA</span>, <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">30</span>, <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">35</span>, <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">22</span>, <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">11</span>)   <span class="co" style="color: #5E5E5E;
background-color: null;
font-style: inherit;"># May not walked</span></span>
<span id="cb2-2">no_walks   <span class="ot" style="color: #003B4F;
background-color: null;
font-style: inherit;">&lt;-</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">rep</span>(<span class="cn" style="color: #8f5902;
background-color: null;
font-style: inherit;">NA_real_</span>, <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">6</span>)           <span class="co" style="color: #5E5E5E;
background-color: null;
font-style: inherit;"># nobody walked all season</span></span>
<span id="cb2-3"></span>
<span id="cb2-4"><span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">sum</span>(one_gap)</span></code></pre></div></div>
<div class="cell-output cell-output-stdout">
<pre><code>[1] NA</code></pre>
</div>
<div class="code-copy-outer-scaffold"><div class="sourceCode cell-code" id="cb4" style="background: #f1f3f5;"><pre class="sourceCode r code-with-copy"><code class="sourceCode r"><span id="cb4-1"><span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">sum</span>(one_gap, <span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">na.rm =</span> <span class="cn" style="color: #8f5902;
background-color: null;
font-style: inherit;">TRUE</span>)</span></code></pre></div></div>
<div class="cell-output cell-output-stdout">
<pre><code>[1] 106</code></pre>
</div>
<div class="code-copy-outer-scaffold"><div class="sourceCode cell-code" id="cb6" style="background: #f1f3f5;"><pre class="sourceCode r code-with-copy"><code class="sourceCode r"><span id="cb6-1"><span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">mean</span>(one_gap, <span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">na.rm =</span> <span class="cn" style="color: #8f5902;
background-color: null;
font-style: inherit;">TRUE</span>)</span></code></pre></div></div>
<div class="cell-output cell-output-stdout">
<pre><code>[1] 21.2</code></pre>
</div>
<div class="code-copy-outer-scaffold"><div class="sourceCode cell-code" id="cb8" style="background: #f1f3f5;"><pre class="sourceCode r code-with-copy"><code class="sourceCode r"><span id="cb8-1"><span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">c</span>(<span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">length =</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">length</span>(one_gap), <span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">walked =</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">sum</span>(<span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">!</span><span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">is.na</span>(one_gap)))</span></code></pre></div></div>
<div class="cell-output cell-output-stdout">
<pre><code>length walked 
     6      5 </code></pre>
</div>
<div class="code-copy-outer-scaffold"><div class="sourceCode cell-code" id="cb10" style="background: #f1f3f5;"><pre class="sourceCode r code-with-copy"><code class="sourceCode r"><span id="cb10-1">species_seen <span class="ot" style="color: #003B4F;
background-color: null;
font-style: inherit;">&lt;-</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">c</span>(<span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"Maniola jurtina"</span>, <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"Pieris rapae"</span>, <span class="cn" style="color: #8f5902;
background-color: null;
font-style: inherit;">NA</span>, <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"Maniola jurtina"</span>)   <span class="co" style="color: #5E5E5E;
background-color: null;
font-style: inherit;"># one name not recorded (NA)</span></span>
<span id="cb10-2"><span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">c</span>(<span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">distinct =</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">length</span>(<span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">unique</span>(species_seen)), <span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">species =</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">length</span>(<span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">unique</span>(<span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">na.omit</span>(species_seen))))</span></code></pre></div></div>
<div class="cell-output cell-output-stdout">
<pre><code>distinct  species 
       3        2 </code></pre>
</div>
<div class="code-copy-outer-scaffold"><div class="sourceCode cell-code" id="cb12" style="background: #f1f3f5;"><pre class="sourceCode r code-with-copy"><code class="sourceCode r"><span id="cb12-1"><span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">sum</span>(no_walks, <span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">na.rm =</span> <span class="cn" style="color: #8f5902;
background-color: null;
font-style: inherit;">TRUE</span>)</span></code></pre></div></div>
<div class="cell-output cell-output-stdout">
<pre><code>[1] 0</code></pre>
</div>
<div class="code-copy-outer-scaffold"><div class="sourceCode cell-code" id="cb14" style="background: #f1f3f5;"><pre class="sourceCode r code-with-copy"><code class="sourceCode r"><span id="cb14-1"><span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">mean</span>(no_walks, <span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">na.rm =</span> <span class="cn" style="color: #8f5902;
background-color: null;
font-style: inherit;">TRUE</span>)</span></code></pre></div></div>
<div class="cell-output cell-output-stdout">
<pre><code>[1] NaN</code></pre>
</div>
<div class="code-copy-outer-scaffold"><div class="sourceCode cell-code" id="cb16" style="background: #f1f3f5;"><pre class="sourceCode r code-with-copy"><code class="sourceCode r"><span id="cb16-1"><span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">suppressWarnings</span>(<span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">max</span>(no_walks, <span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">na.rm =</span> <span class="cn" style="color: #8f5902;
background-color: null;
font-style: inherit;">TRUE</span>))</span></code></pre></div></div>
<div class="cell-output cell-output-stdout">
<pre><code>[1] -Inf</code></pre>
</div>
<div class="code-copy-outer-scaffold"><div class="sourceCode cell-code" id="cb18" style="background: #f1f3f5;"><pre class="sourceCode r code-with-copy"><code class="sourceCode r"><span id="cb18-1">max_warned <span class="ot" style="color: #003B4F;
background-color: null;
font-style: inherit;">&lt;-</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">tryCatch</span>({ <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">max</span>(no_walks, <span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">na.rm =</span> <span class="cn" style="color: #8f5902;
background-color: null;
font-style: inherit;">TRUE</span>); <span class="cn" style="color: #8f5902;
background-color: null;
font-style: inherit;">FALSE</span> },</span>
<span id="cb18-2">                       <span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">warning =</span> <span class="cf" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">function</span>(w) <span class="cn" style="color: #8f5902;
background-color: null;
font-style: inherit;">TRUE</span>)</span>
<span id="cb18-3"><span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">stopifnot</span>(<span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">is.na</span>(<span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">sum</span>(one_gap)),                                  <span class="co" style="color: #5E5E5E;
background-color: null;
font-style: inherit;"># one NA spoils the sum</span></span>
<span id="cb18-4">          <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">sum</span>(one_gap, <span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">na.rm =</span> <span class="cn" style="color: #8f5902;
background-color: null;
font-style: inherit;">TRUE</span>) <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">==</span> <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">106</span>,                    <span class="co" style="color: #5E5E5E;
background-color: null;
font-style: inherit;"># the NA is dropped</span></span>
<span id="cb18-5">          <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">mean</span>(one_gap, <span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">na.rm =</span> <span class="cn" style="color: #8f5902;
background-color: null;
font-style: inherit;">TRUE</span>) <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">==</span> <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">106</span> <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">/</span> <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">5</span>,               <span class="co" style="color: #5E5E5E;
background-color: null;
font-style: inherit;"># divided by 5, not 6</span></span>
<span id="cb18-6">          <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">length</span>(one_gap) <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">==</span> <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">6</span>, <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">sum</span>(<span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">!</span><span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">is.na</span>(one_gap)) <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">==</span> <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">5</span>,      <span class="co" style="color: #5E5E5E;
background-color: null;
font-style: inherit;"># length() counts the NA</span></span>
<span id="cb18-7">          <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">length</span>(<span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">unique</span>(species_seen)) <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">==</span> <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">3</span>,                    <span class="co" style="color: #5E5E5E;
background-color: null;
font-style: inherit;"># unique() keeps NA as a value</span></span>
<span id="cb18-8">          <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">length</span>(<span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">unique</span>(<span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">na.omit</span>(species_seen))) <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">==</span> <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">2</span>,           <span class="co" style="color: #5E5E5E;
background-color: null;
font-style: inherit;"># ... unless it is removed</span></span>
<span id="cb18-9">          <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">identical</span>(<span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">read.csv</span>(<span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">text =</span> <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"walk,species</span><span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">\n</span><span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">1,</span><span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">\n</span><span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">2,Pieris rapae"</span>)<span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">$</span>species[<span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">1</span>], <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">""</span>),  <span class="co" style="color: #5E5E5E;
background-color: null;
font-style: inherit;"># a blank text cell is "", not NA</span></span>
<span id="cb18-10">          <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">sum</span>(no_walks, <span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">na.rm =</span> <span class="cn" style="color: #8f5902;
background-color: null;
font-style: inherit;">TRUE</span>) <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">==</span> <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">0</span>,                     <span class="co" style="color: #5E5E5E;
background-color: null;
font-style: inherit;"># nothing left: zero</span></span>
<span id="cb18-11">          <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">is.nan</span>(<span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">mean</span>(no_walks, <span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">na.rm =</span> <span class="cn" style="color: #8f5902;
background-color: null;
font-style: inherit;">TRUE</span>)),                 <span class="co" style="color: #5E5E5E;
background-color: null;
font-style: inherit;"># nothing left: NaN</span></span>
<span id="cb18-12">          <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">suppressWarnings</span>(<span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">max</span>(no_walks, <span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">na.rm =</span> <span class="cn" style="color: #8f5902;
background-color: null;
font-style: inherit;">TRUE</span>)) <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">==</span> <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">-</span><span class="cn" style="color: #8f5902;
background-color: null;
font-style: inherit;">Inf</span>, <span class="co" style="color: #5E5E5E;
background-color: null;
font-style: inherit;"># nothing left: -Inf</span></span>
<span id="cb18-13">          max_warned,                                           <span class="co" style="color: #5E5E5E;
background-color: null;
font-style: inherit;"># ... with a warning</span></span>
<span id="cb18-14">          <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">rowSums</span>(<span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">rbind</span>(one_gap, no_walks), <span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">na.rm =</span> <span class="cn" style="color: #8f5902;
background-color: null;
font-style: inherit;">TRUE</span>) <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">==</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">c</span>(<span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">106</span>, <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">0</span>),  <span class="co" style="color: #5E5E5E;
background-color: null;
font-style: inherit;"># rowSums() alike</span></span>
<span id="cb18-15">          <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">colSums</span>(<span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">cbind</span>(one_gap, no_walks), <span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">na.rm =</span> <span class="cn" style="color: #8f5902;
background-color: null;
font-style: inherit;">TRUE</span>) <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">==</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">c</span>(<span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">106</span>, <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">0</span>))  <span class="co" style="color: #5E5E5E;
background-color: null;
font-style: inherit;"># colSums() alike</span></span></code></pre></div></div>
</div>
<p>Without <code>na.rm</code>, one missing value makes the whole summary <code>NA</code>. That is R saying the answer is not known, and it is the honest default. With <code>na.rm = TRUE</code> the missing values are dropped and the summary is computed from what is left, and the functions then differ in what “what is left” means. <code>mean()</code> divides by the number of values it kept, five here, so the mean per walked month is still a mean. <code>sum()</code> has nothing to divide by: the five walked months are added up and May counts as nothing. Note that <code>length()</code> still counts the <code>NA</code>; the number of walked months is <code>sum(!is.na(x))</code>. Counting distinct values treats <code>NA</code> the same way, as a value and not as a gap: <code>length(unique(x))</code> counts it as one more value, so a walk with one species name missing gains a species, as the <code>distinct</code> and <code>species</code> counts above show. dplyr’s <code>n_distinct()</code> does the same unless it is given <code>na.rm = TRUE</code> (its default is <code>na.rm = FALSE</code> in dplyr 1.1.4); <code>length(unique(na.omit(x)))</code> is the base R count without the gap. Both only drop an <code>NA</code>: a blank text cell read with <code>read.csv()</code> arrives as an empty string, <code>""</code>, which every one of these counts as a species unless <code>na.strings</code> includes <code>""</code>, as <a href="https://tidyecology.com/posts/reading-field-data-into-r/">Reading field data into R</a> shows.</p>
<p>The empty year shows the three functions disagreeing outright. With every value removed, <code>sum()</code> returns 0, <code>mean()</code> returns <code>NaN</code> (zero divided by zero, “not a number”) and <code>max()</code> returns <code>-Inf</code> with a warning. The <code>stopifnot()</code> line checks each of these, so the page would not build if a future version of R changed them. Of the three, only the sum looks like a real value. <code>NaN</code> and <code>-Inf</code> stand out in a table and are hard to mistake for a count; a 0 sits on the plot as a year in which no butterflies were seen. <code>rowSums()</code> and <code>colSums()</code> with <code>na.rm = TRUE</code> follow the same rule as <code>sum()</code>, one row or column at a time (the last two lines of the check), and so does every <code>sum()</code> inside a grouped summary of the kind built in <a href="https://tidyecology.com/posts/grouped-summaries-in-r/">Summarising ecological data by group</a>.</p>
</section>
<section id="twenty-years-of-a-stable-transect" class="level2">
<h2 id="twenty-years-of-a-stable-transect-h" class="anchored" data-anchor-id="twenty-years-of-a-stable-transect">Twenty years of a stable transect</h2>
<p>The simulated transect has a population that does not change. Each month has its own expected count, low in April and September and highest in July, and the six expected counts add up to 120 butterflies a season, every season, from 2005 to 2024. The observed counts are Poisson draws around those values. What changes is the walking: the chance that a month is missed rises in a straight line from 5 per cent in 2005 to 40 per cent in 2024, the same for every month, as volunteers drop out. These design constants were fixed before any trend was fitted.</p>
<div class="cell">
<div class="code-copy-outer-scaffold"><div class="sourceCode cell-code" id="cb19" style="background: #f1f3f5;"><pre class="sourceCode r code-with-copy"><code class="sourceCode r"><span id="cb19-1">years      <span class="ot" style="color: #003B4F;
background-color: null;
font-style: inherit;">&lt;-</span> <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">2005</span><span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">:</span><span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">2024</span></span>
<span id="cb19-2">months     <span class="ot" style="color: #003B4F;
background-color: null;
font-style: inherit;">&lt;-</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">c</span>(<span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"Apr"</span>, <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"May"</span>, <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"Jun"</span>, <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"Jul"</span>, <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"Aug"</span>, <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"Sep"</span>)</span>
<span id="cb19-3">month_mean <span class="ot" style="color: #003B4F;
background-color: null;
font-style: inherit;">&lt;-</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">c</span>(<span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">8</span>, <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">16</span>, <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">28</span>, <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">32</span>, <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">24</span>, <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">12</span>)            <span class="co" style="color: #5E5E5E;
background-color: null;
font-style: inherit;"># expected count per walk, 120 a season</span></span>
<span id="cb19-4">p_missed   <span class="ot" style="color: #003B4F;
background-color: null;
font-style: inherit;">&lt;-</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">seq</span>(<span class="fl" style="color: #AD0000;
background-color: null;
font-style: inherit;">0.05</span>, <span class="fl" style="color: #AD0000;
background-color: null;
font-style: inherit;">0.40</span>, <span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">length.out =</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">length</span>(years))</span>
<span id="cb19-5"></span>
<span id="cb19-6">simulate_transect <span class="ot" style="color: #003B4F;
background-color: null;
font-style: inherit;">&lt;-</span> <span class="cf" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">function</span>(<span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">p_month =</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">matrix</span>(p_missed, <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">length</span>(years), <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">6</span>)) {</span>
<span id="cb19-7">  counts <span class="ot" style="color: #003B4F;
background-color: null;
font-style: inherit;">&lt;-</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">matrix</span>(<span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">rpois</span>(<span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">length</span>(years) <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">*</span> <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">6</span>, <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">rep</span>(month_mean, <span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">each =</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">length</span>(years))),</span>
<span id="cb19-8">                   <span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">nrow =</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">length</span>(years), <span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">dimnames =</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">list</span>(years, months))</span>
<span id="cb19-9">  missed <span class="ot" style="color: #003B4F;
background-color: null;
font-style: inherit;">&lt;-</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">matrix</span>(<span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">runif</span>(<span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">length</span>(years) <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">*</span> <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">6</span>), <span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">nrow =</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">length</span>(years)) <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">&lt;</span> p_month</span>
<span id="cb19-10">  counts[missed] <span class="ot" style="color: #003B4F;
background-color: null;
font-style: inherit;">&lt;-</span> <span class="cn" style="color: #8f5902;
background-color: null;
font-style: inherit;">NA</span></span>
<span id="cb19-11">  counts</span>
<span id="cb19-12">}</span>
<span id="cb19-13"></span>
<span id="cb19-14"><span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">set.seed</span>(<span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">1612</span>)</span>
<span id="cb19-15">counts <span class="ot" style="color: #003B4F;
background-color: null;
font-style: inherit;">&lt;-</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">simulate_transect</span>()</span>
<span id="cb19-16">counts[<span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">c</span>(<span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"2005"</span>, <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"2015"</span>, <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"2024"</span>), ]</span></code></pre></div></div>
<div class="cell-output cell-output-stdout">
<pre><code>     Apr May Jun Jul Aug Sep
2005  11  NA  38  35  16  10
2015  NA  16  NA  32  23   9
2024   6  12  NA  33  NA  NA</code></pre>
</div>
</div>
<p>Each row is a season. The yearly table the analyst builds has the <code>na.rm</code> total, and, because it costs one line, the number of months walked:</p>
<div class="cell">
<div class="code-copy-outer-scaffold"><div class="sourceCode cell-code" id="cb21" style="background: #f1f3f5;"><pre class="sourceCode r code-with-copy"><code class="sourceCode r"><span id="cb21-1">yearly <span class="ot" style="color: #003B4F;
background-color: null;
font-style: inherit;">&lt;-</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">data.frame</span>(<span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">year     =</span> years,</span>
<span id="cb21-2">                     <span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">total    =</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">rowSums</span>(counts, <span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">na.rm =</span> <span class="cn" style="color: #8f5902;
background-color: null;
font-style: inherit;">TRUE</span>),</span>
<span id="cb21-3">                     <span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">walked   =</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">rowSums</span>(<span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">!</span><span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">is.na</span>(counts)))</span>
<span id="cb21-4">yearly<span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">$</span>per_walk <span class="ot" style="color: #003B4F;
background-color: null;
font-style: inherit;">&lt;-</span> yearly<span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">$</span>total <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">/</span> yearly<span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">$</span>walked      <span class="co" style="color: #5E5E5E;
background-color: null;
font-style: inherit;"># NaN in a year with no walks</span></span>
<span id="cb21-5"><span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">stopifnot</span>(<span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">all.equal</span>(yearly<span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">$</span>per_walk, <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">unname</span>(<span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">rowMeans</span>(counts, <span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">na.rm =</span> <span class="cn" style="color: #8f5902;
background-color: null;
font-style: inherit;">TRUE</span>))))</span>
<span id="cb21-6"></span>
<span id="cb21-7">per_decade <span class="ot" style="color: #003B4F;
background-color: null;
font-style: inherit;">&lt;-</span> <span class="cf" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">function</span>(slope) <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">100</span> <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">*</span> (<span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">exp</span>(<span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">10</span> <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">*</span> slope) <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">-</span> <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">1</span>)   <span class="co" style="color: #5E5E5E;
background-color: null;
font-style: inherit;"># log-scale slope as per cent per decade</span></span>
<span id="cb21-8">fit_naive  <span class="ot" style="color: #003B4F;
background-color: null;
font-style: inherit;">&lt;-</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">glm</span>(total <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">~</span> year, <span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">family =</span> poisson, <span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">data =</span> yearly)</span>
<span id="cb21-9">naive_decade <span class="ot" style="color: #003B4F;
background-color: null;
font-style: inherit;">&lt;-</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">per_decade</span>(<span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">coef</span>(fit_naive)[[<span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"year"</span>]])</span>
<span id="cb21-10"><span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">c</span>(<span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">naive_per_decade =</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">round</span>(naive_decade, <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">1</span>),</span>
<span id="cb21-11">  <span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">walks_first_5_years =</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">sum</span>(yearly<span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">$</span>walked[<span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">1</span><span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">:</span><span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">5</span>]),</span>
<span id="cb21-12">  <span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">walks_last_5_years  =</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">sum</span>(yearly<span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">$</span>walked[<span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">16</span><span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">:</span><span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">20</span>]))</span></code></pre></div></div>
<div class="cell-output cell-output-stdout">
<pre><code>   naive_per_decade walks_first_5_years  walks_last_5_years 
              -20.4                27.0                18.0 </code></pre>
</div>
</div>
<p>A Poisson GLM of the yearly totals on year, the log-linear trend also fitted in <a href="https://tidyecology.com/posts/population-trend-estimation/">Estimating population trends in R</a>, reports a change of -20.4 per cent per decade. The population was built not to change. The first five seasons had 27 walks between them and the last five had 18.</p>
</section>
<section id="where-the-decline-comes-from" class="level2">
<h2 id="where-the-decline-comes-from-h" class="anchored" data-anchor-id="where-the-decline-comes-from">Where the decline comes from</h2>
<p>The decline can be worked out without a simulation. A month that is walked contributes its expected count to the total, and a month that is missed contributes 0. If each month is missed with probability p, the expected <code>na.rm</code> total is</p>
<pre><code>expected total = (8 + 16 + 28 + 32 + 24 + 12) x (1 - p) = 120 x (1 - p)</code></pre>
<p>so it falls from 120 x 0.95 = 114 in 2005 to 120 x 0.60 = 72 in 2024 while the population stays at 120. The trend in the totals is the trend in <code>1 - p</code>, the share of months walked. Fitting the same log-linear model to these expected totals gives the trend the naive analysis is aiming at (the chunk uses the quasipoisson family, because the expected totals are not whole numbers; the slope is the same as with poisson). The chunk then repeats the simulated transect 2000 times to check it:</p>
<div class="cell">
<div class="code-copy-outer-scaffold"><div class="sourceCode cell-code" id="cb24" style="background: #f1f3f5;"><pre class="sourceCode r code-with-copy"><code class="sourceCode r"><span id="cb24-1">expected_total <span class="ot" style="color: #003B4F;
background-color: null;
font-style: inherit;">&lt;-</span> <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">120</span> <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">*</span> (<span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">1</span> <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">-</span> p_missed)</span>
<span id="cb24-2">closed_slope   <span class="ot" style="color: #003B4F;
background-color: null;
font-style: inherit;">&lt;-</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">coef</span>(<span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">glm</span>(expected_total <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">~</span> years, <span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">family =</span> quasipoisson))[[<span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"years"</span>]]</span>
<span id="cb24-3"><span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">stopifnot</span>(<span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">isTRUE</span>(<span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">all.equal</span>(closed_slope,                <span class="co" style="color: #5E5E5E;
background-color: null;
font-style: inherit;"># same slope as poisson</span></span>
<span id="cb24-4">  <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">suppressWarnings</span>(<span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">coef</span>(<span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">glm</span>(expected_total <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">~</span> years, <span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">family =</span> poisson)))[[<span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"years"</span>]])))</span>
<span id="cb24-5"></span>
<span id="cb24-6">trend_pair <span class="ot" style="color: #003B4F;
background-color: null;
font-style: inherit;">&lt;-</span> <span class="cf" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">function</span>(counts) {</span>
<span id="cb24-7">  total  <span class="ot" style="color: #003B4F;
background-color: null;
font-style: inherit;">&lt;-</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">rowSums</span>(counts, <span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">na.rm =</span> <span class="cn" style="color: #8f5902;
background-color: null;
font-style: inherit;">TRUE</span>)</span>
<span id="cb24-8">  walked <span class="ot" style="color: #003B4F;
background-color: null;
font-style: inherit;">&lt;-</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">rowSums</span>(<span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">!</span><span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">is.na</span>(counts))</span>
<span id="cb24-9">  keep   <span class="ot" style="color: #003B4F;
background-color: null;
font-style: inherit;">&lt;-</span> walked <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">&gt;</span> <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">0</span>                                 <span class="co" style="color: #5E5E5E;
background-color: null;
font-style: inherit;"># a year with no walks is unknown</span></span>
<span id="cb24-10">  month  <span class="ot" style="color: #003B4F;
background-color: null;
font-style: inherit;">&lt;-</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">factor</span>(<span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">rep</span>(months, <span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">each =</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">length</span>(years)), <span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">levels =</span> months)</span>
<span id="cb24-11">  <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">c</span>(<span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">naive  =</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">coef</span>(<span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">glm</span>(total <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">~</span> years, <span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">family =</span> poisson))[[<span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"years"</span>]],</span>
<span id="cb24-12">    <span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">offset =</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">coef</span>(<span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">glm</span>(total[keep] <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">~</span> years[keep] <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">+</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">offset</span>(<span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">log</span>(walked[keep])),</span>
<span id="cb24-13">                      <span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">family =</span> poisson))[[<span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">2</span>]],</span>
<span id="cb24-14">    <span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">month  =</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">coef</span>(<span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">glm</span>(<span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">as.vector</span>(counts) <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">~</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">rep</span>(years, <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">6</span>) <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">+</span> month,</span>
<span id="cb24-15">                      <span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">family =</span> poisson))[[<span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">2</span>]],</span>
<span id="cb24-16">    <span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">zero_years =</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">sum</span>(walked <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">==</span> <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">0</span>))</span>
<span id="cb24-17">}</span>
<span id="cb24-18"></span>
<span id="cb24-19"><span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">set.seed</span>(<span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">2016</span>)</span>
<span id="cb24-20">n_rep <span class="ot" style="color: #003B4F;
background-color: null;
font-style: inherit;">&lt;-</span> <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">2000</span></span>
<span id="cb24-21">reps  <span class="ot" style="color: #003B4F;
background-color: null;
font-style: inherit;">&lt;-</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">t</span>(<span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">replicate</span>(n_rep, <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">trend_pair</span>(<span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">simulate_transect</span>())))</span>
<span id="cb24-22"></span>
<span id="cb24-23">naive_mean  <span class="ot" style="color: #003B4F;
background-color: null;
font-style: inherit;">&lt;-</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">mean</span>(reps[, <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"naive"</span>])</span>
<span id="cb24-24">naive_mcse  <span class="ot" style="color: #003B4F;
background-color: null;
font-style: inherit;">&lt;-</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">sd</span>(reps[, <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"naive"</span>]) <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">/</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">sqrt</span>(n_rep)</span>
<span id="cb24-25">naive_neg   <span class="ot" style="color: #003B4F;
background-color: null;
font-style: inherit;">&lt;-</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">mean</span>(reps[, <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"naive"</span>] <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">&lt;</span> <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">0</span>)</span>
<span id="cb24-26">naive_neg_se <span class="ot" style="color: #003B4F;
background-color: null;
font-style: inherit;">&lt;-</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">sqrt</span>(naive_neg <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">*</span> (<span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">1</span> <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">-</span> naive_neg) <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">/</span> n_rep)</span>
<span id="cb24-27">zero_share  <span class="ot" style="color: #003B4F;
background-color: null;
font-style: inherit;">&lt;-</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">mean</span>(reps[, <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"zero_years"</span>] <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">&gt;</span> <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">0</span>)</span>
<span id="cb24-28">zero_expect <span class="ot" style="color: #003B4F;
background-color: null;
font-style: inherit;">&lt;-</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">sum</span>(p_missed<span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">^</span><span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">6</span>)                         <span class="co" style="color: #5E5E5E;
background-color: null;
font-style: inherit;"># expected all-missed years per series</span></span>
<span id="cb24-29">zero_prob   <span class="ot" style="color: #003B4F;
background-color: null;
font-style: inherit;">&lt;-</span> <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">1</span> <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">-</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">prod</span>(<span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">1</span> <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">-</span> p_missed<span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">^</span><span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">6</span>)                <span class="co" style="color: #5E5E5E;
background-color: null;
font-style: inherit;"># chance of at least one such year</span></span>
<span id="cb24-30"><span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">round</span>(<span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">c</span>(<span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">closed_per_decade =</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">per_decade</span>(closed_slope),</span>
<span id="cb24-31">        <span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">sim_per_decade =</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">per_decade</span>(naive_mean),</span>
<span id="cb24-32">        <span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">slope_gap_in_mcse =</span> (naive_mean <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">-</span> closed_slope) <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">/</span> naive_mcse,</span>
<span id="cb24-33">        <span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">share_negative =</span> naive_neg, <span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">mcse =</span> naive_neg_se,</span>
<span id="cb24-34">        <span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">series_with_a_zero_year =</span> zero_share, <span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">expected_zero_years =</span> zero_expect,</span>
<span id="cb24-35">        <span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">chance_of_a_zero_year =</span> zero_prob), <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">4</span>)</span></code></pre></div></div>
<div class="cell-output cell-output-stdout">
<pre><code>      closed_per_decade          sim_per_decade       slope_gap_in_mcse 
               -21.2265                -21.4050                 -0.9812 
         share_negative                    mcse series_with_a_zero_year 
                 0.9905                  0.0022                  0.0120 
    expected_zero_years   chance_of_a_zero_year 
                 0.0148                  0.0148 </code></pre>
</div>
</div>
<p>The expected totals give -21.2 per cent per decade. Across the 2000 simulated transects the average naive slope converts to -21.4 per cent per decade, 1.0 Monte Carlo standard errors from the worked-out value, and 99.1 per cent of the transects show a decline (Monte Carlo standard error 0.2 percentage points). The simulation adds nothing the arithmetic did not already say: a total with <code>na.rm = TRUE</code> measures butterflies counted, and here the butterflies counted per season went down because the walks went down.</p>
<p>A year with all six months missed is where the rule from the first section shows up on a plot. Its expected number per transect is the sum of p to the sixth power over the twenty years, 0.0148. The chance of at least one such year is 1 minus the product of (1 - p^6), 0.0148 (almost the same number, because the terms are tiny), and in the simulation 1.2 per cent of the 2000 transects had at least one such year (Monte Carlo standard error 0.2 percentage points). Each of those years went into the trend as a total of 0 butterflies: the lowest point on the graph, and the least informative one. The chance of an empty year is p to the power of the number of planned visits, so false zeros are rare with six visits and common with few: at the 2024 missed share of 40 per cent a year with three planned visits would be empty with probability 0.064, against 0.0041 with six.</p>
</section>
<section id="two-fixes-measured-with-the-same-trend" class="level2">
<h2 id="two-fixes-measured-with-the-same-trend-h" class="anchored" data-anchor-id="two-fixes-measured-with-the-same-trend">Two fixes, measured with the same trend</h2>
<p>The first fix is a different summary: the mean count per walked month, <code>rowMeans(counts, na.rm = TRUE)</code>, which is the <code>per_walk</code> column above. Multiplied by 6 it is an estimate of the season total that does not shrink when walks are missed, and a year without walks comes out as <code>NaN</code>, so <code>glm()</code> drops it instead of fitting a zero.</p>
<p>The second fix is the model. Put the monthly counts in a long table, one row per month and year, and fit the Poisson GLM to them. <code>glm()</code> drops rows with a missing response by default (the <code>na.action</code> option is <code>na.omit</code>), so the unwalked months are simply absent, and a year with no walks has no rows. No offset is needed at the month level, because every row is one walk. If you keep the yearly table instead, the same model is the yearly total with <code>offset(log(walked))</code>, which turns the total into a rate per walk; <a href="https://tidyecology.com/posts/offsets-for-rates-and-densities/">Offsets for rates and densities in Poisson GLMs</a> explains offsets. The two give the same slope to the last digit, which the chunk checks:</p>
<div class="cell">
<div class="code-copy-outer-scaffold"><div class="sourceCode cell-code" id="cb26" style="background: #f1f3f5;"><pre class="sourceCode r code-with-copy"><code class="sourceCode r"><span id="cb26-1">long <span class="ot" style="color: #003B4F;
background-color: null;
font-style: inherit;">&lt;-</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">data.frame</span>(<span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">year  =</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">rep</span>(years, <span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">times =</span> <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">6</span>),</span>
<span id="cb26-2">                   <span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">month =</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">factor</span>(<span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">rep</span>(months, <span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">each =</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">length</span>(years)), <span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">levels =</span> months),</span>
<span id="cb26-3">                   <span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">count =</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">as.vector</span>(counts))</span>
<span id="cb26-4">fit_month  <span class="ot" style="color: #003B4F;
background-color: null;
font-style: inherit;">&lt;-</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">glm</span>(count <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">~</span> year, <span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">family =</span> poisson, <span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">data =</span> long)</span>
<span id="cb26-5">fit_offset <span class="ot" style="color: #003B4F;
background-color: null;
font-style: inherit;">&lt;-</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">glm</span>(total <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">~</span> year <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">+</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">offset</span>(<span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">log</span>(walked)), <span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">family =</span> poisson,</span>
<span id="cb26-6">                  <span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">data =</span> yearly[yearly<span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">$</span>walked <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">&gt;</span> <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">0</span>, ])</span>
<span id="cb26-7"></span>
<span id="cb26-8"><span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">stopifnot</span>(<span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">identical</span>(<span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">getOption</span>(<span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"na.action"</span>), <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"na.omit"</span>),</span>
<span id="cb26-9">          <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">is.nan</span>(<span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">rowMeans</span>(<span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">rbind</span>(no_walks), <span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">na.rm =</span> <span class="cn" style="color: #8f5902;
background-color: null;
font-style: inherit;">TRUE</span>)),               <span class="co" style="color: #5E5E5E;
background-color: null;
font-style: inherit;"># empty year: NaN</span></span>
<span id="cb26-10">          <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">length</span>(<span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">fitted</span>(<span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">glm</span>(<span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">c</span>(<span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">1</span>, <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">2</span>, <span class="cn" style="color: #8f5902;
background-color: null;
font-style: inherit;">NaN</span>, <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">4</span>) <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">~</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">seq_len</span>(<span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">4</span>), <span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">family =</span> poisson))) <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">==</span> <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">3</span>,</span>
<span id="cb26-11">          <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">length</span>(<span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">fitted</span>(fit_month)) <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">==</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">sum</span>(<span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">!</span><span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">is.na</span>(long<span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">$</span>count)),   <span class="co" style="color: #5E5E5E;
background-color: null;
font-style: inherit;"># missing rows dropped</span></span>
<span id="cb26-12">          <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">isTRUE</span>(<span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">all.equal</span>(<span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">coef</span>(fit_month)[[<span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"year"</span>]], <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">coef</span>(fit_offset)[[<span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"year"</span>]],</span>
<span id="cb26-13">                           <span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">tolerance =</span> <span class="fl" style="color: #AD0000;
background-color: null;
font-style: inherit;">1e-6</span>)))</span>
<span id="cb26-14">month_decade <span class="ot" style="color: #003B4F;
background-color: null;
font-style: inherit;">&lt;-</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">per_decade</span>(<span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">coef</span>(fit_month)[[<span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"year"</span>]])</span>
<span id="cb26-15"></span>
<span id="cb26-16">offset_mean   <span class="ot" style="color: #003B4F;
background-color: null;
font-style: inherit;">&lt;-</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">mean</span>(reps[, <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"offset"</span>])</span>
<span id="cb26-17">offset_mcse   <span class="ot" style="color: #003B4F;
background-color: null;
font-style: inherit;">&lt;-</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">sd</span>(reps[, <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"offset"</span>]) <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">/</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">sqrt</span>(n_rep)</span>
<span id="cb26-18">offset_neg    <span class="ot" style="color: #003B4F;
background-color: null;
font-style: inherit;">&lt;-</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">mean</span>(reps[, <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"offset"</span>] <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">&lt;</span> <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">0</span>)</span>
<span id="cb26-19">offset_neg_se <span class="ot" style="color: #003B4F;
background-color: null;
font-style: inherit;">&lt;-</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">sqrt</span>(offset_neg <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">*</span> (<span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">1</span> <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">-</span> offset_neg) <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">/</span> n_rep)</span>
<span id="cb26-20">month_mean_slope <span class="ot" style="color: #003B4F;
background-color: null;
font-style: inherit;">&lt;-</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">mean</span>(reps[, <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"month"</span>])</span>
<span id="cb26-21">month_mcse    <span class="ot" style="color: #003B4F;
background-color: null;
font-style: inherit;">&lt;-</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">sd</span>(reps[, <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"month"</span>]) <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">/</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">sqrt</span>(n_rep)</span>
<span id="cb26-22">slope_sd      <span class="ot" style="color: #003B4F;
background-color: null;
font-style: inherit;">&lt;-</span> <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">10</span> <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">*</span> <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">100</span> <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">*</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">apply</span>(reps[, <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">c</span>(<span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"offset"</span>, <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"month"</span>)], <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">2</span>, sd)   <span class="co" style="color: #5E5E5E;
background-color: null;
font-style: inherit;"># spread across transects</span></span>
<span id="cb26-23"><span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">round</span>(<span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">c</span>(<span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">this_transect =</span> month_decade,</span>
<span id="cb26-24">        <span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">sim_per_decade =</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">per_decade</span>(offset_mean),</span>
<span id="cb26-25">        <span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">mcse_per_decade =</span> <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">10</span> <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">*</span> <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">100</span> <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">*</span> offset_mcse,</span>
<span id="cb26-26">        <span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">share_negative =</span> offset_neg, <span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">mcse =</span> offset_neg_se,</span>
<span id="cb26-27">        <span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">month_term_per_decade =</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">per_decade</span>(month_mean_slope),</span>
<span id="cb26-28">        <span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">month_term_mcse =</span> <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">10</span> <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">*</span> <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">100</span> <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">*</span> month_mcse,</span>
<span id="cb26-29">        <span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">sd_without_month =</span> slope_sd[[<span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"offset"</span>]], <span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">sd_with_month =</span> slope_sd[[<span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"month"</span>]]), <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">4</span>)</span></code></pre></div></div>
<div class="cell-output cell-output-stdout">
<pre><code>        this_transect        sim_per_decade       mcse_per_decade 
               3.0607               -0.1594                0.1223 
       share_negative                  mcse month_term_per_decade 
               0.5080                0.0112               -0.0976 
      month_term_mcse      sd_without_month         sd_with_month 
               0.0916                5.4688                4.0974 </code></pre>
</div>
</div>
<p>On the transect above the monthly model gives +3.1 per cent per decade, against -20.4 from the <code>na.rm</code> totals. Across the 2000 transects the average slope converts to -0.16 per cent per decade (Monte Carlo standard error about 0.12), and 50.8 per cent of the transects show a decline (Monte Carlo standard error 1.1), which is what a population with no trend should give: half up, half down. Adding a term for the month, <code>count ~ year + month</code>, does no harm here: its average slope over the same 2000 transects converts to -0.10 per cent per decade (Monte Carlo standard error about 0.09), and the slopes of single transects spread less (standard deviation 4.1 against 5.5 per cent per decade without it), because a year that happens to miss July no longer looks poorer than one that misses April. It is also the version that survives the next section.</p>
<div class="cell">
<div class="cell-output-display">
<div id="fig-totals" class="quarto-float quarto-figure quarto-figure-center anchored" alt="Yearly butterfly totals for one simulated transect from 2005 to 2024, on a y axis from 0 to about 160, with a dotted horizontal line at the true total of 120. Rust points, the sum with na.rm = TRUE, fall from about 110 in 2005 to about 50 in 2024, and their rust trend line falls from about 115 to 75. Green points, six times the mean per walked month, scatter between about 85 and 160 around the dotted line, and their green trend line runs almost flat from about 122 to 129. A row of numbers near the bottom gives the months walked each year, 5 or 6 in the first years and 3 in the last two; in 2006, 2007 and 2008, with all six months walked, only the green point shows.">
<figure class="quarto-float quarto-float-fig figure">
<div aria-describedby="fig-totals-caption-0ceaefa1-69ba-4598-a22c-09a6ac19f8ca">
<img src="https://tidyecology.com/posts/missing-values-in-summaries/index_files/figure-html/fig-totals-1.png" class="img-fluid figure-img" alt="Yearly butterfly totals for one simulated transect from 2005 to 2024, on a y axis from 0 to about 160, with a dotted horizontal line at the true total of 120. Rust points, the sum with na.rm = TRUE, fall from about 110 in 2005 to about 50 in 2024, and their rust trend line falls from about 115 to 75. Green points, six times the mean per walked month, scatter between about 85 and 160 around the dotted line, and their green trend line runs almost flat from about 122 to 129. A row of numbers near the bottom gives the months walked each year, 5 or 6 in the first years and 3 in the last two; in 2006, 2007 and 2008, with all six months walked, only the green point shows." width="720">
</div>
<figcaption class="quarto-float-caption-bottom quarto-float-caption quarto-float-fig" id="fig-totals-caption-0ceaefa1-69ba-4598-a22c-09a6ac19f8ca">
Figure&nbsp;1: One simulated transect with a stable population of 120 butterflies a season. Rust: the yearly total from sum(na.rm = TRUE) with its Poisson trend line. Green: six times the mean count per walked month, with the trend of the monthly Poisson GLM. The dotted line is the true season total; the numbers along the bottom are the months walked each year. In a year with all six months walked the two points coincide.
</figcaption>
</figure>
</div>
</div>
</div>
</section>
<section id="when-some-months-are-missed-more-than-others" class="level2">
<h2 id="when-some-months-are-missed-more-than-others-h" class="anchored" data-anchor-id="when-some-months-are-missed-more-than-others">When some months are missed more than others</h2>
<p>Both fixes rest on one assumption: once the year is known, a month is missed for reasons that have nothing to do with how many butterflies it would have had. In the simulation above that is true by construction: the chance of a missed walk depends on the year and on nothing else. That is not “missing completely at random” in the sense of <a href="https://tidyecology.com/posts/missing-data-mechanisms-mcar-mar-mnar/">Missing data: MCAR, MAR and MNAR</a>, because the chance changes with the year; it is missing at random given the year, and a summary or a model that takes the year into account, as both fixes do, is not biased by it. Nakagawa and Freckleton (2008) set out why ecologists should at least check which case their missing values are in before they drop anything.</p>
<p>Suppose instead that the volunteers who drop out stop walking at the edges of the season. The next chunk keeps the same share of missed months each year but puts every missed walk in April, May or September, the three months with the lowest expected counts, each missed with twice the yearly probability:</p>
<div class="cell">
<div class="code-copy-outer-scaffold"><div class="sourceCode cell-code" id="cb28" style="background: #f1f3f5;"><pre class="sourceCode r code-with-copy"><code class="sourceCode r"><span id="cb28-1">edge_months <span class="ot" style="color: #003B4F;
background-color: null;
font-style: inherit;">&lt;-</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">c</span>(<span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"Apr"</span>, <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"May"</span>, <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"Sep"</span>)</span>
<span id="cb28-2">p_edge <span class="ot" style="color: #003B4F;
background-color: null;
font-style: inherit;">&lt;-</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">matrix</span>(<span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">0</span>, <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">length</span>(years), <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">6</span>, <span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">dimnames =</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">list</span>(years, months))</span>
<span id="cb28-3">p_edge[, edge_months] <span class="ot" style="color: #003B4F;
background-color: null;
font-style: inherit;">&lt;-</span> <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">2</span> <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">*</span> p_missed                 <span class="co" style="color: #5E5E5E;
background-color: null;
font-style: inherit;"># same expected share missed per year</span></span>
<span id="cb28-4"><span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">stopifnot</span>(<span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">isTRUE</span>(<span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">all.equal</span>(<span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">rowMeans</span>(p_edge), p_missed, <span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">check.attributes =</span> <span class="cn" style="color: #8f5902;
background-color: null;
font-style: inherit;">FALSE</span>)))</span>
<span id="cb28-5"></span>
<span id="cb28-6">trend_edge <span class="ot" style="color: #003B4F;
background-color: null;
font-style: inherit;">&lt;-</span> <span class="cf" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">function</span>(counts) {</span>
<span id="cb28-7">  long <span class="ot" style="color: #003B4F;
background-color: null;
font-style: inherit;">&lt;-</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">data.frame</span>(<span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">year  =</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">rep</span>(years, <span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">times =</span> <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">6</span>),</span>
<span id="cb28-8">                     <span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">month =</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">factor</span>(<span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">rep</span>(months, <span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">each =</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">length</span>(years)), <span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">levels =</span> months),</span>
<span id="cb28-9">                     <span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">count =</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">as.vector</span>(counts))</span>
<span id="cb28-10">  <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">c</span>(<span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">naive       =</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">coef</span>(<span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">glm</span>(<span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">rowSums</span>(counts, <span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">na.rm =</span> <span class="cn" style="color: #8f5902;
background-color: null;
font-style: inherit;">TRUE</span>) <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">~</span> years, <span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">family =</span> poisson))[[<span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"years"</span>]],</span>
<span id="cb28-11">    <span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">per_walk    =</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">coef</span>(<span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">glm</span>(count <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">~</span> year, <span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">family =</span> poisson, <span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">data =</span> long))[[<span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"year"</span>]],</span>
<span id="cb28-12">    <span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">month_term  =</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">coef</span>(<span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">glm</span>(count <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">~</span> year <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">+</span> month, <span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">family =</span> poisson, <span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">data =</span> long))[[<span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"year"</span>]])</span>
<span id="cb28-13">}</span>
<span id="cb28-14"></span>
<span id="cb28-15"><span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">set.seed</span>(<span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">2017</span>)</span>
<span id="cb28-16">reps_edge <span class="ot" style="color: #003B4F;
background-color: null;
font-style: inherit;">&lt;-</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">t</span>(<span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">replicate</span>(n_rep, <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">trend_edge</span>(<span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">simulate_transect</span>(p_edge))))</span>
<span id="cb28-17">edge_decade <span class="ot" style="color: #003B4F;
background-color: null;
font-style: inherit;">&lt;-</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">per_decade</span>(<span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">colMeans</span>(reps_edge))</span>
<span id="cb28-18">edge_mcse   <span class="ot" style="color: #003B4F;
background-color: null;
font-style: inherit;">&lt;-</span> <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">10</span> <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">*</span> <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">100</span> <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">*</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">apply</span>(reps_edge, <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">2</span>, sd) <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">/</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">sqrt</span>(n_rep)</span>
<span id="cb28-19">edge_up     <span class="ot" style="color: #003B4F;
background-color: null;
font-style: inherit;">&lt;-</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">mean</span>(reps_edge[, <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"per_walk"</span>] <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">&gt;</span> <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">0</span>)</span>
<span id="cb28-20"><span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">round</span>(<span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">rbind</span>(<span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">per_decade =</span> edge_decade, <span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">mcse =</span> edge_mcse), <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">2</span>)</span></code></pre></div></div>
<div class="cell-output cell-output-stdout">
<pre><code>            naive per_walk month_term
per_decade -11.92    11.90       0.07
mcse         0.12     0.11       0.09</code></pre>
</div>
<div class="code-copy-outer-scaffold"><div class="sourceCode cell-code" id="cb30" style="background: #f1f3f5;"><pre class="sourceCode r code-with-copy"><code class="sourceCode r"><span id="cb30-1"><span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">c</span>(<span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">share_per_walk_rising =</span> edge_up)</span></code></pre></div></div>
<div class="cell-output cell-output-stdout">
<pre><code>share_per_walk_rising 
                0.992 </code></pre>
</div>
</div>
<p>Now the naive total falls by 11.9 per cent per decade, less than before, because the months being lost are the ones that held few butterflies. The mean per walked month goes wrong the other way: the months still walked are increasingly the rich midsummer ones, and the monthly GLM without a month term reports +11.9 per cent per decade, an increase in 99 per cent of the transects. Here the reason for missing a walk is the month, and the month is recorded, so it can go into the model: <code>count ~ year + month</code> compares each month with itself across years and gives +0.07 per cent per decade. In the terms of Rubin (1976) this is still missing at random, now given the year and the month, so the model needs both. Butterfly monitoring schemes take the same route with more machinery: a model of the seasonal pattern, fitted to the counts that were made, gives an index of abundance that allows for missing counts (Rothery and Roy 2001). If walks were missed because of the weather on days with few butterflies, and the weather was not recorded, neither fix could correct it from these counts alone.</p>
</section>
<section id="what-to-check-in-your-own-data" class="level2">
<h2 id="what-to-check-in-your-own-data-h" class="anchored" data-anchor-id="what-to-check-in-your-own-data">What to check in your own data</h2>
<p>Before any <code>na.rm = TRUE</code>, count the missing values per group: <code>rowSums(is.na(counts))</code> or <code>table(year, is.na(count))</code>. If that count changes over the years, a sum with <code>na.rm = TRUE</code> will change with it.</p>
<p>Keep the number of visits in the yearly table next to every total, and plot it under the series, as the figure above does. A reader who sees the visits thinning out will ask the right question. A rate per walk is only as good as the walk: it assumes a walk in 2024 is the same effort as a walk in 2005. In casual records, where visits get longer and recorders choose where to go, it is not, and <a href="https://tidyecology.com/posts/reporting-rates-and-effort-drift/">Reporting rates and effort drift</a> measures the false trend that leaves in a per-list rate.</p>
<p>Search your script for <code>sum(</code> and <code>rowSums(</code> with <code>na.rm = TRUE</code> and ask of each one whether a missing value means “nobody looked” or “looked and found none”. Only the second is a zero. For the first, use a mean per visit or a model of the visit-level counts.</p>
<p>Look for zeros in your yearly totals and check each against the number of visits. A zero from a year with no visits should be <code>NA</code>, and it should not reach a trend model.</p>
<p>If visits were missed more in some months or sites than others, put that month or site in the model (as <code>count ~ year + month</code>), and say in the methods why visits were missed, as far as you know.</p>
</section>
<section id="references" class="level2">
<h2 id="references-h" class="anchored" data-anchor-id="references">References</h2>
<p>Nakagawa S, Freckleton RP 2008 Trends in Ecology and Evolution 23(11):592-596 (<a href="https://doi.org/10.1016/j.tree.2008.06.014">10.1016/j.tree.2008.06.014</a>)</p>
<p>Rothery P, Roy DB 2001 Journal of Applied Statistics 28(7):897-909 (<a href="https://doi.org/10.1080/02664760120074979">10.1080/02664760120074979</a>)</p>
<p>Rubin DB 1976 Biometrika 63(3):581-592 (<a href="https://doi.org/10.1093/biomet/63.3.581">10.1093/biomet/63.3.581</a>)</p>
</section>
<section id="related-tutorials" class="level2">
<h2 id="related-tutorials-h" class="anchored" data-anchor-id="related-tutorials">Related tutorials</h2>
<ul>
<li><a href="https://tidyecology.com/posts/reading-field-data-into-r/">Reading field data into R</a></li>
<li><a href="https://tidyecology.com/posts/offsets-for-rates-and-densities/">Offsets for rates and densities in Poisson GLMs</a></li>
<li><a href="https://tidyecology.com/posts/missing-data-mechanisms-mcar-mar-mnar/">Missing data: MCAR, MAR and MNAR</a></li>
<li><a href="https://tidyecology.com/posts/testing-your-analysis-code/">Testing your analysis code</a></li>
</ul>
<details class="te-repro" data-pagefind-ignore="">
<summary>Reproducibility</summary>
<ul>
<li>Code last run: 2026-11-06</li>
<li>R version 4.5.3 (2026-03-11), aarch64-apple-darwin20</li>
<li>Packages: ggplot2 4.0.3</li>
</ul>
</details>


<!-- -->

</section>

 ]]></description>
  <category>R</category>
  <category>missing data</category>
  <category>monitoring</category>
  <category>count data</category>
  <category>GLM</category>
  <category>ecology tutorial</category>
  <guid isPermaLink="false">https://tidyecology.com/posts/missing-values-in-summaries/</guid>
  <pubDate>Sun, 27 Sep 2026 08:00:00 GMT</pubDate>
  <media:content url="https://tidyecology.com/posts/missing-values-in-summaries/thumbnail.png" medium="image" type="image/png" height="104" width="144"/>
</item>
<item>
  <title>Recoding field data in R: ifelse, if_else, case_when</title>
  <dc:creator>Tidy Ecology</dc:creator>
  <link>https://tidyecology.com/posts/recoding-with-case-when/</link>
  <description><![CDATA[ 





<p>A tree inventory records one number per stem: the diameter at breast height, in centimetres. The report wants something coarser. The protocol says a stem under 10 cm is a sapling, 10 to under 25 cm is a pole, 25 to under 50 cm is a mature tree and anything from 50 cm up is a large tree, and the table of counts per class is the first thing anybody reads. Turning a measurement into classes like this is called recoding, and in R it is one line of <code>case_when()</code>, <code>if_else()</code> or <code>ifelse()</code>. The line runs, the table looks like a table, and the counts can still be wrong.</p>
<p>This post recodes one simulated inventory in several ways and measures what each mistake does to the counts. It stays with numbers turned into classes. Recoding text by a lookup table is the subject of <a href="https://tidyecology.com/posts/cleaning-species-names/">Cleaning species names before you count</a>, the difference between a blank cell and <code>NA</code> is in <a href="https://tidyecology.com/posts/reading-field-data-into-r/">Reading field data into R</a>, and parsing dates is in <a href="https://tidyecology.com/posts/dates-and-times-in-ecological-data/">Dates and times in ecological data</a>; this post links to those rather than repeating them.</p>
<section id="the-short-answer" class="level2">
<h2 id="the-short-answer-h" class="anchored" data-anchor-id="the-short-answer">The short answer</h2>
<p>Write the conditions of a <code>case_when()</code> from the most specific to the most general, or write each class as a closed interval so the order cannot matter. Deal with missing values in their own line before any catch-all, because a catch-all takes them too. Use <code>dplyr::if_else()</code> rather than base <code>ifelse()</code> when the result is a date or a factor, and check the class of what comes back. When the classes are intervals, <code>cut()</code> with explicit breaks is often the clearest tool, but check which side of each break a value exactly on the boundary goes to. And after every recode, look at the smallest and largest raw value inside each class.</p>
</section>
<section id="a-simulated-inventory" class="level2">
<h2 id="a-simulated-inventory-h" class="anchored" data-anchor-id="a-simulated-inventory">A simulated inventory</h2>
<p>The data are simulated, with a fixed seed so every number below is reproducible: 400 stems from 5 cm up, diameters recorded to the nearest centimetre as some inventory sheets do, and 20 stems with no diameter at all (a stem behind a fence, a multi-stemmed hazel nobody agreed how to measure).</p>
<div class="cell">
<div class="code-copy-outer-scaffold"><div class="sourceCode cell-code" id="cb1" style="background: #f1f3f5;"><pre class="sourceCode r code-with-copy"><code class="sourceCode r"><span id="cb1-1"><span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">library</span>(dplyr)</span>
<span id="cb1-2"><span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">library</span>(ggplot2)</span>
<span id="cb1-3"></span>
<span id="cb1-4">te_paper  <span class="ot" style="color: #003B4F;
background-color: null;
font-style: inherit;">&lt;-</span> <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"#f5f4ee"</span></span>
<span id="cb1-5">te_ink    <span class="ot" style="color: #003B4F;
background-color: null;
font-style: inherit;">&lt;-</span> <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"#16241d"</span></span>
<span id="cb1-6">te_forest <span class="ot" style="color: #003B4F;
background-color: null;
font-style: inherit;">&lt;-</span> <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"#275139"</span></span>
<span id="cb1-7">te_rust   <span class="ot" style="color: #003B4F;
background-color: null;
font-style: inherit;">&lt;-</span> <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"#b5534e"</span></span>
<span id="cb1-8">te_gold   <span class="ot" style="color: #003B4F;
background-color: null;
font-style: inherit;">&lt;-</span> <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"#c9b458"</span></span>
<span id="cb1-9">te_line   <span class="ot" style="color: #003B4F;
background-color: null;
font-style: inherit;">&lt;-</span> <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"#dad9ca"</span></span>
<span id="cb1-10">te_canvas <span class="ot" style="color: #003B4F;
background-color: null;
font-style: inherit;">&lt;-</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">theme</span>(<span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">plot.background  =</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">element_rect</span>(<span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">fill =</span> te_paper, <span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">colour =</span> <span class="cn" style="color: #8f5902;
background-color: null;
font-style: inherit;">NA</span>),</span>
<span id="cb1-11">                   <span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">panel.background =</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">element_rect</span>(<span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">fill =</span> te_paper, <span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">colour =</span> <span class="cn" style="color: #8f5902;
background-color: null;
font-style: inherit;">NA</span>))</span></code></pre></div></div>
</div>
<div class="cell">
<div class="code-copy-outer-scaffold"><div class="sourceCode cell-code" id="cb2" style="background: #f1f3f5;"><pre class="sourceCode r code-with-copy"><code class="sourceCode r"><span id="cb2-1"><span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">set.seed</span>(<span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">1013</span>)</span>
<span id="cb2-2">n_stem <span class="ot" style="color: #003B4F;
background-color: null;
font-style: inherit;">&lt;-</span> <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">400</span></span>
<span id="cb2-3">n_unmeasured <span class="ot" style="color: #003B4F;
background-color: null;
font-style: inherit;">&lt;-</span> <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">20</span></span>
<span id="cb2-4"></span>
<span id="cb2-5">stems <span class="ot" style="color: #003B4F;
background-color: null;
font-style: inherit;">&lt;-</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">data.frame</span>(</span>
<span id="cb2-6">  <span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">stem =</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">sprintf</span>(<span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"T%03d"</span>, <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">1</span><span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">:</span>n_stem),</span>
<span id="cb2-7">  <span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">dbh  =</span> <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">5</span> <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">+</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">round</span>(<span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">rgamma</span>(n_stem, <span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">shape =</span> <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">2</span>, <span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">rate =</span> <span class="fl" style="color: #AD0000;
background-color: null;
font-style: inherit;">0.1</span>))</span>
<span id="cb2-8">)</span>
<span id="cb2-9">dbh_simulated <span class="ot" style="color: #003B4F;
background-color: null;
font-style: inherit;">&lt;-</span> stems<span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">$</span>dbh   <span class="co" style="color: #5E5E5E;
background-color: null;
font-style: inherit;"># kept aside: the sheet never shows these for the lost stems</span></span>
<span id="cb2-10">stems<span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">$</span>dbh[<span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">sample</span>(n_stem, n_unmeasured)] <span class="ot" style="color: #003B4F;
background-color: null;
font-style: inherit;">&lt;-</span> <span class="cn" style="color: #8f5902;
background-color: null;
font-style: inherit;">NA</span></span>
<span id="cb2-11"></span>
<span id="cb2-12"><span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">summary</span>(stems<span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">$</span>dbh)</span></code></pre></div></div>
<div class="cell-output cell-output-stdout">
<pre><code>   Min. 1st Qu.  Median    Mean 3rd Qu.    Max.    NA's 
   6.00   15.00   22.00   25.55   33.00   84.00      20 </code></pre>
</div>
</div>
<p>The diameters run from 6 to 84 cm with a median of 22 cm. Half of the measured stems lie between 15 and 33 cm, with few saplings and a long tail of big trees. That hump-shaped distribution fits a stand that regenerated mostly at one time, not an uneven-aged wood, where the thinnest stems are the most numerous.</p>
</section>
<section id="case_when-stops-at-the-first-true-condition" class="level2">
<h2 id="case_when-stops-at-the-first-true-condition-h" class="anchored" data-anchor-id="case_when-stops-at-the-first-true-condition">case_when() stops at the first true condition</h2>
<p><code>case_when()</code> reads its conditions from top to bottom, and each stem gets the value of the first condition that is true for it. The later lines are never consulted for that stem. The dplyr documentation says so, and the chunk below checks it on the single value 30:</p>
<div class="cell">
<div class="code-copy-outer-scaffold"><div class="sourceCode cell-code" id="cb4" style="background: #f1f3f5;"><pre class="sourceCode r code-with-copy"><code class="sourceCode r"><span id="cb4-1"><span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">stopifnot</span>(<span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">case_when</span>(<span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">30</span> <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">&gt;</span> <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">10</span> <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">~</span> <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"pole"</span>, <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">30</span> <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">&gt;</span> <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">25</span> <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">~</span> <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"mature"</span>) <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">==</span> <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"pole"</span>)</span></code></pre></div></div>
</div>
<p>Now the recode as it is often first written, with the thresholds in the order they appear in the protocol, lowest first:</p>
<div class="cell">
<div class="code-copy-outer-scaffold"><div class="sourceCode cell-code" id="cb5" style="background: #f1f3f5;"><pre class="sourceCode r code-with-copy"><code class="sourceCode r"><span id="cb5-1">stems <span class="ot" style="color: #003B4F;
background-color: null;
font-style: inherit;">&lt;-</span> stems <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">|&gt;</span></span>
<span id="cb5-2">  <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">mutate</span>(<span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">class_lowest_first =</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">case_when</span>(</span>
<span id="cb5-3">    dbh <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">&gt;=</span> <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">10</span> <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">~</span> <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"pole"</span>,</span>
<span id="cb5-4">    dbh <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">&gt;=</span> <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">25</span> <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">~</span> <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"mature"</span>,</span>
<span id="cb5-5">    dbh <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">&gt;=</span> <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">50</span> <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">~</span> <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"large"</span>,</span>
<span id="cb5-6">    dbh <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">&lt;</span> <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">10</span>  <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">~</span> <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"sapling"</span></span>
<span id="cb5-7">  ))</span>
<span id="cb5-8"><span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">count</span>(stems, class_lowest_first)</span></code></pre></div></div>
<div class="cell-output cell-output-stdout">
<pre><code>  class_lowest_first   n
1               pole 351
2            sapling  29
3               &lt;NA&gt;  20</code></pre>
</div>
</div>
<p>There is no mature tree and no large tree in the whole wood. A stem of 60 cm satisfies <code>dbh &gt;= 10</code>, so it becomes a pole and the two lines below that one never see it. Put the most specific condition first and the same four lines give the protocol’s classes:</p>
<div class="cell">
<div class="code-copy-outer-scaffold"><div class="sourceCode cell-code" id="cb7" style="background: #f1f3f5;"><pre class="sourceCode r code-with-copy"><code class="sourceCode r"><span id="cb7-1">stems <span class="ot" style="color: #003B4F;
background-color: null;
font-style: inherit;">&lt;-</span> stems <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">|&gt;</span></span>
<span id="cb7-2">  <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">mutate</span>(<span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">size_class =</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">case_when</span>(</span>
<span id="cb7-3">    dbh <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">&gt;=</span> <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">50</span> <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">~</span> <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"large"</span>,</span>
<span id="cb7-4">    dbh <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">&gt;=</span> <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">25</span> <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">~</span> <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"mature"</span>,</span>
<span id="cb7-5">    dbh <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">&gt;=</span> <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">10</span> <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">~</span> <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"pole"</span>,</span>
<span id="cb7-6">    dbh <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">&lt;</span> <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">10</span>  <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">~</span> <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"sapling"</span></span>
<span id="cb7-7">  ))</span>
<span id="cb7-8"><span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">count</span>(stems, size_class)</span></code></pre></div></div>
<div class="cell-output cell-output-stdout">
<pre><code>  size_class   n
1      large  23
2     mature 137
3       pole 191
4    sapling  29
5       &lt;NA&gt;  20</code></pre>
</div>
<div class="code-copy-outer-scaffold"><div class="sourceCode cell-code" id="cb9" style="background: #f1f3f5;"><pre class="sourceCode r code-with-copy"><code class="sourceCode r"><span id="cb9-1">n_wrong <span class="ot" style="color: #003B4F;
background-color: null;
font-style: inherit;">&lt;-</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">sum</span>(stems<span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">$</span>class_lowest_first <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">!=</span> stems<span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">$</span>size_class, <span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">na.rm =</span> <span class="cn" style="color: #8f5902;
background-color: null;
font-style: inherit;">TRUE</span>)</span>
<span id="cb9-2">n_measured <span class="ot" style="color: #003B4F;
background-color: null;
font-style: inherit;">&lt;-</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">sum</span>(<span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">!</span><span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">is.na</span>(stems<span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">$</span>dbh))</span>
<span id="cb9-3">d <span class="ot" style="color: #003B4F;
background-color: null;
font-style: inherit;">&lt;-</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">which</span>(stems<span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">$</span>class_lowest_first <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">!=</span> stems<span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">$</span>size_class)</span>
<span id="cb9-4"><span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">stopifnot</span>(<span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">all</span>(stems<span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">$</span>class_lowest_first[d] <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">==</span> <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"pole"</span>),</span>
<span id="cb9-5">          <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">identical</span>(d, <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">which</span>(stems<span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">$</span>size_class <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">%in%</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">c</span>(<span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"mature"</span>, <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"large"</span>))))</span></code></pre></div></div>
</div>
<p>The two versions disagree on 160 of the 380 measured stems, 42.1 per cent of them, and every one of those was a mature or large tree filed as a pole. Nothing warned.</p>
<p>The share is not a property of the code. With the lowest threshold first, every stem of 25 cm or more becomes a pole, so the share misclassified is simply the share of stems in the two higher classes. For this simulated stand it can be worked out without the data: a diameter is 25 cm or more when the rounded gamma draw is 20 or more, that is, when the draw itself is at least 19.5.</p>
<div class="cell">
<div class="code-copy-outer-scaffold"><div class="sourceCode cell-code" id="cb10" style="background: #f1f3f5;"><pre class="sourceCode r code-with-copy"><code class="sourceCode r"><span id="cb10-1">p_big <span class="ot" style="color: #003B4F;
background-color: null;
font-style: inherit;">&lt;-</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">pgamma</span>(<span class="fl" style="color: #AD0000;
background-color: null;
font-style: inherit;">19.5</span>, <span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">shape =</span> <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">2</span>, <span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">rate =</span> <span class="fl" style="color: #AD0000;
background-color: null;
font-style: inherit;">0.1</span>, <span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">lower.tail =</span> <span class="cn" style="color: #8f5902;
background-color: null;
font-style: inherit;">FALSE</span>)</span>
<span id="cb10-2">p_big</span></code></pre></div></div>
<div class="cell-output cell-output-stdout">
<pre><code>[1] 0.4197085</code></pre>
</div>
</div>
<p>The expected share is 42.0 per cent, and the 42.1 per cent above is what one draw of 400 stems gave. In a stand with few trees of 25 cm or more, the same code would move few stems; in a stand of mostly big trees it would move most of them.</p>
<p>The alternative that does not depend on order at all is to write each class as a closed interval, <code>dbh &gt;= 10 &amp; dbh &lt; 25 ~ "pole"</code>, so that no stem can satisfy two lines. It is longer, and it is the version to prefer when somebody else will edit the code later.</p>
</section>
<section id="missing-values-fall-through-to-the-catch-all" class="level2">
<h2 id="missing-values-fall-through-to-the-catch-all-h" class="anchored" data-anchor-id="missing-values-fall-through-to-the-catch-all">Missing values fall through to the catch-all</h2>
<p>Most recodes end with a line that catches everything left over. In dplyr 1.1.0 and later that is the <code>.default</code> argument; older code writes <code>TRUE ~ "sapling"</code>, which does the same. It is tempting for the smallest class, because anything not caught above must be small.</p>
<div class="cell">
<div class="code-copy-outer-scaffold"><div class="sourceCode cell-code" id="cb12" style="background: #f1f3f5;"><pre class="sourceCode r code-with-copy"><code class="sourceCode r"><span id="cb12-1">stems <span class="ot" style="color: #003B4F;
background-color: null;
font-style: inherit;">&lt;-</span> stems <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">|&gt;</span></span>
<span id="cb12-2">  <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">mutate</span>(<span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">class_catch_all =</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">case_when</span>(</span>
<span id="cb12-3">    dbh <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">&gt;=</span> <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">50</span> <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">~</span> <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"large"</span>,</span>
<span id="cb12-4">    dbh <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">&gt;=</span> <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">25</span> <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">~</span> <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"mature"</span>,</span>
<span id="cb12-5">    dbh <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">&gt;=</span> <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">10</span> <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">~</span> <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"pole"</span>,</span>
<span id="cb12-6">    <span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">.default  =</span> <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"sapling"</span></span>
<span id="cb12-7">  ))</span>
<span id="cb12-8"><span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">count</span>(stems, class_catch_all)</span></code></pre></div></div>
<div class="cell-output cell-output-stdout">
<pre><code>  class_catch_all   n
1           large  23
2          mature 137
3            pole 191
4         sapling  49</code></pre>
</div>
</div>
<p>The <code>NA</code> row has gone, and the saplings have grown by exactly the number of unmeasured stems. For a stem with no diameter, <code>dbh &gt;= 50</code> is <code>NA</code>, not <code>FALSE</code>, and <code>case_when()</code> treats an <code>NA</code> condition as not true, moves on, and ends up at the catch-all. The documentation for <code>.default</code> states this directly, and it is the behaviour the next chunk guards, together with what happens when there is no catch-all:</p>
<div class="cell">
<div class="code-copy-outer-scaffold"><div class="sourceCode cell-code" id="cb14" style="background: #f1f3f5;"><pre class="sourceCode r code-with-copy"><code class="sourceCode r"><span id="cb14-1"><span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">stopifnot</span>(</span>
<span id="cb14-2">  <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">case_when</span>(<span class="cn" style="color: #8f5902;
background-color: null;
font-style: inherit;">NA_real_</span> <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">&gt;</span> <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">10</span> <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">~</span> <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"pole"</span>, <span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">.default =</span> <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"sapling"</span>) <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">==</span> <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"sapling"</span>,</span>
<span id="cb14-3">  <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">is.na</span>(<span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">case_when</span>(<span class="cn" style="color: #8f5902;
background-color: null;
font-style: inherit;">NA_real_</span> <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">&gt;</span> <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">10</span> <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">~</span> <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"pole"</span>))</span>
<span id="cb14-4">)</span>
<span id="cb14-5"></span>
<span id="cb14-6">share_true  <span class="ot" style="color: #003B4F;
background-color: null;
font-style: inherit;">&lt;-</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">mean</span>(stems<span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">$</span>size_class <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">==</span> <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"sapling"</span>, <span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">na.rm =</span> <span class="cn" style="color: #8f5902;
background-color: null;
font-style: inherit;">TRUE</span>)</span>
<span id="cb14-7">share_catch <span class="ot" style="color: #003B4F;
background-color: null;
font-style: inherit;">&lt;-</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">mean</span>(stems<span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">$</span>class_catch_all <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">==</span> <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"sapling"</span>)</span>
<span id="cb14-8">n_moved <span class="ot" style="color: #003B4F;
background-color: null;
font-style: inherit;">&lt;-</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">sum</span>(<span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">is.na</span>(stems<span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">$</span>dbh) <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">&amp;</span> stems<span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">$</span>class_catch_all <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">==</span> <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"sapling"</span>)</span>
<span id="cb14-9">n_moved_small <span class="ot" style="color: #003B4F;
background-color: null;
font-style: inherit;">&lt;-</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">sum</span>(<span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">is.na</span>(stems<span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">$</span>dbh) <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">&amp;</span> dbh_simulated <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">&lt;</span> <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">10</span>)</span></code></pre></div></div>
</div>
<p>20 stems of unknown size are now saplings. The sapling share of the measured stems is 7.6 per cent; in the catch-all version it is 12.2 per cent, and it looks like a finding about regeneration rather than a gap on the data sheet. Because the data are simulated, we can look up the diameters those stems had before they were lost: only 1 of the 20 had been under 10 cm. The catch-all did not guess the class of an unknown stem; it filed all of them in the one class that happened to be written last.</p>
<p>The fix is one line at the top, or no catch-all at all:</p>
<div class="cell">
<div class="code-copy-outer-scaffold"><div class="sourceCode cell-code" id="cb15" style="background: #f1f3f5;"><pre class="sourceCode r code-with-copy"><code class="sourceCode r"><span id="cb15-1">stems <span class="ot" style="color: #003B4F;
background-color: null;
font-style: inherit;">&lt;-</span> stems <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">|&gt;</span></span>
<span id="cb15-2">  <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">mutate</span>(<span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">class_na_first =</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">case_when</span>(</span>
<span id="cb15-3">    <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">is.na</span>(dbh) <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">~</span> <span class="cn" style="color: #8f5902;
background-color: null;
font-style: inherit;">NA</span>,</span>
<span id="cb15-4">    dbh <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">&gt;=</span> <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">50</span>  <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">~</span> <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"large"</span>,</span>
<span id="cb15-5">    dbh <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">&gt;=</span> <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">25</span>  <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">~</span> <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"mature"</span>,</span>
<span id="cb15-6">    dbh <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">&gt;=</span> <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">10</span>  <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">~</span> <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"pole"</span>,</span>
<span id="cb15-7">    <span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">.default   =</span> <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"sapling"</span></span>
<span id="cb15-8">  ))</span>
<span id="cb15-9"><span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">stopifnot</span>(<span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">identical</span>(stems<span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">$</span>class_na_first, stems<span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">$</span>size_class))</span></code></pre></div></div>
</div>
<p>With <code>is.na(dbh) ~ NA</code> first, the catch-all only sees measured stems, and the result is identical to the four-condition version. The recode in <code>size_class</code> needed no such line because it had no catch-all: a stem that matched nothing got <code>NA</code>, which is what an unmeasured stem should get. dplyr 1.2.0 added a third option, <code>.unmatched = "error"</code>, which stops with an error instead of filling in when a value matches no line (<a href="https://dplyr.tidyverse.org/news/">the dplyr changelog</a>). It is not in dplyr 1.1.4, the version this post was written with, so it is not run here.</p>
<div class="cell">
<div class="code-copy-outer-scaffold"><div class="sourceCode cell-code" id="cb16" style="background: #f1f3f5;"><pre class="sourceCode r code-with-copy"><code class="sourceCode r"><span id="cb16-1">class_levels <span class="ot" style="color: #003B4F;
background-color: null;
font-style: inherit;">&lt;-</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">c</span>(<span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"sapling"</span>, <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"pole"</span>, <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"mature"</span>, <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"large"</span>, <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"not measured"</span>)</span>
<span id="cb16-2">version_levels <span class="ot" style="color: #003B4F;
background-color: null;
font-style: inherit;">&lt;-</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">c</span>(<span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"lowest threshold first"</span>, <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"catch-all for saplings"</span>, <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"highest threshold first"</span>)</span>
<span id="cb16-3"></span>
<span id="cb16-4">tally <span class="ot" style="color: #003B4F;
background-color: null;
font-style: inherit;">&lt;-</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">bind_rows</span>(</span>
<span id="cb16-5">  <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">count</span>(stems, <span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">class =</span> class_lowest_first) <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">|&gt;</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">mutate</span>(<span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">version =</span> version_levels[<span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">1</span>]),</span>
<span id="cb16-6">  <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">count</span>(stems, <span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">class =</span> class_catch_all)    <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">|&gt;</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">mutate</span>(<span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">version =</span> version_levels[<span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">2</span>]),</span>
<span id="cb16-7">  <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">count</span>(stems, <span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">class =</span> size_class)         <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">|&gt;</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">mutate</span>(<span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">version =</span> version_levels[<span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">3</span>])</span>
<span id="cb16-8">) <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">|&gt;</span></span>
<span id="cb16-9">  <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">mutate</span>(<span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">class =</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">coalesce</span>(class, <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"not measured"</span>))</span>
<span id="cb16-10"></span>
<span id="cb16-11"><span class="co" style="color: #5E5E5E;
background-color: null;
font-style: inherit;"># every class in every version, with 0 where a version has no stems in it</span></span>
<span id="cb16-12">tally <span class="ot" style="color: #003B4F;
background-color: null;
font-style: inherit;">&lt;-</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">expand.grid</span>(<span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">class =</span> class_levels, <span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">version =</span> version_levels,</span>
<span id="cb16-13">                     <span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">stringsAsFactors =</span> <span class="cn" style="color: #8f5902;
background-color: null;
font-style: inherit;">FALSE</span>) <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">|&gt;</span></span>
<span id="cb16-14">  <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">left_join</span>(tally, <span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">by =</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">c</span>(<span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"class"</span>, <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"version"</span>)) <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">|&gt;</span></span>
<span id="cb16-15">  <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">mutate</span>(<span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">n =</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">coalesce</span>(n, <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">0</span>L),</span>
<span id="cb16-16">         <span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">class =</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">factor</span>(class, <span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">levels =</span> class_levels),</span>
<span id="cb16-17">         <span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">version =</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">factor</span>(version, <span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">levels =</span> version_levels))</span>
<span id="cb16-18"></span>
<span id="cb16-19"><span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">ggplot</span>(tally, <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">aes</span>(class, n, <span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">fill =</span> version)) <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">+</span></span>
<span id="cb16-20">  <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">geom_col</span>(<span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">position =</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">position_dodge</span>(<span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">width =</span> <span class="fl" style="color: #AD0000;
background-color: null;
font-style: inherit;">0.8</span>), <span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">width =</span> <span class="fl" style="color: #AD0000;
background-color: null;
font-style: inherit;">0.78</span>) <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">+</span></span>
<span id="cb16-21">  <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">geom_text</span>(<span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">aes</span>(<span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">label =</span> n), <span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">position =</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">position_dodge</span>(<span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">width =</span> <span class="fl" style="color: #AD0000;
background-color: null;
font-style: inherit;">0.8</span>),</span>
<span id="cb16-22">            <span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">vjust =</span> <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">-</span><span class="fl" style="color: #AD0000;
background-color: null;
font-style: inherit;">0.4</span>, <span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">size =</span> <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">3</span>, <span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">colour =</span> te_ink) <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">+</span></span>
<span id="cb16-23">  <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">scale_fill_manual</span>(<span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">values =</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">c</span>(te_rust, te_gold, te_forest)) <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">+</span></span>
<span id="cb16-24">  <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">scale_y_continuous</span>(<span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">expand =</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">expansion</span>(<span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">mult =</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">c</span>(<span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">0</span>, <span class="fl" style="color: #AD0000;
background-color: null;
font-style: inherit;">0.08</span>))) <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">+</span></span>
<span id="cb16-25">  <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">labs</span>(<span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">x =</span> <span class="cn" style="color: #8f5902;
background-color: null;
font-style: inherit;">NULL</span>, <span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">y =</span> <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"number of stems"</span>, <span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">fill =</span> <span class="cn" style="color: #8f5902;
background-color: null;
font-style: inherit;">NULL</span>) <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">+</span></span>
<span id="cb16-26">  <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">theme_minimal</span>(<span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">base_size =</span> <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">12</span>) <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">+</span> te_canvas <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">+</span></span>
<span id="cb16-27">  <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">theme</span>(<span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">legend.position =</span> <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"top"</span>, <span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">panel.grid.minor =</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">element_blank</span>(),</span>
<span id="cb16-28">        <span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">panel.grid.major.x =</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">element_blank</span>(),</span>
<span id="cb16-29">        <span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">text =</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">element_text</span>(<span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">colour =</span> te_ink))</span></code></pre></div></div>
<div class="cell-output-display">
<div id="fig-classes" class="quarto-float quarto-figure quarto-figure-center anchored" alt="Grouped bar chart of stem counts in five classes, sapling, pole, mature, large and not measured, for three recodes of the same inventory. Red bars, lowest threshold first: 29 saplings, 351 poles, 0 mature, 0 large and 20 not measured. Gold bars, catch-all for saplings: 49 saplings, 191 poles, 137 mature, 23 large and 0 not measured. Green bars, highest threshold first: 29, 191, 137, 23 and 20. Each bar has its count printed above it.">
<figure class="quarto-float quarto-float-fig figure">
<div aria-describedby="fig-classes-caption-0ceaefa1-69ba-4598-a22c-09a6ac19f8ca">
<img src="https://tidyecology.com/posts/recoding-with-case-when/index_files/figure-html/fig-classes-1.png" class="img-fluid figure-img" alt="Grouped bar chart of stem counts in five classes, sapling, pole, mature, large and not measured, for three recodes of the same inventory. Red bars, lowest threshold first: 29 saplings, 351 poles, 0 mature, 0 large and 20 not measured. Gold bars, catch-all for saplings: 49 saplings, 191 poles, 137 mature, 23 large and 0 not measured. Green bars, highest threshold first: 29, 191, 137, 23 and 20. Each bar has its count printed above it." width="672">
</div>
<figcaption class="quarto-float-caption-bottom quarto-float-caption quarto-float-fig" id="fig-classes-caption-0ceaefa1-69ba-4598-a22c-09a6ac19f8ca">
Figure&nbsp;1: Stems per size class in the same simulated inventory, recoded three ways. With the lowest threshold first, every stem of 10 cm or more is filed as a pole. With a catch-all for saplings, the unmeasured stems join the saplings. With the highest threshold first and no catch-all, the classes match the protocol and the unmeasured stems stay a group of their own.
</figcaption>
</figure>
</div>
</div>
</div>
</section>
<section id="ifelse-and-if_else" class="level2">
<h2 id="ifelse-and-if_else-h" class="anchored" data-anchor-id="ifelse-and-if_else">ifelse() and if_else()</h2>
<p>For two classes, <code>ifelse()</code> from base R and <code>if_else()</code> from dplyr look interchangeable, and for a character result they are. The difference shows with dates. Suppose ten plots were each planned for a visit a week apart, the visit date was written on the sheet, and two sheets have no date. Filling a missing visit date with the planned one is a common repair:</p>
<div class="cell">
<div class="code-copy-outer-scaffold"><div class="sourceCode cell-code" id="cb17" style="background: #f1f3f5;"><pre class="sourceCode r code-with-copy"><code class="sourceCode r"><span id="cb17-1">plots <span class="ot" style="color: #003B4F;
background-color: null;
font-style: inherit;">&lt;-</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">data.frame</span>(</span>
<span id="cb17-2">  <span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">plot    =</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">sprintf</span>(<span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"P%02d"</span>, <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">1</span><span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">:</span><span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">10</span>),</span>
<span id="cb17-3">  <span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">planned =</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">as.Date</span>(<span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"2025-05-05"</span>) <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">+</span> <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">7</span> <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">*</span> (<span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">0</span><span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">:</span><span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">9</span>)</span>
<span id="cb17-4">)</span>
<span id="cb17-5">plots<span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">$</span>visited <span class="ot" style="color: #003B4F;
background-color: null;
font-style: inherit;">&lt;-</span> plots<span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">$</span>planned <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">+</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">sample</span>(<span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">0</span><span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">:</span><span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">3</span>, <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">10</span>, <span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">replace =</span> <span class="cn" style="color: #8f5902;
background-color: null;
font-style: inherit;">TRUE</span>)</span>
<span id="cb17-6">plots<span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">$</span>visited[<span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">c</span>(<span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">4</span>, <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">9</span>)] <span class="ot" style="color: #003B4F;
background-color: null;
font-style: inherit;">&lt;-</span> <span class="cn" style="color: #8f5902;
background-color: null;
font-style: inherit;">NA</span></span>
<span id="cb17-7"></span>
<span id="cb17-8">filled_base  <span class="ot" style="color: #003B4F;
background-color: null;
font-style: inherit;">&lt;-</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">ifelse</span>(<span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">is.na</span>(plots<span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">$</span>visited), plots<span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">$</span>planned, plots<span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">$</span>visited)</span>
<span id="cb17-9">filled_dplyr <span class="ot" style="color: #003B4F;
background-color: null;
font-style: inherit;">&lt;-</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">if_else</span>(<span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">is.na</span>(plots<span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">$</span>visited), plots<span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">$</span>planned, plots<span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">$</span>visited)</span>
<span id="cb17-10"><span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">head</span>(filled_base, <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">3</span>)</span></code></pre></div></div>
<div class="cell-output cell-output-stdout">
<pre><code>[1] 20214 20223 20230</code></pre>
</div>
<div class="code-copy-outer-scaffold"><div class="sourceCode cell-code" id="cb19" style="background: #f1f3f5;"><pre class="sourceCode r code-with-copy"><code class="sourceCode r"><span id="cb19-1"><span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">head</span>(filled_dplyr, <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">3</span>)</span></code></pre></div></div>
<div class="cell-output cell-output-stdout">
<pre><code>[1] "2025-05-06" "2025-05-15" "2025-05-22"</code></pre>
</div>
<div class="code-copy-outer-scaffold"><div class="sourceCode cell-code" id="cb21" style="background: #f1f3f5;"><pre class="sourceCode r code-with-copy"><code class="sourceCode r"><span id="cb21-1"><span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">stopifnot</span>(<span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">is.numeric</span>(filled_base), <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">!</span><span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">inherits</span>(filled_base, <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"Date"</span>),</span>
<span id="cb21-2">          <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">inherits</span>(filled_dplyr, <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"Date"</span>))</span></code></pre></div></div>
</div>
<p><code>ifelse()</code> returned 20214 where the sheet said 2025-05-06. The help page for <code>ifelse()</code> explains why: the result takes its attributes, including the class, from the condition, which is a plain logical vector, so the <code>Date</code> class is dropped and the day count underneath is all that remains. <code>if_else()</code> keeps the class of <code>true</code> and <code>false</code>. The same thing happens with a factor, where <code>ifelse()</code> returns the level codes:</p>
<div class="cell">
<div class="code-copy-outer-scaffold"><div class="sourceCode cell-code" id="cb22" style="background: #f1f3f5;"><pre class="sourceCode r code-with-copy"><code class="sourceCode r"><span id="cb22-1">habitat <span class="ot" style="color: #003B4F;
background-color: null;
font-style: inherit;">&lt;-</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">factor</span>(<span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">c</span>(<span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"wood"</span>, <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"fen"</span>, <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"meadow"</span>, <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"fen"</span>))</span>
<span id="cb22-2"><span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">ifelse</span>(habitat <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">==</span> <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"fen"</span>, <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"wetland"</span>, habitat)</span></code></pre></div></div>
<div class="cell-output cell-output-stdout">
<pre><code>[1] "3"       "wetland" "2"       "wetland"</code></pre>
</div>
<div class="code-copy-outer-scaffold"><div class="sourceCode cell-code" id="cb24" style="background: #f1f3f5;"><pre class="sourceCode r code-with-copy"><code class="sourceCode r"><span id="cb24-1"><span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">if_else</span>(habitat <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">==</span> <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"fen"</span>, <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"wetland"</span>, habitat)</span></code></pre></div></div>
<div class="cell-output cell-output-stdout">
<pre><code>[1] "wood"    "wetland" "meadow"  "wetland"</code></pre>
</div>
<div class="code-copy-outer-scaffold"><div class="sourceCode cell-code" id="cb26" style="background: #f1f3f5;"><pre class="sourceCode r code-with-copy"><code class="sourceCode r"><span id="cb26-1"><span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">stopifnot</span>(<span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">is.character</span>(<span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">if_else</span>(habitat <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">==</span> <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"fen"</span>, <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"wetland"</span>, habitat)),</span>
<span id="cb26-2">          <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">is.character</span>(<span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">if_else</span>(habitat <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">==</span> <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"fen"</span>, <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"meadow"</span>, habitat)))</span></code></pre></div></div>
</div>
<p><code>if_else()</code> returns the labels, as text: a text value and a factor combine to text, whether or not the text is one of the factor’s levels (the second line of the check uses “meadow”, which is). Wrap the result in <code>factor()</code> if you need a factor again.</p>
<p><code>if_else()</code> is also strict where <code>ifelse()</code> is not: it refuses to combine a number and a text value, and it has a <code>missing</code> argument for the case where the condition itself is <code>NA</code>.</p>
<div class="cell">
<div class="code-copy-outer-scaffold"><div class="sourceCode cell-code" id="cb27" style="background: #f1f3f5;"><pre class="sourceCode r code-with-copy"><code class="sourceCode r"><span id="cb27-1"><span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">stopifnot</span>(<span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">inherits</span>(<span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">try</span>(<span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">if_else</span>(<span class="cn" style="color: #8f5902;
background-color: null;
font-style: inherit;">TRUE</span>, <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"sapling"</span>, <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">1</span>), <span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">silent =</span> <span class="cn" style="color: #8f5902;
background-color: null;
font-style: inherit;">TRUE</span>), <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"try-error"</span>))</span>
<span id="cb27-2"></span>
<span id="cb27-3">stems <span class="ot" style="color: #003B4F;
background-color: null;
font-style: inherit;">&lt;-</span> stems <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">|&gt;</span></span>
<span id="cb27-4">  <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">mutate</span>(<span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">tree_or_sapling =</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">if_else</span>(dbh <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">&gt;=</span> <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">10</span>, <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"tree"</span>, <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"sapling"</span>,</span>
<span id="cb27-5">                                   <span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">missing =</span> <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"not measured"</span>))</span>
<span id="cb27-6"><span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">count</span>(stems, tree_or_sapling)</span></code></pre></div></div>
<div class="cell-output cell-output-stdout">
<pre><code>  tree_or_sapling   n
1    not measured  20
2         sapling  29
3            tree 351</code></pre>
</div>
<div class="code-copy-outer-scaffold"><div class="sourceCode cell-code" id="cb29" style="background: #f1f3f5;"><pre class="sourceCode r code-with-copy"><code class="sourceCode r"><span id="cb29-1"><span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">stopifnot</span>(<span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">sum</span>(stems<span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">$</span>tree_or_sapling <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">==</span> <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"not measured"</span>) <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">==</span> n_unmeasured)</span></code></pre></div></div>
</div>
<p>Without <code>missing</code>, those 20 stems would be <code>NA</code>, which is also honest. What <code>if_else()</code> never does is put them in one of the two classes.</p>
</section>
<section id="cut-and-the-stem-on-the-boundary" class="level2">
<h2 id="cut-and-the-stem-on-the-boundary-h" class="anchored" data-anchor-id="cut-and-the-stem-on-the-boundary">cut() and the stem on the boundary</h2>
<p>When the classes are intervals on one measurement, <code>cut()</code> states them as a vector of breaks and cannot get the order wrong. It has its own question to answer: which class does a stem of exactly 10 cm belong to? The default, <code>right = TRUE</code>, closes each interval on the right, so the intervals are (0, 10], (10, 25] and so on, and 10 goes into the lower class.</p>
<div class="cell">
<div class="code-copy-outer-scaffold"><div class="sourceCode cell-code" id="cb30" style="background: #f1f3f5;"><pre class="sourceCode r code-with-copy"><code class="sourceCode r"><span id="cb30-1">breaks <span class="ot" style="color: #003B4F;
background-color: null;
font-style: inherit;">&lt;-</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">c</span>(<span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">0</span>, <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">10</span>, <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">25</span>, <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">50</span>, <span class="cn" style="color: #8f5902;
background-color: null;
font-style: inherit;">Inf</span>)</span>
<span id="cb30-2">size_labels <span class="ot" style="color: #003B4F;
background-color: null;
font-style: inherit;">&lt;-</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">c</span>(<span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"sapling"</span>, <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"pole"</span>, <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"mature"</span>, <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"large"</span>)</span>
<span id="cb30-3"></span>
<span id="cb30-4">stems <span class="ot" style="color: #003B4F;
background-color: null;
font-style: inherit;">&lt;-</span> stems <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">|&gt;</span></span>
<span id="cb30-5">  <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">mutate</span>(<span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">cut_right =</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">cut</span>(dbh, breaks, <span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">labels =</span> size_labels),</span>
<span id="cb30-6">         <span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">cut_left  =</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">cut</span>(dbh, breaks, <span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">labels =</span> size_labels, <span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">right =</span> <span class="cn" style="color: #8f5902;
background-color: null;
font-style: inherit;">FALSE</span>))</span>
<span id="cb30-7"></span>
<span id="cb30-8"><span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">stopifnot</span>(<span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">cut</span>(<span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">10</span>, breaks) <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">==</span> <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"(0,10]"</span>, <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">cut</span>(<span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">10</span>, breaks, <span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">right =</span> <span class="cn" style="color: #8f5902;
background-color: null;
font-style: inherit;">FALSE</span>) <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">==</span> <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"[10,25)"</span>)</span>
<span id="cb30-9"></span>
<span id="cb30-10">n_boundary <span class="ot" style="color: #003B4F;
background-color: null;
font-style: inherit;">&lt;-</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">sum</span>(stems<span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">$</span>dbh <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">%in%</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">c</span>(<span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">10</span>, <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">25</span>, <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">50</span>))</span>
<span id="cb30-11">n_differ_right <span class="ot" style="color: #003B4F;
background-color: null;
font-style: inherit;">&lt;-</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">sum</span>(<span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">as.character</span>(stems<span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">$</span>cut_right) <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">!=</span> stems<span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">$</span>size_class, <span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">na.rm =</span> <span class="cn" style="color: #8f5902;
background-color: null;
font-style: inherit;">TRUE</span>)</span>
<span id="cb30-12">n_differ_left  <span class="ot" style="color: #003B4F;
background-color: null;
font-style: inherit;">&lt;-</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">sum</span>(<span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">as.character</span>(stems<span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">$</span>cut_left)  <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">!=</span> stems<span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">$</span>size_class, <span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">na.rm =</span> <span class="cn" style="color: #8f5902;
background-color: null;
font-style: inherit;">TRUE</span>)</span>
<span id="cb30-13"><span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">c</span>(<span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">on_a_boundary =</span> n_boundary, <span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">default_differs =</span> n_differ_right,</span>
<span id="cb30-14">  <span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">right_false_differs =</span> n_differ_left)</span></code></pre></div></div>
<div class="cell-output cell-output-stdout">
<pre><code>      on_a_boundary     default_differs right_false_differs 
                 21                  21                   0 </code></pre>
</div>
<div class="code-copy-outer-scaffold"><div class="sourceCode cell-code" id="cb32" style="background: #f1f3f5;"><pre class="sourceCode r code-with-copy"><code class="sourceCode r"><span id="cb32-1">differs <span class="ot" style="color: #003B4F;
background-color: null;
font-style: inherit;">&lt;-</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">which</span>(<span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">as.character</span>(stems<span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">$</span>cut_right) <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">!=</span> stems<span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">$</span>size_class)</span>
<span id="cb32-2"><span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">stopifnot</span>(n_differ_left <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">==</span> <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">0</span>,</span>
<span id="cb32-3">          <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">identical</span>(differs, <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">which</span>(stems<span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">$</span>dbh <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">%in%</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">c</span>(<span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">10</span>, <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">25</span>, <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">50</span>))))</span></code></pre></div></div>
</div>
<p>The protocol says “10 to under 25 cm”, which is the interval [10, 25), so <code>right = FALSE</code> is the setting that matches it, and it agrees with the <code>case_when()</code> version on every measured stem. The default puts 21 stems into the class below, and they are precisely the 21 stems recorded at 10, 25 or 50 cm. That is 5.5 per cent of the measured stems. Diameters rounded to whole centimetres make boundary values frequent: with every value an integer, each break is a value that real records take. How often a stem lands exactly on a break depends on the recording resolution, and for the simulated stand it can be worked out:</p>
<div class="cell">
<div class="code-copy-outer-scaffold"><div class="sourceCode cell-code" id="cb33" style="background: #f1f3f5;"><pre class="sourceCode r code-with-copy"><code class="sourceCode r"><span id="cb33-1">breaks_on_draw <span class="ot" style="color: #003B4F;
background-color: null;
font-style: inherit;">&lt;-</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">c</span>(<span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">10</span>, <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">25</span>, <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">50</span>) <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">-</span> <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">5</span>   <span class="co" style="color: #5E5E5E;
background-color: null;
font-style: inherit;"># the breaks on the scale of the gamma draw</span></span>
<span id="cb33-2">share_on_break <span class="ot" style="color: #003B4F;
background-color: null;
font-style: inherit;">&lt;-</span> <span class="cf" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">function</span>(step) {    <span class="co" style="color: #5E5E5E;
background-color: null;
font-style: inherit;"># step: recording resolution in cm</span></span>
<span id="cb33-3">  <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">sum</span>(<span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">pgamma</span>(breaks_on_draw <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">+</span> step <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">/</span> <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">2</span>, <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">2</span>, <span class="fl" style="color: #AD0000;
background-color: null;
font-style: inherit;">0.1</span>) <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">-</span></span>
<span id="cb33-4">      <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">pgamma</span>(breaks_on_draw <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">-</span> step <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">/</span> <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">2</span>, <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">2</span>, <span class="fl" style="color: #AD0000;
background-color: null;
font-style: inherit;">0.1</span>))</span>
<span id="cb33-5">}</span>
<span id="cb33-6">on_break <span class="ot" style="color: #003B4F;
background-color: null;
font-style: inherit;">&lt;-</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">c</span>(<span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">whole_cm =</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">share_on_break</span>(<span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">1</span>), <span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">tenth_cm =</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">share_on_break</span>(<span class="fl" style="color: #AD0000;
background-color: null;
font-style: inherit;">0.1</span>))</span>
<span id="cb33-7">on_break</span></code></pre></div></div>
<div class="cell-output cell-output-stdout">
<pre><code>   whole_cm    tenth_cm 
0.062355875 0.006239227 </code></pre>
</div>
</div>
<p>Recorded to the whole centimetre, 6.2 per cent of the stems are expected on a break; recorded to 0.1 cm, 0.62 per cent, a tenth as many. How many stems this affects depends on how coarsely the sheet records diameter; which way the boundary stems go does not.</p>
<p><code>cut()</code> also leaves one end of the breaks open, and a value equal to that break becomes <code>NA</code>: with the default <code>right = TRUE</code> it is the lowest break, with <code>right = FALSE</code> the highest. With breaks from 0 to <code>Inf</code> and diameters of 5 cm and more, neither can happen here. For cover classes from 0 to 100 per cent, the default loses every bare quadrat and <code>right = FALSE</code> loses every quadrat at full cover. <code>include.lowest = TRUE</code> closes the open end in both cases (the name says “lowest”, but with <code>right = FALSE</code> it closes the highest break):</p>
<div class="cell">
<div class="code-copy-outer-scaffold"><div class="sourceCode cell-code" id="cb35" style="background: #f1f3f5;"><pre class="sourceCode r code-with-copy"><code class="sourceCode r"><span id="cb35-1">cover_breaks <span class="ot" style="color: #003B4F;
background-color: null;
font-style: inherit;">&lt;-</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">c</span>(<span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">0</span>, <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">5</span>, <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">25</span>, <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">50</span>, <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">75</span>, <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">100</span>)</span>
<span id="cb35-2"><span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">stopifnot</span>(<span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">is.na</span>(<span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">cut</span>(<span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">0</span>, cover_breaks)),</span>
<span id="cb35-3">          <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">is.na</span>(<span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">cut</span>(<span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">100</span>, cover_breaks, <span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">right =</span> <span class="cn" style="color: #8f5902;
background-color: null;
font-style: inherit;">FALSE</span>)),</span>
<span id="cb35-4">          <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">!</span><span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">is.na</span>(<span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">cut</span>(<span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">0</span>, cover_breaks, <span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">include.lowest =</span> <span class="cn" style="color: #8f5902;
background-color: null;
font-style: inherit;">TRUE</span>)),</span>
<span id="cb35-5">          <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">!</span><span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">is.na</span>(<span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">cut</span>(<span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">100</span>, cover_breaks, <span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">right =</span> <span class="cn" style="color: #8f5902;
background-color: null;
font-style: inherit;">FALSE</span>, <span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">include.lowest =</span> <span class="cn" style="color: #8f5902;
background-color: null;
font-style: inherit;">TRUE</span>)))</span></code></pre></div></div>
</div>
<p>Missing values stay missing in <code>cut()</code>, which is the behaviour you want:</p>
<div class="cell">
<div class="code-copy-outer-scaffold"><div class="sourceCode cell-code" id="cb36" style="background: #f1f3f5;"><pre class="sourceCode r code-with-copy"><code class="sourceCode r"><span id="cb36-1"><span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">stopifnot</span>(<span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">is.na</span>(<span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">cut</span>(<span class="cn" style="color: #8f5902;
background-color: null;
font-style: inherit;">NA_real_</span>, breaks)))</span></code></pre></div></div>
</div>
</section>
<section id="what-to-check-in-your-own-data" class="level2">
<h2 id="what-to-check-in-your-own-data-h" class="anchored" data-anchor-id="what-to-check-in-your-own-data">What to check in your own data</h2>
<p>The one check that would have caught every class mistake above is a grouped summary of the raw measurement inside each new class. A class that holds values outside its own range has been filled from the wrong line.</p>
<div class="cell">
<div class="code-copy-outer-scaffold"><div class="sourceCode cell-code" id="cb37" style="background: #f1f3f5;"><pre class="sourceCode r code-with-copy"><code class="sourceCode r"><span id="cb37-1">stems <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">|&gt;</span></span>
<span id="cb37-2">  <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">group_by</span>(class_lowest_first) <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">|&gt;</span></span>
<span id="cb37-3">  <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">summarise</span>(<span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">n =</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">n</span>(), <span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">smallest =</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">min</span>(dbh), <span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">largest =</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">max</span>(dbh))</span></code></pre></div></div>
<div class="cell-output cell-output-stdout">
<pre><code># A tibble: 3 × 4
  class_lowest_first     n smallest largest
  &lt;chr&gt;              &lt;int&gt;    &lt;dbl&gt;   &lt;dbl&gt;
1 pole                 351       10      84
2 sapling               29        6       9
3 &lt;NA&gt;                  20       NA      NA</code></pre>
</div>
<div class="code-copy-outer-scaffold"><div class="sourceCode cell-code" id="cb39" style="background: #f1f3f5;"><pre class="sourceCode r code-with-copy"><code class="sourceCode r"><span id="cb39-1">stems <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">|&gt;</span></span>
<span id="cb39-2">  <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">group_by</span>(class_catch_all) <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">|&gt;</span></span>
<span id="cb39-3">  <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">summarise</span>(<span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">n =</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">n</span>(), <span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">smallest =</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">min</span>(dbh), <span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">largest =</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">max</span>(dbh))</span></code></pre></div></div>
<div class="cell-output cell-output-stdout">
<pre><code># A tibble: 4 × 4
  class_catch_all     n smallest largest
  &lt;chr&gt;           &lt;int&gt;    &lt;dbl&gt;   &lt;dbl&gt;
1 large              23       50      84
2 mature            137       25      49
3 pole              191       10      24
4 sapling            49       NA      NA</code></pre>
</div>
<div class="code-copy-outer-scaffold"><div class="sourceCode cell-code" id="cb41" style="background: #f1f3f5;"><pre class="sourceCode r code-with-copy"><code class="sourceCode r"><span id="cb41-1">stems <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">|&gt;</span></span>
<span id="cb41-2">  <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">group_by</span>(cut_right) <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">|&gt;</span></span>
<span id="cb41-3">  <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">summarise</span>(<span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">n =</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">n</span>(), <span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">smallest =</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">min</span>(dbh), <span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">largest =</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">max</span>(dbh))</span></code></pre></div></div>
<div class="cell-output cell-output-stdout">
<pre><code># A tibble: 5 × 4
  cut_right     n smallest largest
  &lt;fct&gt;     &lt;int&gt;    &lt;dbl&gt;   &lt;dbl&gt;
1 sapling      38        6      10
2 pole        190       11      25
3 mature      133       26      50
4 large        19       52      84
5 &lt;NA&gt;         20       NA      NA</code></pre>
</div>
<div class="code-copy-outer-scaffold"><div class="sourceCode cell-code" id="cb43" style="background: #f1f3f5;"><pre class="sourceCode r code-with-copy"><code class="sourceCode r"><span id="cb43-1">protocol_ok <span class="ot" style="color: #003B4F;
background-color: null;
font-style: inherit;">&lt;-</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">with</span>(stems, <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">all</span>(</span>
<span id="cb43-2">  (size_class <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">==</span> <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"sapling"</span> <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">&amp;</span> dbh <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">&lt;</span> <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">10</span>) <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">|</span></span>
<span id="cb43-3">  (size_class <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">==</span> <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"pole"</span>    <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">&amp;</span> dbh <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">&gt;=</span> <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">10</span> <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">&amp;</span> dbh <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">&lt;</span> <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">25</span>) <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">|</span></span>
<span id="cb43-4">  (size_class <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">==</span> <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"mature"</span>  <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">&amp;</span> dbh <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">&gt;=</span> <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">25</span> <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">&amp;</span> dbh <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">&lt;</span> <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">50</span>) <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">|</span></span>
<span id="cb43-5">  (size_class <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">==</span> <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"large"</span>   <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">&amp;</span> dbh <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">&gt;=</span> <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">50</span>), <span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">na.rm =</span> <span class="cn" style="color: #8f5902;
background-color: null;
font-style: inherit;">TRUE</span>))</span>
<span id="cb43-6"><span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">stopifnot</span>(protocol_ok, <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">sum</span>(<span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">is.na</span>(stems<span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">$</span>size_class)) <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">==</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">sum</span>(<span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">is.na</span>(stems<span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">$</span>dbh)))</span>
<span id="cb43-7">pole_max <span class="ot" style="color: #003B4F;
background-color: null;
font-style: inherit;">&lt;-</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">max</span>(stems<span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">$</span>dbh[stems<span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">$</span>class_lowest_first <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">==</span> <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"pole"</span>], <span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">na.rm =</span> <span class="cn" style="color: #8f5902;
background-color: null;
font-style: inherit;">TRUE</span>)</span>
<span id="cb43-8">sapling_max_cut <span class="ot" style="color: #003B4F;
background-color: null;
font-style: inherit;">&lt;-</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">max</span>(stems<span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">$</span>dbh[stems<span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">$</span>cut_right <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">==</span> <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"sapling"</span>], <span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">na.rm =</span> <span class="cn" style="color: #8f5902;
background-color: null;
font-style: inherit;">TRUE</span>)</span></code></pre></div></div>
</div>
<p>Each table shows its own mistake. With the lowest threshold first, the pole class runs up to 84 cm. With the catch-all, the sapling row has <code>NA</code> as its smallest and largest value: <code>min()</code> and <code>max()</code> return <code>NA</code> when any value in the group is missing, and a class of measured stems should have none. With the default <code>cut()</code>, the sapling class reaches 10 cm, which the protocol calls a pole. For <code>size_class</code> every stem sits inside its protocol limits and the missing values line up with the missing diameters, which is what the final <code>stopifnot()</code> checks. The grouping itself is covered in <a href="https://tidyecology.com/posts/grouped-summaries-in-r/">Summarising ecological data by group</a>.</p>
<p>Beyond that, four things are quick to check on any recode. Count the missing values before and after: <code>sum(is.na(dbh))</code> should equal the number of stems whose class is <code>NA</code> (or “not measured”), and if it is smaller, a catch-all has absorbed some. Put a value that sits exactly on each boundary through the code and read which class it lands in; with whole-number measurements, some real records sit there. Run <code>class()</code> on the result when the input was a date or a factor. And if your conditions overlap, read them in order as the function does, from the top, and ask of a big value which line it meets first.</p>
<p>None of these checks can tell you whether the protocol’s boundaries are sensible for the question; that is an ecological decision, and <a href="https://tidyecology.com/posts/size-class-boundaries-in-a-matrix-model/">Size-class boundaries in a matrix population model</a> shows how much it can change a result. The checks only tell you that the code does what the protocol says. The chapter on logical vectors in Wickham, Cetinkaya-Rundel and Grolemund (2023) covers <code>if_else()</code> and <code>case_when()</code> with more examples, and the reference pages for <a href="https://dplyr.tidyverse.org/reference/case_when.html">case_when()</a> and <a href="https://dplyr.tidyverse.org/reference/if_else.html">if_else()</a> are the place to confirm the rules for the version you have installed.</p>
</section>
<section id="references" class="level2">
<h2 id="references-h" class="anchored" data-anchor-id="references">References</h2>
<ul>
<li>Wickham H, Cetinkaya-Rundel M, Grolemund G 2023 R for Data Science, 2nd edn. O’Reilly (ISBN 978-1-492-09740-2; free online at https://r4ds.hadley.nz)</li>
<li>Wickham H, Francois R, Henry L, Muller K, Vaughan D 2023 dplyr: A Grammar of Data Manipulation. R package (written with version 1.1.4; https://dplyr.tidyverse.org)</li>
</ul>
</section>
<section id="related-tutorials" class="level2">
<h2 id="related-tutorials-h" class="anchored" data-anchor-id="related-tutorials">Related tutorials</h2>
<ul>
<li><a href="https://tidyecology.com/posts/cleaning-species-names/">Cleaning species names before you count</a></li>
<li><a href="https://tidyecology.com/posts/reading-field-data-into-r/">Reading field data into R</a></li>
<li><a href="https://tidyecology.com/posts/grouped-summaries-in-r/">Summarising ecological data by group</a></li>
<li><a href="https://tidyecology.com/posts/size-class-boundaries-in-a-matrix-model/">Size-class boundaries in a matrix population model</a></li>
</ul>
<details class="te-repro" data-pagefind-ignore="">
<summary>Reproducibility</summary>
<ul>
<li>Code last run: 2026-09-30</li>
<li>R version 4.5.3 (2026-03-11), aarch64-apple-darwin20</li>
<li>Packages: dplyr 1.2.1, ggplot2 4.0.3</li>
</ul>
</details>


<!-- -->

</section>

 ]]></description>
  <category>R</category>
  <category>dplyr</category>
  <category>data wrangling</category>
  <category>data cleaning</category>
  <category>missing data</category>
  <category>ecology tutorial</category>
  <guid isPermaLink="false">https://tidyecology.com/posts/recoding-with-case-when/</guid>
  <pubDate>Sun, 27 Sep 2026 07:00:00 GMT</pubDate>
  <media:content url="https://tidyecology.com/posts/recoding-with-case-when/thumbnail.png" medium="image" type="image/png" height="104" width="144"/>
</item>
<item>
  <title>Factor levels in R: reference groups and empty sites</title>
  <dc:creator>Tidy Ecology</dc:creator>
  <link>https://tidyecology.com/posts/factor-levels-in-r/</link>
  <description><![CDATA[ 





<p>A fire experiment: quadrats that were left alone, quadrats that were burnt, quadrats that were mown, and the dry biomass cut from each at the end of the season. You fit <code>lm(biomass ~ treatment)</code>, open the coefficient table, and there is a row for <code>treatmentcontrol</code> but no row for burnt. Nothing failed. R has made a choice about your treatment column, and the table is an answer to a question you did not ask.</p>
<p>A factor is R’s way of storing a grouping column: a set of labels plus a list of the allowed values, the levels, in a fixed order. That list decides three things that show up in ecological results. Its first entry is the group every model coefficient is measured against. Its members are the groups that a count or a summary is allowed to report, including groups with nothing in them. And any value that is not on the list stops being a value at all. Each of the three main sections below runs one of these on a small simulated data set, shows the number that comes out wrong without any warning, and then fixes it. Two further sections add the cases next to them: an empty cell in a crossed design, where R does warn but quietly, and a grouping column stored as numbers, which never becomes a factor at all.</p>
<p><strong>The short answer.</strong> Turn every grouping column into a factor yourself, with the levels written out from your study design rather than taken from the data. Put the group you want to compare against first. Include the sites that produced no records. Then check that no value dropped out on the way.</p>
<p>This post assumes you have met <code>group_by()</code> and <code>summarise()</code>, which <a href="https://tidyecology.com/posts/grouped-summaries-in-r/">Summarising ecological data by group</a> introduces. The data are simulated, and every seed is in the code.</p>
<div class="cell">
<div class="code-copy-outer-scaffold"><div class="sourceCode cell-code" id="cb1" style="background: #f1f3f5;"><pre class="sourceCode r code-with-copy"><code class="sourceCode r"><span id="cb1-1"><span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">library</span>(dplyr)</span>
<span id="cb1-2"><span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">library</span>(ggplot2)</span>
<span id="cb1-3"><span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">options</span>(<span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">scipen =</span> <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">6</span>)   <span class="co" style="color: #5E5E5E;
background-color: null;
font-style: inherit;"># print small p-values as decimals</span></span>
<span id="cb1-4"></span>
<span id="cb1-5">te_paper  <span class="ot" style="color: #003B4F;
background-color: null;
font-style: inherit;">&lt;-</span> <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"#f5f4ee"</span></span>
<span id="cb1-6">te_ink    <span class="ot" style="color: #003B4F;
background-color: null;
font-style: inherit;">&lt;-</span> <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"#16241d"</span></span>
<span id="cb1-7">te_body   <span class="ot" style="color: #003B4F;
background-color: null;
font-style: inherit;">&lt;-</span> <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"#2c3a31"</span></span>
<span id="cb1-8">te_forest <span class="ot" style="color: #003B4F;
background-color: null;
font-style: inherit;">&lt;-</span> <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"#275139"</span></span>
<span id="cb1-9">te_rust   <span class="ot" style="color: #003B4F;
background-color: null;
font-style: inherit;">&lt;-</span> <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"#b5534e"</span></span>
<span id="cb1-10">te_gold   <span class="ot" style="color: #003B4F;
background-color: null;
font-style: inherit;">&lt;-</span> <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"#c9b458"</span></span>
<span id="cb1-11">te_line   <span class="ot" style="color: #003B4F;
background-color: null;
font-style: inherit;">&lt;-</span> <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"#dad9ca"</span></span>
<span id="cb1-12"></span>
<span id="cb1-13">theme_datasheet <span class="ot" style="color: #003B4F;
background-color: null;
font-style: inherit;">&lt;-</span> <span class="cf" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">function</span>() {</span>
<span id="cb1-14">  <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">theme_minimal</span>(<span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">base_size =</span> <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">12</span>) <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">+</span></span>
<span id="cb1-15">    <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">theme</span>(<span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">plot.background  =</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">element_rect</span>(<span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">fill =</span> te_paper, <span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">colour =</span> <span class="cn" style="color: #8f5902;
background-color: null;
font-style: inherit;">NA</span>),</span>
<span id="cb1-16">          <span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">panel.background =</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">element_rect</span>(<span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">fill =</span> te_paper, <span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">colour =</span> <span class="cn" style="color: #8f5902;
background-color: null;
font-style: inherit;">NA</span>),</span>
<span id="cb1-17">          <span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">panel.grid.major =</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">element_line</span>(<span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">colour =</span> te_line, <span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">linewidth =</span> <span class="fl" style="color: #AD0000;
background-color: null;
font-style: inherit;">0.3</span>),</span>
<span id="cb1-18">          <span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">panel.grid.minor =</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">element_blank</span>(),</span>
<span id="cb1-19">          <span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">text             =</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">element_text</span>(<span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">colour =</span> te_body),</span>
<span id="cb1-20">          <span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">axis.text        =</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">element_text</span>(<span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">colour =</span> te_body),</span>
<span id="cb1-21">          <span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">strip.text       =</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">element_text</span>(<span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">colour =</span> te_ink, <span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">face =</span> <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"bold"</span>))</span>
<span id="cb1-22">}</span></code></pre></div></div>
</div>
<section id="the-first-level-is-the-reference-group" class="level2">
<h2 id="the-first-level-is-the-reference-group-h" class="anchored" data-anchor-id="the-first-level-is-the-reference-group">The first level is the reference group</h2>
<p>Eight quadrats per treatment, with true mean biomass fixed in the code at 120 g for control, 90 g for burnt and 95 g for mown: mowing is built to remove almost as much as fire does. The treatment column is plain text, which is what <code>read.csv()</code> and <code>data.frame()</code> give you: since R 4.0.0 neither turns text into factors unless you ask.</p>
<div class="cell">
<div class="code-copy-outer-scaffold"><div class="sourceCode cell-code" id="cb2" style="background: #f1f3f5;"><pre class="sourceCode r code-with-copy"><code class="sourceCode r"><span id="cb2-1"><span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">set.seed</span>(<span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">1012</span>)</span>
<span id="cb2-2">treat_means <span class="ot" style="color: #003B4F;
background-color: null;
font-style: inherit;">&lt;-</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">c</span>(<span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">control =</span> <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">120</span>, <span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">burnt =</span> <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">90</span>, <span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">mown =</span> <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">95</span>)    <span class="co" style="color: #5E5E5E;
background-color: null;
font-style: inherit;"># true means, g per quadrat</span></span>
<span id="cb2-3">n_per <span class="ot" style="color: #003B4F;
background-color: null;
font-style: inherit;">&lt;-</span> <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">8</span></span>
<span id="cb2-4"></span>
<span id="cb2-5">plots <span class="ot" style="color: #003B4F;
background-color: null;
font-style: inherit;">&lt;-</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">data.frame</span>(<span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">treatment =</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">rep</span>(<span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">names</span>(treat_means), <span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">each =</span> n_per))</span>
<span id="cb2-6">plots<span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">$</span>biomass <span class="ot" style="color: #003B4F;
background-color: null;
font-style: inherit;">&lt;-</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">round</span>(<span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">rnorm</span>(<span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">nrow</span>(plots), <span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">mean =</span> treat_means[plots<span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">$</span>treatment], <span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">sd =</span> <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">15</span>), <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">1</span>)</span>
<span id="cb2-7"></span>
<span id="cb2-8"><span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">stopifnot</span>(<span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">is.character</span>(plots<span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">$</span>treatment),</span>
<span id="cb2-9">          <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">is.character</span>(<span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">read.csv</span>(<span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">text =</span> <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"treatment</span><span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">\n</span><span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">burnt"</span>)<span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">$</span>treatment))</span>
<span id="cb2-10"><span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">head</span>(plots, <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">3</span>)</span></code></pre></div></div>
<div class="cell-output cell-output-stdout">
<pre><code>  treatment biomass
1   control   107.9
2   control   117.5
3   control   111.5</code></pre>
</div>
</div>
<p><code>lm()</code> needs groups, so it converts the text column to a factor on the way in. <code>factor()</code> sorts the distinct values to make the levels, the first sorted level becomes the reference, and “burnt” comes before “control” in the alphabet.</p>
<div class="cell">
<div class="code-copy-outer-scaffold"><div class="sourceCode cell-code" id="cb4" style="background: #f1f3f5;"><pre class="sourceCode r code-with-copy"><code class="sourceCode r"><span id="cb4-1"><span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">stopifnot</span>(<span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">identical</span>(<span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">levels</span>(<span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">factor</span>(plots<span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">$</span>treatment)), <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">c</span>(<span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"burnt"</span>, <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"control"</span>, <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"mown"</span>)))</span>
<span id="cb4-2"></span>
<span id="cb4-3">fit_default <span class="ot" style="color: #003B4F;
background-color: null;
font-style: inherit;">&lt;-</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">lm</span>(biomass <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">~</span> treatment, <span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">data =</span> plots)</span>
<span id="cb4-4">cf_def <span class="ot" style="color: #003B4F;
background-color: null;
font-style: inherit;">&lt;-</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">coef</span>(<span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">summary</span>(fit_default))</span>
<span id="cb4-5"><span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">round</span>(cf_def, <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">4</span>)</span></code></pre></div></div>
<div class="cell-output cell-output-stdout">
<pre><code>                 Estimate Std. Error t value Pr(&gt;|t|)
(Intercept)       88.9500     5.1737 17.1927   0.0000
treatmentcontrol  37.8000     7.3167  5.1662   0.0000
treatmentmown     -4.4875     7.3167 -0.6133   0.5463</code></pre>
</div>
</div>
<p>Read the table the way the model means it. The intercept, 89.0 g, is the mean of the burnt quadrats. <code>treatmentcontrol</code> is control minus burnt, +37.8 g. And <code>treatmentmown</code> is mown minus burnt: -4.5 g with a p-value of 0.55. Read as “the effect of mowing”, that row says mowing did very little. It says nothing of the sort. It compares two disturbance treatments with each other, and the comparison the experiment was built for, mown against untouched, is not in the table at all.</p>
<p>The fix is one line. Make the column a factor and name the reference, either with <code>relevel()</code> or by writing out all the levels in the order you want (useful later for plots and tables):</p>
<div class="cell">
<div class="code-copy-outer-scaffold"><div class="sourceCode cell-code" id="cb6" style="background: #f1f3f5;"><pre class="sourceCode r code-with-copy"><code class="sourceCode r"><span id="cb6-1">plots<span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">$</span>treatment <span class="ot" style="color: #003B4F;
background-color: null;
font-style: inherit;">&lt;-</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">relevel</span>(<span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">factor</span>(plots<span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">$</span>treatment), <span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">ref =</span> <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"control"</span>)</span>
<span id="cb6-2"><span class="co" style="color: #5E5E5E;
background-color: null;
font-style: inherit;"># same result: factor(plots$treatment, levels = c("control", "burnt", "mown"))</span></span>
<span id="cb6-3"><span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">levels</span>(plots<span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">$</span>treatment)</span></code></pre></div></div>
<div class="cell-output cell-output-stdout">
<pre><code>[1] "control" "burnt"   "mown"   </code></pre>
</div>
<div class="code-copy-outer-scaffold"><div class="sourceCode cell-code" id="cb8" style="background: #f1f3f5;"><pre class="sourceCode r code-with-copy"><code class="sourceCode r"><span id="cb8-1">fit_control <span class="ot" style="color: #003B4F;
background-color: null;
font-style: inherit;">&lt;-</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">lm</span>(biomass <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">~</span> treatment, <span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">data =</span> plots)</span>
<span id="cb8-2"><span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">round</span>(<span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">coef</span>(<span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">summary</span>(fit_control)), <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">4</span>)</span></code></pre></div></div>
<div class="cell-output cell-output-stdout">
<pre><code>               Estimate Std. Error t value Pr(&gt;|t|)
(Intercept)    126.7500     5.1737 24.4988        0
treatmentburnt -37.8000     7.3167 -5.1662        0
treatmentmown  -42.2875     7.3167 -5.7796        0</code></pre>
</div>
</div>
<p>Now the intercept is the control mean, 126.8 g, and each row is a treatment against it: burnt -37.8 g, mown -42.3 g with a p-value below 0.0001. The same word, mown, sat on a row with a small estimate and a large p-value a moment ago, and now sits on a row with a large negative estimate. <code>relevel()</code> only works on a factor; on a text column it stops with an error, which is why the <code>factor()</code> call comes first.</p>
<p>Nothing about the model itself has changed. The coefficients are differences between the same three group means, taken from a different starting group. (How a factor becomes an intercept plus differences is in <a href="https://tidyecology.com/posts/linear-models-t-test-anova/">t-tests and ANOVA as linear models in R</a>.)</p>
<div class="cell">
<div class="code-copy-outer-scaffold"><div class="sourceCode cell-code" id="cb10" style="background: #f1f3f5;"><pre class="sourceCode r code-with-copy"><code class="sourceCode r"><span id="cb10-1"><span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">all.equal</span>(<span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">fitted</span>(fit_default), <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">fitted</span>(fit_control))</span></code></pre></div></div>
<div class="cell-output cell-output-stdout">
<pre><code>[1] TRUE</code></pre>
</div>
<div class="code-copy-outer-scaffold"><div class="sourceCode cell-code" id="cb12" style="background: #f1f3f5;"><pre class="sourceCode r code-with-copy"><code class="sourceCode r"><span id="cb12-1">max_fit_diff <span class="ot" style="color: #003B4F;
background-color: null;
font-style: inherit;">&lt;-</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">max</span>(<span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">abs</span>(<span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">fitted</span>(fit_default) <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">-</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">fitted</span>(fit_control)))</span>
<span id="cb12-2"><span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">round</span>(<span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">c</span>(<span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">logLik_default =</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">as.numeric</span>(<span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">logLik</span>(fit_default)),</span>
<span id="cb12-3">        <span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">logLik_control =</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">as.numeric</span>(<span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">logLik</span>(fit_control)),</span>
<span id="cb12-4">        <span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">r2_default =</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">summary</span>(fit_default)<span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">$</span>r.squared,</span>
<span id="cb12-5">        <span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">r2_control =</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">summary</span>(fit_control)<span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">$</span>r.squared), <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">4</span>)</span></code></pre></div></div>
<div class="cell-output cell-output-stdout">
<pre><code>logLik_default logLik_control     r2_default     r2_control 
      -96.8517       -96.8517         0.6575         0.6575 </code></pre>
</div>
<div class="code-copy-outer-scaffold"><div class="sourceCode cell-code" id="cb14" style="background: #f1f3f5;"><pre class="sourceCode r code-with-copy"><code class="sourceCode r"><span id="cb14-1">grp_mean <span class="ot" style="color: #003B4F;
background-color: null;
font-style: inherit;">&lt;-</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">tapply</span>(plots<span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">$</span>biomass, plots<span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">$</span>treatment, mean)</span>
<span id="cb14-2"><span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">round</span>(grp_mean, <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">2</span>)</span></code></pre></div></div>
<div class="cell-output cell-output-stdout">
<pre><code>control   burnt    mown 
 126.75   88.95   84.46 </code></pre>
</div>
</div>
<p>The fitted values of the two models agree to within floating-point rounding. The log-likelihood is -96.8517 both times and R-squared is 0.6575 both times. The reference level changes what each coefficient means; it does not change the fit, the predictions or any test of the treatment as a whole (the next section shows one exception for the predictions: an empty cell in a crossed design). That is why the mistake is easy to miss: every diagnostic you run on the model looks the same. <a href="https://tidyecology.com/posts/contrasts-and-post-hoc/">Contrasts and post-hoc comparisons in R</a> goes on to other codings (sum-to-zero, planned contrasts) and to comparing every pair.</p>
<div class="cell">
<div class="cell-output-display">
<div id="fig-reference" class="quarto-float quarto-figure quarto-figure-center anchored" alt="Two panels of quadrat biomass. Each shows the eight quadrats per treatment as pale green points, a dark green diamond at each treatment mean, a dashed horizontal line at the reference mean and vertical rust arrows labelled with the coefficient. Left panel, reference burnt near 89 g: arrows of plus 37.8 to control and minus 4.5 to mown. Right panel, reference control near 127 g: arrows of minus 37.8 to burnt and minus 42.3 to mown.">
<figure class="quarto-float quarto-float-fig figure">
<div aria-describedby="fig-reference-caption-0ceaefa1-69ba-4598-a22c-09a6ac19f8ca">
<img src="https://tidyecology.com/posts/factor-levels-in-r/index_files/figure-html/fig-reference-1.png" class="img-fluid figure-img" alt="Two panels of quadrat biomass. Each shows the eight quadrats per treatment as pale green points, a dark green diamond at each treatment mean, a dashed horizontal line at the reference mean and vertical rust arrows labelled with the coefficient. Left panel, reference burnt near 89 g: arrows of plus 37.8 to control and minus 4.5 to mown. Right panel, reference control near 127 g: arrows of minus 37.8 to burnt and minus 42.3 to mown." width="720">
</div>
<figcaption class="quarto-float-caption-bottom quarto-float-caption quarto-float-fig" id="fig-reference-caption-0ceaefa1-69ba-4598-a22c-09a6ac19f8ca">
Figure&nbsp;1: The same biomass data, the same three group means and the same fitted model, read against two reference levels. The dashed line is the intercept and each arrow is one coefficient, drawn from the reference mean to the group mean. With burnt as the reference, the mown arrow is short; with control as the reference it is long and points down.
</figcaption>
</figure>
</div>
</div>
</div>
<p>The same levels set the order of groups in plots and tables: alphabetical unless you say otherwise. To sort groups by a statistic instead, for bars in order of their mean, <code>reorder()</code> builds the level order from the data:</p>
<div class="cell">
<div class="code-copy-outer-scaffold"><div class="sourceCode cell-code" id="cb16" style="background: #f1f3f5;"><pre class="sourceCode r code-with-copy"><code class="sourceCode r"><span id="cb16-1"><span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">levels</span>(<span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">reorder</span>(plots<span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">$</span>treatment, plots<span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">$</span>biomass, <span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">FUN =</span> mean))</span></code></pre></div></div>
<div class="cell-output cell-output-stdout">
<pre><code>[1] "mown"    "burnt"   "control"</code></pre>
</div>
</div>
</section>
<section id="unless-a-cell-of-the-design-is-empty" class="level2">
<h2 id="unless-a-cell-of-the-design-is-empty-h" class="anchored" data-anchor-id="unless-a-cell-of-the-design-is-empty">Unless a cell of the design is empty</h2>
<p>The reference level did not change any prediction above because every treatment had quadrats in it, so every prediction was the mean of quadrats that were cut. With two grouping columns crossed, that can fail. A second survey cuts biomass in three habitats in three seasons, four quadrats for each habitat and season, except that the wetland was under water in spring and its quadrats were never cut. The true means are fixed in the code, with a wetland that is poor in spring and peaks in autumn.</p>
<div class="cell">
<div class="code-copy-outer-scaffold"><div class="sourceCode cell-code" id="cb18" style="background: #f1f3f5;"><pre class="sourceCode r code-with-copy"><code class="sourceCode r"><span id="cb18-1"><span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">set.seed</span>(<span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">1015</span>)</span>
<span id="cb18-2">cell_mean <span class="ot" style="color: #003B4F;
background-color: null;
font-style: inherit;">&lt;-</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">rbind</span>(<span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">forest    =</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">c</span>(<span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">spring =</span> <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">60</span>, <span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">summer =</span>  <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">80</span>, <span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">autumn =</span>  <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">70</span>),   <span class="co" style="color: #5E5E5E;
background-color: null;
font-style: inherit;"># true means, g</span></span>
<span id="cb18-3">                   <span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">grassland =</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">c</span>(<span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">spring =</span> <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">90</span>, <span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">summer =</span> <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">140</span>, <span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">autumn =</span> <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">100</span>),</span>
<span id="cb18-4">                   <span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">wetland   =</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">c</span>(<span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">spring =</span> <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">70</span>, <span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">summer =</span> <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">130</span>, <span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">autumn =</span> <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">150</span>))</span>
<span id="cb18-5">survey <span class="ot" style="color: #003B4F;
background-color: null;
font-style: inherit;">&lt;-</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">expand.grid</span>(<span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">quadrat =</span> <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">1</span><span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">:</span><span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">4</span>, <span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">season =</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">colnames</span>(cell_mean),</span>
<span id="cb18-6">                      <span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">habitat =</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">rownames</span>(cell_mean), <span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">stringsAsFactors =</span> <span class="cn" style="color: #8f5902;
background-color: null;
font-style: inherit;">FALSE</span>)</span>
<span id="cb18-7">survey <span class="ot" style="color: #003B4F;
background-color: null;
font-style: inherit;">&lt;-</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">subset</span>(survey, <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">!</span>(habitat <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">==</span> <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"wetland"</span> <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">&amp;</span> season <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">==</span> <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"spring"</span>))   <span class="co" style="color: #5E5E5E;
background-color: null;
font-style: inherit;"># flooded, never cut</span></span>
<span id="cb18-8">survey<span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">$</span>biomass <span class="ot" style="color: #003B4F;
background-color: null;
font-style: inherit;">&lt;-</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">round</span>(<span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">rnorm</span>(<span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">nrow</span>(survey), cell_mean[<span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">cbind</span>(survey<span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">$</span>habitat, survey<span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">$</span>season)],</span>
<span id="cb18-9">                              <span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">sd =</span> <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">15</span>), <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">1</span>)</span>
<span id="cb18-10"><span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">table</span>(survey<span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">$</span>habitat, survey<span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">$</span>season)</span></code></pre></div></div>
<div class="cell-output cell-output-stdout">
<pre><code>           
            autumn spring summer
  forest         4      4      4
  grassland      4      4      4
  wetland        4      0      4</code></pre>
</div>
</div>
<p>The model <code>biomass ~ habitat * season</code> asks for a separate mean in every habitat and season, the interaction. Fit it twice: once with the text columns as they are, so forest and autumn are the references because they come first in the alphabet, and once with grassland and summer set as the references by hand. Then ask both fits for the cell that was never cut.</p>
<div class="cell">
<div class="code-copy-outer-scaffold"><div class="sourceCode cell-code" id="cb20" style="background: #f1f3f5;"><pre class="sourceCode r code-with-copy"><code class="sourceCode r"><span id="cb20-1">fit_alpha <span class="ot" style="color: #003B4F;
background-color: null;
font-style: inherit;">&lt;-</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">lm</span>(biomass <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">~</span> habitat <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">*</span> season, <span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">data =</span> survey)</span>
<span id="cb20-2"></span>
<span id="cb20-3">survey_hand <span class="ot" style="color: #003B4F;
background-color: null;
font-style: inherit;">&lt;-</span> survey</span>
<span id="cb20-4">survey_hand<span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">$</span>habitat <span class="ot" style="color: #003B4F;
background-color: null;
font-style: inherit;">&lt;-</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">factor</span>(survey<span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">$</span>habitat, <span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">levels =</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">c</span>(<span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"grassland"</span>, <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"forest"</span>, <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"wetland"</span>))</span>
<span id="cb20-5">survey_hand<span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">$</span>season  <span class="ot" style="color: #003B4F;
background-color: null;
font-style: inherit;">&lt;-</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">factor</span>(survey<span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">$</span>season, <span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">levels =</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">c</span>(<span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"summer"</span>, <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"spring"</span>, <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"autumn"</span>))</span>
<span id="cb20-6">fit_hand <span class="ot" style="color: #003B4F;
background-color: null;
font-style: inherit;">&lt;-</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">lm</span>(biomass <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">~</span> habitat <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">*</span> season, <span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">data =</span> survey_hand)</span>
<span id="cb20-7"></span>
<span id="cb20-8">wet_spring <span class="ot" style="color: #003B4F;
background-color: null;
font-style: inherit;">&lt;-</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">data.frame</span>(<span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">habitat =</span> <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"wetland"</span>, <span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">season =</span> <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"spring"</span>)</span>
<span id="cb20-9">pred_alpha <span class="ot" style="color: #003B4F;
background-color: null;
font-style: inherit;">&lt;-</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">suppressWarnings</span>(<span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">predict</span>(fit_alpha, wet_spring))   <span class="co" style="color: #5E5E5E;
background-color: null;
font-style: inherit;"># the warning is shown below</span></span>
<span id="cb20-10">pred_hand  <span class="ot" style="color: #003B4F;
background-color: null;
font-style: inherit;">&lt;-</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">suppressWarnings</span>(<span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">predict</span>(fit_hand, wet_spring))</span>
<span id="cb20-11"><span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">round</span>(<span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">c</span>(<span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">forest_autumn_first =</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">as.numeric</span>(pred_alpha),</span>
<span id="cb20-12">        <span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">grassland_summer_first =</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">as.numeric</span>(pred_hand)), <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">2</span>)</span></code></pre></div></div>
<div class="cell-output cell-output-stdout">
<pre><code>   forest_autumn_first grassland_summer_first 
                132.85                  64.15 </code></pre>
</div>
</div>
<p>Both fits give the same fitted value for every quadrat that was cut, and they still predict 132.85 g and 64.15 g for wetland in spring, a cell built at 70 g. Neither number comes from a wetland quadrat in spring, because there are none. Each is put together from three cells that were cut: the wetland mean in the reference season, plus the reference habitat in spring, minus the reference habitat in the reference season. For the alphabetical fit that is wetland in autumn plus forest in spring minus forest in autumn:</p>
<div class="cell">
<div class="code-copy-outer-scaffold"><div class="sourceCode cell-code" id="cb22" style="background: #f1f3f5;"><pre class="sourceCode r code-with-copy"><code class="sourceCode r"><span id="cb22-1">cell_avg <span class="ot" style="color: #003B4F;
background-color: null;
font-style: inherit;">&lt;-</span> <span class="cf" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">function</span>(h, s) <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">mean</span>(survey<span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">$</span>biomass[survey<span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">$</span>habitat <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">==</span> h <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">&amp;</span> survey<span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">$</span>season <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">==</span> s])</span>
<span id="cb22-2">three_cells <span class="ot" style="color: #003B4F;
background-color: null;
font-style: inherit;">&lt;-</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">cell_avg</span>(<span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"wetland"</span>, <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"autumn"</span>) <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">+</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">cell_avg</span>(<span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"forest"</span>, <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"spring"</span>) <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">-</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">cell_avg</span>(<span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"forest"</span>, <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"autumn"</span>)</span>
<span id="cb22-3"><span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">round</span>(<span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">c</span>(<span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">three_cells =</span> three_cells, <span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">alphabetical_fit =</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">as.numeric</span>(pred_alpha)), <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">2</span>)</span></code></pre></div></div>
<div class="cell-output cell-output-stdout">
<pre><code>     three_cells alphabetical_fit 
          132.85           132.85 </code></pre>
</div>
</div>
<p>It is the prediction of the alphabetical fit. For the fit set by hand the three cells are wetland in summer plus grassland in spring minus grassland in summer. This is arithmetic, not something the simulation found, and it means the gap between the two predictions is set by how differently the habitats change between seasons, the very thing the interaction was meant to estimate.</p>
<p>R does flag the problem, in three places that are easy to scroll past:</p>
<div class="cell">
<div class="code-copy-outer-scaffold"><div class="sourceCode cell-code" id="cb24" style="background: #f1f3f5;"><pre class="sourceCode r code-with-copy"><code class="sourceCode r"><span id="cb24-1"><span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">coef</span>(fit_alpha)[<span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">is.na</span>(<span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">coef</span>(fit_alpha))]</span></code></pre></div></div>
<div class="cell-output cell-output-stdout">
<pre><code>habitatwetland:seasonspring 
                         NA </code></pre>
</div>
<div class="code-copy-outer-scaffold"><div class="sourceCode cell-code" id="cb26" style="background: #f1f3f5;"><pre class="sourceCode r code-with-copy"><code class="sourceCode r"><span id="cb26-1"><span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">grep</span>(<span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"singularities"</span>, <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">capture.output</span>(<span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">summary</span>(fit_alpha)), <span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">value =</span> <span class="cn" style="color: #8f5902;
background-color: null;
font-style: inherit;">TRUE</span>)</span></code></pre></div></div>
<div class="cell-output cell-output-stdout">
<pre><code>[1] "Coefficients: (1 not defined because of singularities)"</code></pre>
</div>
<div class="code-copy-outer-scaffold"><div class="sourceCode cell-code" id="cb28" style="background: #f1f3f5;"><pre class="sourceCode r code-with-copy"><code class="sourceCode r"><span id="cb28-1"><span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">tryCatch</span>(<span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">predict</span>(fit_alpha, wet_spring), <span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">warning =</span> conditionMessage)</span></code></pre></div></div>
<div class="cell-output cell-output-stdout">
<pre><code>[1] "prediction from rank-deficient fit; attr(*, \"non-estim\") has doubtful cases"</code></pre>
</div>
</div>
<p>An <code>NA</code> coefficient means R dropped a column it could not estimate. <a href="https://tidyecology.com/posts/fitting-a-senescence-model/">Fitting a senescence model to individual records</a> meets one of the same kind, where age is tied to female and season, and the slope R does report is what one arbitrary constraint happens to produce. Since R 4.3.0, <code>predict()</code> on an <code>lm()</code> fit takes <code>rankdeficient = "NA"</code> and returns <code>NA</code> for such a row instead of a number, which is the honest answer here: wetland in spring was not measured.</p>
<p>If a number is needed anyway, fit <code>biomass ~ habitat + season</code> without the interaction. It predicts 104.9 g whatever the reference levels, against the 70 g the cell was built at, because it assumes the wetland differs from the other habitats by the same amount in every season. That is an assumption to state in the methods, and in this simulation it is false by construction. <a href="https://tidyecology.com/posts/poststratifying-unstructured-records/">Multilevel post-stratification of records</a> fills the empty cells of a survey frame with a main-effects model and with a multilevel model, and measures what each costs.</p>
</section>
<section id="sites-with-no-records-drop-out-of-a-count" class="level2">
<h2 id="sites-with-no-records-drop-out-of-a-count-h" class="anchored" data-anchor-id="sites-with-no-records-drop-out-of-a-count">Sites with no records drop out of a count</h2>
<p>A season of camera trapping for pine marten at twenty sites, stored the way detection data usually is: one row per detection. A site where the camera ran all season and saw nothing has no row. Each site’s expected number of detections is drawn at random, so some sites end up empty.</p>
<div class="cell">
<div class="code-copy-outer-scaffold"><div class="sourceCode cell-code" id="cb30" style="background: #f1f3f5;"><pre class="sourceCode r code-with-copy"><code class="sourceCode r"><span id="cb30-1"><span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">set.seed</span>(<span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">1013</span>)</span>
<span id="cb30-2">site_ids  <span class="ot" style="color: #003B4F;
background-color: null;
font-style: inherit;">&lt;-</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">sprintf</span>(<span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"S%02d"</span>, <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">1</span><span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">:</span><span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">20</span>)                 <span class="co" style="color: #5E5E5E;
background-color: null;
font-style: inherit;"># the survey design</span></span>
<span id="cb30-3">site_rate <span class="ot" style="color: #003B4F;
background-color: null;
font-style: inherit;">&lt;-</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">exp</span>(<span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">rnorm</span>(<span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">length</span>(site_ids), <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">log</span>(<span class="fl" style="color: #AD0000;
background-color: null;
font-style: inherit;">1.5</span>), <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">1</span>))</span>
<span id="cb30-4">n_det     <span class="ot" style="color: #003B4F;
background-color: null;
font-style: inherit;">&lt;-</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">rpois</span>(<span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">length</span>(site_ids), site_rate)</span>
<span id="cb30-5"></span>
<span id="cb30-6">records <span class="ot" style="color: #003B4F;
background-color: null;
font-style: inherit;">&lt;-</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">data.frame</span>(<span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">site =</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">rep</span>(site_ids, <span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">times =</span> n_det))</span>
<span id="cb30-7"><span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">c</span>(<span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">detections =</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">nrow</span>(records), <span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">sites_surveyed =</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">length</span>(site_ids),</span>
<span id="cb30-8">  <span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">sites_with_none =</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">sum</span>(n_det <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">==</span> <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">0</span>))</span></code></pre></div></div>
<div class="cell-output cell-output-stdout">
<pre><code>     detections  sites_surveyed sites_with_none 
             50              20               8 </code></pre>
</div>
</div>
<p>Count detections per site and summarise:</p>
<div class="cell">
<div class="code-copy-outer-scaffold"><div class="sourceCode cell-code" id="cb32" style="background: #f1f3f5;"><pre class="sourceCode r code-with-copy"><code class="sourceCode r"><span id="cb32-1">per_site_text <span class="ot" style="color: #003B4F;
background-color: null;
font-style: inherit;">&lt;-</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">count</span>(records, site)</span>
<span id="cb32-2"><span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">c</span>(<span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">sites_in_table =</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">nrow</span>(per_site_text),</span>
<span id="cb32-3">  <span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">mean_detections =</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">mean</span>(per_site_text<span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">$</span>n),</span>
<span id="cb32-4">  <span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">share_detected  =</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">mean</span>(per_site_text<span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">$</span>n <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">&gt;</span> <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">0</span>))</span></code></pre></div></div>
<div class="cell-output cell-output-stdout">
<pre><code> sites_in_table mean_detections  share_detected 
      12.000000        4.166667        1.000000 </code></pre>
</div>
</div>
<p>The table has 12 sites, not 20. The 8 sites with no detections are not in <code>records</code>, so no function working from <code>records</code> alone can know they exist. The mean comes out at 4.17 detections per site, and the share of sites where the marten was detected comes out at 1.00: every site in the table has at least one detection, because that is how a site gets into the table.</p>
<p>Turning the column into a factor does not help if the levels come from the same records, since <code>factor()</code> can only list the values it sees: <code>nlevels(factor(records$site))</code> is 12. The levels have to come from the design, the list of sites you actually surveyed. Even then, <code>count()</code> and <code>group_by()</code> drop empty levels by default, so the argument <code>.drop = FALSE</code> is the second half of the fix:</p>
<div class="cell">
<div class="code-copy-outer-scaffold"><div class="sourceCode cell-code" id="cb34" style="background: #f1f3f5;"><pre class="sourceCode r code-with-copy"><code class="sourceCode r"><span id="cb34-1">records<span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">$</span>site <span class="ot" style="color: #003B4F;
background-color: null;
font-style: inherit;">&lt;-</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">factor</span>(records<span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">$</span>site, <span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">levels =</span> site_ids)</span>
<span id="cb34-2"></span>
<span id="cb34-3">per_site_default <span class="ot" style="color: #003B4F;
background-color: null;
font-style: inherit;">&lt;-</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">count</span>(records, site)</span>
<span id="cb34-4">per_site_all     <span class="ot" style="color: #003B4F;
background-color: null;
font-style: inherit;">&lt;-</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">count</span>(records, site, <span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">.drop =</span> <span class="cn" style="color: #8f5902;
background-color: null;
font-style: inherit;">FALSE</span>)</span>
<span id="cb34-5"></span>
<span id="cb34-6"><span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">stopifnot</span>(<span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">nrow</span>(per_site_default) <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">==</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">sum</span>(n_det <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">&gt;</span> <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">0</span>),</span>
<span id="cb34-7">          <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">nrow</span>(per_site_all) <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">==</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">length</span>(site_ids),</span>
<span id="cb34-8">          <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">nrow</span>(<span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">count</span>(<span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">data.frame</span>(<span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">site =</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">as.character</span>(records<span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">$</span>site)), site,</span>
<span id="cb34-9">                     <span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">.drop =</span> <span class="cn" style="color: #8f5902;
background-color: null;
font-style: inherit;">FALSE</span>)) <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">==</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">sum</span>(n_det <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">&gt;</span> <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">0</span>))</span>
<span id="cb34-10"><span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">c</span>(<span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">default =</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">nrow</span>(per_site_default), <span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">drop_false =</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">nrow</span>(per_site_all))</span></code></pre></div></div>
<div class="cell-output cell-output-stdout">
<pre><code>   default drop_false 
        12         20 </code></pre>
</div>
</div>
<p>The last line of the <code>stopifnot()</code> is the other half of the rule: <code>.drop = FALSE</code> does nothing for a text column, because a text column has no list of levels to keep. You need both, a factor with the design’s levels and <code>.drop = FALSE</code>. Base R’s <code>table()</code> keeps empty levels without being asked, and <code>group_by()</code> takes the same argument:</p>
<div class="cell">
<div class="code-copy-outer-scaffold"><div class="sourceCode cell-code" id="cb36" style="background: #f1f3f5;"><pre class="sourceCode r code-with-copy"><code class="sourceCode r"><span id="cb36-1"><span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">sum</span>(<span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">table</span>(records<span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">$</span>site) <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">==</span> <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">0</span>)</span></code></pre></div></div>
<div class="cell-output cell-output-stdout">
<pre><code>[1] 8</code></pre>
</div>
<div class="code-copy-outer-scaffold"><div class="sourceCode cell-code" id="cb38" style="background: #f1f3f5;"><pre class="sourceCode r code-with-copy"><code class="sourceCode r"><span id="cb38-1">per_site <span class="ot" style="color: #003B4F;
background-color: null;
font-style: inherit;">&lt;-</span> records <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">|&gt;</span></span>
<span id="cb38-2">  <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">group_by</span>(site, <span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">.drop =</span> <span class="cn" style="color: #8f5902;
background-color: null;
font-style: inherit;">FALSE</span>) <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">|&gt;</span></span>
<span id="cb38-3">  <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">summarise</span>(<span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">detections =</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">n</span>(), <span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">.groups =</span> <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"drop"</span>)</span>
<span id="cb38-4"></span>
<span id="cb38-5"><span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">rbind</span>(<span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">zeros_dropped =</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">c</span>(<span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">sites =</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">nrow</span>(per_site_text), <span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">mean =</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">mean</span>(per_site_text<span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">$</span>n),</span>
<span id="cb38-6">                        <span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">detected =</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">mean</span>(per_site_text<span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">$</span>n <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">&gt;</span> <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">0</span>)),</span>
<span id="cb38-7">      <span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">zeros_kept    =</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">c</span>(<span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">sites =</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">nrow</span>(per_site), <span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">mean =</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">mean</span>(per_site<span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">$</span>detections),</span>
<span id="cb38-8">                        <span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">detected =</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">mean</span>(per_site<span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">$</span>detections <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">&gt;</span> <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">0</span>)))</span></code></pre></div></div>
<div class="cell-output cell-output-stdout">
<pre><code>              sites     mean detected
zeros_dropped    12 4.166667      1.0
zeros_kept       20 2.500000      0.6</code></pre>
</div>
</div>
<p>With the empty sites back, the mean is 2.50 detections per site and the share of sites with a detection is 0.60. Dropping the zeros inflated the mean by 67 per cent and turned a species detected at 12 of 20 sites into one detected at every site in the table. No simulation is needed for the first number: the same 50 detections are divided by 12 sites instead of 20, so the mean is always inflated by the number of surveyed sites over the number with a detection, minus one (here 20/12 - 1).</p>
<div class="cell">
<div class="cell-output-display">
<div id="fig-empty-sites" class="quarto-float quarto-figure quarto-figure-center anchored" alt="Bar chart of detections for sites S01 to S20. Twelve sites have green bars, the tallest at 14 detections for S05. Eight sites, S02, S07, S09, S12 and S17 to S20, have no bar and a red cross on the zero line. A dashed red horizontal line sits at 4.17 and a solid dark green line at 2.50.">
<figure class="quarto-float quarto-float-fig figure">
<div aria-describedby="fig-empty-sites-caption-0ceaefa1-69ba-4598-a22c-09a6ac19f8ca">
<img src="https://tidyecology.com/posts/factor-levels-in-r/index_files/figure-html/fig-empty-sites-1.png" class="img-fluid figure-img" alt="Bar chart of detections for sites S01 to S20. Twelve sites have green bars, the tallest at 14 detections for S05. Eight sites, S02, S07, S09, S12 and S17 to S20, have no bar and a red cross on the zero line. A dashed red horizontal line sits at 4.17 and a solid dark green line at 2.50." width="720">
</div>
<figcaption class="quarto-float-caption-bottom quarto-float-caption quarto-float-fig" id="fig-empty-sites-caption-0ceaefa1-69ba-4598-a22c-09a6ac19f8ca">
Figure&nbsp;2: Detections per site for the twenty simulated camera sites. Red crosses mark the sites with no detections, which have no rows in the detection table. The dashed line is the mean over the sites that count() returns by default; the solid line is the mean over all twenty sites.
</figcaption>
</figure>
</div>
</div>
</div>
<p>The same zeros can come back through a join instead, when the site list lives in its own table; <a href="https://tidyecology.com/posts/joining-ecological-tables/">Joining ecological tables without losing zeros</a> takes that route. Either way the site list has to exist somewhere, and it can be lost on the way through a file: <a href="https://tidyecology.com/posts/what-a-csv-loses/">What a CSV loses</a> shows an unsampled site disappearing from the level set when a factor is written to CSV and read back.</p>
</section>
<section id="levels-set-by-hand-turn-mismatches-into-na" class="level2">
<h2 id="levels-set-by-hand-turn-mismatches-into-na-h" class="anchored" data-anchor-id="levels-set-by-hand-turn-mismatches-into-na">Levels set by hand turn mismatches into NA</h2>
<p>Writing the levels out is the fix in both sections above, and it has a trap of its own. Here is a habitat column for 150 vegetation plots, typed by several people over a season. Most entries are clean, and a few carry a capital letter, a trailing space or a two-word spelling.</p>
<div class="cell">
<div class="code-copy-outer-scaffold"><div class="sourceCode cell-code" id="cb40" style="background: #f1f3f5;"><pre class="sourceCode r code-with-copy"><code class="sourceCode r"><span id="cb40-1"><span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">set.seed</span>(<span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">1014</span>)</span>
<span id="cb40-2">n_rec    <span class="ot" style="color: #003B4F;
background-color: null;
font-style: inherit;">&lt;-</span> <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">150</span></span>
<span id="cb40-3">true_hab <span class="ot" style="color: #003B4F;
background-color: null;
font-style: inherit;">&lt;-</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">sample</span>(<span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">c</span>(<span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"forest"</span>, <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"grassland"</span>, <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"wetland"</span>), n_rec, <span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">replace =</span> <span class="cn" style="color: #8f5902;
background-color: null;
font-style: inherit;">TRUE</span>,</span>
<span id="cb40-4">                   <span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">prob =</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">c</span>(<span class="fl" style="color: #AD0000;
background-color: null;
font-style: inherit;">0.5</span>, <span class="fl" style="color: #AD0000;
background-color: null;
font-style: inherit;">0.3</span>, <span class="fl" style="color: #AD0000;
background-color: null;
font-style: inherit;">0.2</span>))</span>
<span id="cb40-5">typed <span class="ot" style="color: #003B4F;
background-color: null;
font-style: inherit;">&lt;-</span> true_hab</span>
<span id="cb40-6">slip  <span class="ot" style="color: #003B4F;
background-color: null;
font-style: inherit;">&lt;-</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">runif</span>(n_rec) <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">&lt;</span> <span class="fl" style="color: #AD0000;
background-color: null;
font-style: inherit;">0.15</span>                         <span class="co" style="color: #5E5E5E;
background-color: null;
font-style: inherit;"># entries typed differently</span></span>
<span id="cb40-7">variants <span class="ot" style="color: #003B4F;
background-color: null;
font-style: inherit;">&lt;-</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">list</span>(<span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">forest =</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">c</span>(<span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"Forest"</span>, <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"forest "</span>), <span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">grassland =</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">c</span>(<span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"Grassland"</span>, <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"grassland "</span>),</span>
<span id="cb40-8">                 <span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">wetland =</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">c</span>(<span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"wet land"</span>, <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"Wetland"</span>))</span>
<span id="cb40-9">typed[slip] <span class="ot" style="color: #003B4F;
background-color: null;
font-style: inherit;">&lt;-</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">vapply</span>(true_hab[slip], <span class="cf" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">function</span>(h) <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">sample</span>(variants[[h]], <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">1</span>), <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">character</span>(<span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">1</span>))</span>
<span id="cb40-10"><span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">table</span>(typed)</span></code></pre></div></div>
<div class="cell-output cell-output-stdout">
<pre><code>typed
    forest     Forest    forest   grassland  Grassland grassland    wet land 
        62          4          7         38          3          6          1 
   wetland    Wetland 
        28          1 </code></pre>
</div>
</div>
<p>You want the habitats in a fixed order, so you write the levels out:</p>
<div class="cell">
<div class="code-copy-outer-scaffold"><div class="sourceCode cell-code" id="cb42" style="background: #f1f3f5;"><pre class="sourceCode r code-with-copy"><code class="sourceCode r"><span id="cb42-1">hab_levels <span class="ot" style="color: #003B4F;
background-color: null;
font-style: inherit;">&lt;-</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">c</span>(<span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"forest"</span>, <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"grassland"</span>, <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"wetland"</span>)</span>
<span id="cb42-2">habitat <span class="ot" style="color: #003B4F;
background-color: null;
font-style: inherit;">&lt;-</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">factor</span>(typed, <span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">levels =</span> hab_levels)</span>
<span id="cb42-3"><span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">c</span>(<span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">NA_in_typed =</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">sum</span>(<span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">is.na</span>(typed)), <span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">NA_in_factor =</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">sum</span>(<span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">is.na</span>(habitat)))</span></code></pre></div></div>
<div class="cell-output cell-output-stdout">
<pre><code> NA_in_typed NA_in_factor 
           0           22 </code></pre>
</div>
</div>
<div class="cell">
<details class="code-fold">
<summary>Helper code used by the chunks below</summary>
<div class="code-copy-outer-scaffold"><div class="sourceCode cell-code" id="cb44" style="background: #f1f3f5;"><pre class="sourceCode r code-with-copy"><code class="sourceCode r"><span id="cb44-1">hab_warning <span class="ot" style="color: #003B4F;
background-color: null;
font-style: inherit;">&lt;-</span> <span class="cn" style="color: #8f5902;
background-color: null;
font-style: inherit;">NULL</span></span>
<span id="cb44-2"><span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">invisible</span>(<span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">withCallingHandlers</span>(<span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">factor</span>(typed, <span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">levels =</span> hab_levels),</span>
<span id="cb44-3">                              <span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">warning =</span> <span class="cf" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">function</span>(w) hab_warning <span class="ot" style="color: #003B4F;
background-color: null;
font-style: inherit;">&lt;&lt;-</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">conditionMessage</span>(w)))</span>
<span id="cb44-4">share_true <span class="ot" style="color: #003B4F;
background-color: null;
font-style: inherit;">&lt;-</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">prop.table</span>(<span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">table</span>(true_hab))</span>
<span id="cb44-5">share_hand <span class="ot" style="color: #003B4F;
background-color: null;
font-style: inherit;">&lt;-</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">prop.table</span>(<span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">table</span>(habitat))</span>
<span id="cb44-6">lost <span class="ot" style="color: #003B4F;
background-color: null;
font-style: inherit;">&lt;-</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">table</span>(<span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">factor</span>(true_hab[<span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">is.na</span>(habitat)], <span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">levels =</span> hab_levels))</span>
<span id="cb44-7">kept <span class="ot" style="color: #003B4F;
background-color: null;
font-style: inherit;">&lt;-</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">table</span>(habitat)</span>
<span id="cb44-8">fair <span class="ot" style="color: #003B4F;
background-color: null;
font-style: inherit;">&lt;-</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">sum</span>(<span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">is.na</span>(habitat)) <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">*</span> share_true   <span class="co" style="color: #5E5E5E;
background-color: null;
font-style: inherit;"># losses in proportion to class size</span></span>
<span id="cb44-9"><span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">stopifnot</span>(<span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">is.null</span>(hab_warning), <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">sum</span>(<span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">table</span>(habitat)) <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">==</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">sum</span>(<span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">!</span><span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">is.na</span>(habitat)), <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">all</span>(kept <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">&lt;</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">table</span>(true_hab)),</span>
<span id="cb44-10">          lost[[<span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"wetland"</span>]] <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">&lt;</span> fair[[<span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"wetland"</span>]], lost[[<span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"grassland"</span>]] <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">&gt;</span> fair[[<span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"grassland"</span>]])</span></code></pre></div></div>
</details>
</div>
<p><code>factor()</code> matches each value against the levels exactly, character for character, and every value without a match becomes <code>NA</code>. It does this without a warning. 22 of the 150 plots, 15 per cent of the sheet, now have no habitat, although the column had no missing values a line earlier. The R documentation for <code>factor()</code> states this behaviour; it is not a bug, and nothing downstream will point back to it.</p>
<p>What it does to a class share depends on where the mismatches fall:</p>
<div class="cell">
<div class="code-copy-outer-scaffold"><div class="sourceCode cell-code" id="cb45" style="background: #f1f3f5;"><pre class="sourceCode r code-with-copy"><code class="sourceCode r"><span id="cb45-1"><span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">round</span>(<span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">cbind</span>(<span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">true =</span> share_true, <span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">after_levels =</span> share_hand,</span>
<span id="cb45-2">            <span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">plots_lost =</span> lost, <span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">plots_left =</span> kept), <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">3</span>)</span></code></pre></div></div>
<div class="cell-output cell-output-stdout">
<pre><code>           true after_levels plots_lost plots_left
forest    0.487        0.484         11         62
grassland 0.313        0.297          9         38
wetland   0.200        0.219          2         28</code></pre>
</div>
</div>
<p><code>table()</code> leaves <code>NA</code> out unless told otherwise, so every share is now a share of the 128 plots that survived. Wetland lost 2 of its 30 plots, fewer than its fair part of the 22 losses, so its share rose from 0.200 to 0.219 although no wetland plot was added. Grassland lost 9 of its 47, more than its fair part, and its share fell from 0.313 to 0.297. In this simulation every habitat is mistyped at the same rate, so the shares move only a little. When one habitat has a spelling of its own (one recorder who always writes “wet land”) the losses pile up in that class and its share drops with them. The counts are wrong regardless: here every habitat has fewer plots than were surveyed.</p>
<p>The fix is a check before and a check after. Before, ask which values have no level to go to; clean them; ask again:</p>
<div class="cell">
<div class="code-copy-outer-scaffold"><div class="sourceCode cell-code" id="cb47" style="background: #f1f3f5;"><pre class="sourceCode r code-with-copy"><code class="sourceCode r"><span id="cb47-1"><span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">setdiff</span>(<span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">unique</span>(typed), hab_levels)</span></code></pre></div></div>
<div class="cell-output cell-output-stdout">
<pre><code>[1] "grassland " "Forest"     "Grassland"  "forest "    "Wetland"   
[6] "wet land"  </code></pre>
</div>
<div class="code-copy-outer-scaffold"><div class="sourceCode cell-code" id="cb49" style="background: #f1f3f5;"><pre class="sourceCode r code-with-copy"><code class="sourceCode r"><span id="cb49-1">cleaned <span class="ot" style="color: #003B4F;
background-color: null;
font-style: inherit;">&lt;-</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">tolower</span>(<span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">trimws</span>(typed))</span>
<span id="cb49-2"><span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">setdiff</span>(<span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">unique</span>(cleaned), hab_levels)</span></code></pre></div></div>
<div class="cell-output cell-output-stdout">
<pre><code>[1] "wet land"</code></pre>
</div>
<div class="code-copy-outer-scaffold"><div class="sourceCode cell-code" id="cb51" style="background: #f1f3f5;"><pre class="sourceCode r code-with-copy"><code class="sourceCode r"><span id="cb51-1">cleaned[cleaned <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">==</span> <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"wet land"</span>] <span class="ot" style="color: #003B4F;
background-color: null;
font-style: inherit;">&lt;-</span> <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"wetland"</span></span>
<span id="cb51-2">habitat <span class="ot" style="color: #003B4F;
background-color: null;
font-style: inherit;">&lt;-</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">factor</span>(cleaned, <span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">levels =</span> hab_levels)</span>
<span id="cb51-3"><span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">stopifnot</span>(<span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">sum</span>(<span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">is.na</span>(habitat)) <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">==</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">sum</span>(<span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">is.na</span>(typed)))</span>
<span id="cb51-4"><span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">all</span>(<span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">table</span>(habitat) <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">==</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">table</span>(<span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">factor</span>(true_hab, <span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">levels =</span> hab_levels)))</span></code></pre></div></div>
<div class="cell-output cell-output-stdout">
<pre><code>[1] TRUE</code></pre>
</div>
</div>
<p><code>trimws()</code> and <code>tolower()</code> handle the spaces and capitals, and the two-word spelling needs a decision, written down in the code. <a href="https://tidyecology.com/posts/cleaning-species-names/">Cleaning species names before you count</a> does the same job for species names with a lookup table, which scales better than one line per variant. The lasting fix is on the sheet itself: Broman and Woo (2018) make one consistent code per category part of their first rule for spreadsheet data. The <code>stopifnot()</code> after the <code>factor()</code> call is the one to keep in every script: the number of missing values must not change when a column becomes a factor. The <code>forcats</code> package offers <code>fct()</code>, which stops with an error instead of creating <code>NA</code> (chapter 16 of R for Data Science shows the two side by side), if you prefer a loud failure.</p>
<p>One more factor trap is common enough to name: <code>as.numeric()</code> on a factor returns the level positions, not the values. <a href="https://tidyecology.com/posts/debugging-and-defensive-code/">Debugging and defensive R code</a> measures what that does to a regression on elevation.</p>
</section>
<section id="a-grouping-column-stored-as-numbers" class="level2">
<h2 id="a-grouping-column-stored-as-numbers-h" class="anchored" data-anchor-id="a-grouping-column-stored-as-numbers">A grouping column stored as numbers</h2>
<p>Field numbers, block numbers and site codes are often typed as 1, 2, 3. R reads such a column as numbers, and a model given numbers fits one straight line through them instead of a separate mean for each group. Say the fire experiment’s 24 quadrats sit in four fields, two quadrats of each treatment in each field, and the fields differ in productivity in an order that has nothing to do with their numbers.</p>
<div class="cell">
<div class="code-copy-outer-scaffold"><div class="sourceCode cell-code" id="cb53" style="background: #f1f3f5;"><pre class="sourceCode r code-with-copy"><code class="sourceCode r"><span id="cb53-1"><span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">set.seed</span>(<span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">1016</span>)</span>
<span id="cb53-2">field_effect <span class="ot" style="color: #003B4F;
background-color: null;
font-style: inherit;">&lt;-</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">c</span>(<span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">0</span>, <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">40</span>, <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">-</span><span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">30</span>, <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">20</span>)          <span class="co" style="color: #5E5E5E;
background-color: null;
font-style: inherit;"># g per quadrat, added in fields 1 to 4</span></span>
<span id="cb53-3">fields <span class="ot" style="color: #003B4F;
background-color: null;
font-style: inherit;">&lt;-</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">data.frame</span>(<span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">field =</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">rep</span>(<span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">1</span><span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">:</span><span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">4</span>, <span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">each =</span> <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">6</span>),</span>
<span id="cb53-4">                     <span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">treatment =</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">rep</span>(<span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">rep</span>(<span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">names</span>(treat_means), <span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">each =</span> <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">2</span>), <span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">times =</span> <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">4</span>))</span>
<span id="cb53-5">fields<span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">$</span>biomass <span class="ot" style="color: #003B4F;
background-color: null;
font-style: inherit;">&lt;-</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">round</span>(treat_means[fields<span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">$</span>treatment] <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">+</span> field_effect[fields<span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">$</span>field] <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">+</span></span>
<span id="cb53-6">                          <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">rnorm</span>(<span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">nrow</span>(fields), <span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">sd =</span> <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">15</span>), <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">1</span>)</span>
<span id="cb53-7"><span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">str</span>(fields)</span></code></pre></div></div>
<div class="cell-output cell-output-stdout">
<pre><code>'data.frame':   24 obs. of  3 variables:
 $ field    : int  1 1 1 1 1 1 2 2 2 2 ...
 $ treatment: chr  "control" "control" "burnt" "burnt" ...
 $ biomass  : num  131.7 140.6 109.5 92.2 67.6 ...</code></pre>
</div>
</div>
<p><code>str()</code> shows the problem before any model does: <code>field</code> is <code>int</code>. Fit the treatment test with the field column as it is, and again as a factor:</p>
<div class="cell">
<div class="code-copy-outer-scaffold"><div class="sourceCode cell-code" id="cb55" style="background: #f1f3f5;"><pre class="sourceCode r code-with-copy"><code class="sourceCode r"><span id="cb55-1"><span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">anova</span>(<span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">lm</span>(biomass <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">~</span> field <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">+</span> treatment, <span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">data =</span> fields))</span></code></pre></div></div>
<div class="cell-output cell-output-stdout">
<pre><code>Analysis of Variance Table

Response: biomass
          Df  Sum Sq Mean Sq F value Pr(&gt;F)  
field      1     6.4    6.44  0.0079 0.9299  
treatment  2  4672.3 2336.15  2.8749 0.0799 .
Residuals 20 16252.1  812.61                 
---
Signif. codes:  0 '***' 0.001 '**' 0.01 '*' 0.05 '.' 0.1 ' ' 1</code></pre>
</div>
<div class="code-copy-outer-scaffold"><div class="sourceCode cell-code" id="cb57" style="background: #f1f3f5;"><pre class="sourceCode r code-with-copy"><code class="sourceCode r"><span id="cb57-1"><span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">anova</span>(<span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">lm</span>(biomass <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">~</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">factor</span>(field) <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">+</span> treatment, <span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">data =</span> fields))</span></code></pre></div></div>
<div class="cell-output cell-output-stdout">
<pre><code>Analysis of Variance Table

Response: biomass
              Df  Sum Sq Mean Sq F value    Pr(&gt;F)    
factor(field)  3 10664.8  3554.9 11.4392 0.0001977 ***
treatment      2  4672.3  2336.2  7.5174 0.0042336 ** 
Residuals     18  5593.8   310.8                      
---
Signif. codes:  0 '***' 0.001 '**' 0.01 '*' 0.05 '.' 0.1 ' ' 1</code></pre>
</div>
</div>
<p>The <code>Df</code> column gives it away: <code>field</code> takes 1 degree of freedom, one slope, and <code>factor(field)</code> takes 3, one difference for each field after the first. A straight line through field effects of 0, 40, -30 and 20 g removes almost none of them (0.2 per cent of their spread), so they stay in the residuals and the treatment test weighs its effect against that extra noise. In this data set the treatment p-value is 0.080 with the numeric field and 0.0042 with the factor. One data set could be luck, so here is the same design drawn 1000 times: with the field effects as above, with the same four effects sorted so that they rise with the field number, and with the four effects put in a new random order for every data set:</p>
<div class="cell">
<div class="code-copy-outer-scaffold"><div class="sourceCode cell-code" id="cb59" style="background: #f1f3f5;"><pre class="sourceCode r code-with-copy"><code class="sourceCode r"><span id="cb59-1">p_treatment <span class="ot" style="color: #003B4F;
background-color: null;
font-style: inherit;">&lt;-</span> <span class="cf" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">function</span>(effects) {</span>
<span id="cb59-2">  y <span class="ot" style="color: #003B4F;
background-color: null;
font-style: inherit;">&lt;-</span> treat_means[fields<span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">$</span>treatment] <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">+</span> effects[fields<span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">$</span>field] <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">+</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">rnorm</span>(<span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">nrow</span>(fields), <span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">sd =</span> <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">15</span>)</span>
<span id="cb59-3">  <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">c</span>(<span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">numeric =</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">anova</span>(<span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">lm</span>(y <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">~</span> field <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">+</span> treatment, <span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">data =</span> fields))[<span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"treatment"</span>, <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"Pr(&gt;F)"</span>],</span>
<span id="cb59-4">    <span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">factor  =</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">anova</span>(<span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">lm</span>(y <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">~</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">factor</span>(field) <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">+</span> treatment, <span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">data =</span> fields))[<span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"treatment"</span>, <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"Pr(&gt;F)"</span>])</span>
<span id="cb59-5">}</span>
<span id="cb59-6">n_sim <span class="ot" style="color: #003B4F;
background-color: null;
font-style: inherit;">&lt;-</span> <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">1000</span></span>
<span id="cb59-7">power_mixed  <span class="ot" style="color: #003B4F;
background-color: null;
font-style: inherit;">&lt;-</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">rowMeans</span>(<span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">replicate</span>(n_sim, <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">p_treatment</span>(field_effect)) <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">&lt;</span> <span class="fl" style="color: #AD0000;
background-color: null;
font-style: inherit;">0.05</span>)</span>
<span id="cb59-8">power_sorted <span class="ot" style="color: #003B4F;
background-color: null;
font-style: inherit;">&lt;-</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">rowMeans</span>(<span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">replicate</span>(n_sim, <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">p_treatment</span>(<span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">sort</span>(field_effect))) <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">&lt;</span> <span class="fl" style="color: #AD0000;
background-color: null;
font-style: inherit;">0.05</span>)</span>
<span id="cb59-9">power_random <span class="ot" style="color: #003B4F;
background-color: null;
font-style: inherit;">&lt;-</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">rowMeans</span>(<span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">replicate</span>(n_sim, <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">p_treatment</span>(<span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">sample</span>(field_effect))) <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">&lt;</span> <span class="fl" style="color: #AD0000;
background-color: null;
font-style: inherit;">0.05</span>)</span>
<span id="cb59-10"><span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">rbind</span>(<span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">order_as_above =</span> power_mixed, <span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">order_sorted =</span> power_sorted, <span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">order_shuffled =</span> power_random)</span></code></pre></div></div>
<div class="cell-output cell-output-stdout">
<pre><code>               numeric factor
order_as_above   0.160  0.951
order_sorted     0.953  0.954
order_shuffled   0.391  0.958</code></pre>
</div>
</div>
<p>With the field effects as above, the treatment test found the effect (p below 0.05) in 0.951 of the data sets with <code>factor(field)</code> and in 0.160 with the numeric column. With the effects sorted, the straight line catches nearly all of them, and the factor and the numeric column find the effect in 0.954 and 0.953 of the data sets, the same within Monte Carlo error. The order used above is the worst of the 24 possible orders of these four effects (together with the same order reversed). With the order shuffled for every data set, the numeric column finds the effect in 0.391 of the data sets and the factor in 0.958. (Each share comes from 1000 data sets. Drawn again, a share would typically move by its Monte Carlo standard error, here at most 0.015.) So the damage comes from the order of the codes, and field numbers are labels: nothing makes them line up with productivity, so a numeric column loses power by an amount you cannot know in advance. The trap is for grouping columns in <code>lm()</code>, <code>aov()</code> and <code>glm()</code>. A random effect in lme4, <code>(1 | field)</code>, is safe, because lme4 turns the grouping column into a factor itself.</p>
</section>
<section id="what-to-check-in-your-own-data" class="level2">
<h2 id="what-to-check-in-your-own-data-h" class="anchored" data-anchor-id="what-to-check-in-your-own-data">What to check in your own data</h2>
<p>Look at <code>levels()</code> of every grouping column before a model sees it, and make sure the first level is the group you want to compare against. If a column is still text when it goes into <code>lm()</code> or <code>glm()</code>, the reference is whatever comes first in the alphabet.</p>
<p>Run <code>str()</code> on the data too. A grouping column listed as <code>int</code> or <code>num</code> (field, block or site numbers) goes into <code>lm()</code> as one slope, not as groups; <code>is.numeric()</code> on every grouping column should be <code>FALSE</code> by the time a model sees it.</p>
<p>Before fitting an interaction of two grouping columns, run <code>table()</code> on the pair; a 0 means a combination the model cannot estimate, and any prediction for it depends on the reference levels.</p>
<p>Write the level list from the design (the sites surveyed, the months sampled, the treatments applied), not from <code>unique()</code> on the records. A site with no records can only appear in a summary if something other than the records knows about it.</p>
<p>When you count or summarise by group, compare the number of rows in the result with the number of groups in the design. If they differ, add <code>.drop = FALSE</code> and check the grouping column is a factor. With <code>.drop = FALSE</code>, an empty group gets <code>n()</code> equal to zero, but <code>mean()</code> of a measurement in that group has nothing to average and returns <code>NaN</code>, so decide what an empty site should show before you plot it.</p>
<p>Every time you call <code>factor()</code> with <code>levels =</code>, run <code>setdiff(unique(x), levels)</code> first and compare the count of <code>NA</code> values before and after. A difference is a spelling you have not dealt with.</p>
</section>
<section id="honest-limits" class="level2">
<h2 id="honest-limits-h" class="anchored" data-anchor-id="honest-limits">Honest limits</h2>
<p>Alphabetical order depends on the locale when labels mix capitals and lower case: <code>factor(c("burnt", "Control"))</code> can put either first on different machines, which is one more reason to write the levels out. With two grouping factors, <code>.drop = FALSE</code> keeps every combination of their levels, including combinations the design never had, so check the row count against the design there too.</p>
</section>
<section id="references" class="level2">
<h2 id="references-h" class="anchored" data-anchor-id="references">References</h2>
<p>Broman KW, Woo KH 2018 The American Statistician 72(1):2-10 (<a href="https://doi.org/10.1080/00031305.2017.1375989">10.1080/00031305.2017.1375989</a>)</p>
<p>R Core Team 2024 R documentation: Factors (https://stat.ethz.ch/R-manual/R-devel/library/base/html/factor.html)</p>
<p>R Core Team 2024 R documentation: Reorder levels of factor, relevel (https://stat.ethz.ch/R-manual/R-devel/library/stats/html/relevel.html)</p>
<p>Wickham H, Francois R, Henry L, Muller K, Vaughan D 2023 dplyr documentation: Count the observations in each group (https://dplyr.tidyverse.org/reference/count.html)</p>
<p>Wickham H, Cetinkaya-Rundel M, Grolemund G 2023 R for Data Science, 2nd edition, chapter 16: Factors (https://r4ds.hadley.nz/factors.html)</p>
</section>
<section id="related-tutorials" class="level2">
<h2 id="related-tutorials-h" class="anchored" data-anchor-id="related-tutorials">Related tutorials</h2>
<ul>
<li><a href="https://tidyecology.com/posts/joining-ecological-tables/">Joining ecological tables without losing zeros</a></li>
<li><a href="https://tidyecology.com/posts/contrasts-and-post-hoc/">Contrasts and post-hoc tests</a></li>
<li><a href="https://tidyecology.com/posts/what-a-csv-loses/">What a CSV loses: archiving an R analysis</a></li>
<li><a href="https://tidyecology.com/posts/cleaning-species-names/">Cleaning species names before you count</a></li>
</ul>
<details class="te-repro" data-pagefind-ignore="">
<summary>Reproducibility</summary>
<ul>
<li>Code last run: 2026-09-30</li>
<li>R version 4.5.3 (2026-03-11), aarch64-apple-darwin20</li>
<li>Packages: dplyr 1.2.1, ggplot2 4.0.3</li>
</ul>
</details>


<!-- -->

</section>

 ]]></description>
  <category>R</category>
  <category>dplyr</category>
  <category>data wrangling</category>
  <category>data cleaning</category>
  <category>regression</category>
  <category>ecology tutorial</category>
  <guid isPermaLink="false">https://tidyecology.com/posts/factor-levels-in-r/</guid>
  <pubDate>Sun, 27 Sep 2026 06:00:00 GMT</pubDate>
  <media:content url="https://tidyecology.com/posts/factor-levels-in-r/thumbnail.png" medium="image" type="image/png" height="104" width="144"/>
</item>
<item>
  <title>Reading Excel field sheets into R</title>
  <dc:creator>Tidy Ecology</dc:creator>
  <link>https://tidyecology.com/posts/reading-excel-field-sheets-into-r/</link>
  <description><![CDATA[ 





<p><em>Corrected 7 October 2026: the simulated sheet was described as using the Sundays from October to the end of March; its weekly Sundays run from the start of October to late March and leave out the last Sunday of March.</em></p>
<p>A winter of wetland bird counts, typed by volunteers into one Excel workbook: a row for each species on each count, with the date, the species and the number of birds. By the end of March the sheet has 1500 rows. Two habits of the counters are in it. Faced with a big flock late in the season, some of them typed an estimate such as <code>c. 80</code> instead of a number. And where a count’s date was lost, somebody typed <code>not recorded</code> in the date column.</p>
<p><a href="https://tidyecology.com/posts/reading-field-data-into-r/">Reading field data into R</a> reads a CSV with <code>read.csv()</code>, which looks at every value in a column before it decides the column’s type, so one <code>n/a</code> turns the whole column into text and the first <code>sum()</code> fails. An <code>.xlsx</code> file read with the readxl package behaves differently. <code>read_excel()</code> decides each column’s type from the first 1000 rows only, and a text entry further down that is not a number does not change the type: it becomes <code>NA</code>, with a warning that is easy never to see. Dates have their own problem. Excel stores a date as a number of days, and when that number reaches R as text you need the right starting day to turn it back. <a href="https://tidyecology.com/posts/dates-and-times-in-ecological-data/">Dates and times in ecological data</a> parses dates written as text with a format string; the serial numbers here need an origin instead.</p>
<p><strong>The short answer.</strong> Tell <code>read_excel()</code> what each column is with <code>col_types</code>, and list your missing-value codes in <code>na</code>. Read a column that mixes numbers and notes as text, and turn it into numbers yourself, so that every entry that is not a plain number is counted rather than dropped. A date serial that arrives as text converts with <code>as.Date(as.numeric(x), origin = "1899-12-30")</code>, and a check on the weekday of your count dates catches an origin that is off by a day or two.</p>
<p>The workbook below is simulated and built in the code, and every seed is in the code.</p>
<div class="cell">
<div class="code-copy-outer-scaffold"><div class="sourceCode cell-code" id="cb1" style="background: #f1f3f5;"><pre class="sourceCode r code-with-copy"><code class="sourceCode r"><span id="cb1-1"><span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">library</span>(readxl)     <span class="co" style="color: #5E5E5E;
background-color: null;
font-style: inherit;"># reads .xlsx and .xls files</span></span>
<span id="cb1-2"><span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">library</span>(openxlsx)   <span class="co" style="color: #5E5E5E;
background-color: null;
font-style: inherit;"># used here only to build the example workbook</span></span>
<span id="cb1-3"><span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">library</span>(ggplot2)</span>
<span id="cb1-4"></span>
<span id="cb1-5">te_paper  <span class="ot" style="color: #003B4F;
background-color: null;
font-style: inherit;">&lt;-</span> <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"#f5f4ee"</span></span>
<span id="cb1-6">te_ink    <span class="ot" style="color: #003B4F;
background-color: null;
font-style: inherit;">&lt;-</span> <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"#16241d"</span></span>
<span id="cb1-7">te_body   <span class="ot" style="color: #003B4F;
background-color: null;
font-style: inherit;">&lt;-</span> <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"#2c3a31"</span></span>
<span id="cb1-8">te_forest <span class="ot" style="color: #003B4F;
background-color: null;
font-style: inherit;">&lt;-</span> <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"#275139"</span></span>
<span id="cb1-9">te_rust   <span class="ot" style="color: #003B4F;
background-color: null;
font-style: inherit;">&lt;-</span> <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"#b5534e"</span></span>
<span id="cb1-10">te_gold   <span class="ot" style="color: #003B4F;
background-color: null;
font-style: inherit;">&lt;-</span> <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"#c9b458"</span></span>
<span id="cb1-11">te_line   <span class="ot" style="color: #003B4F;
background-color: null;
font-style: inherit;">&lt;-</span> <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"#dad9ca"</span></span>
<span id="cb1-12"></span>
<span id="cb1-13">theme_datasheet <span class="ot" style="color: #003B4F;
background-color: null;
font-style: inherit;">&lt;-</span> <span class="cf" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">function</span>() {</span>
<span id="cb1-14">  <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">theme_minimal</span>(<span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">base_size =</span> <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">12</span>) <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">+</span></span>
<span id="cb1-15">    <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">theme</span>(<span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">plot.background  =</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">element_rect</span>(<span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">fill =</span> te_paper, <span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">colour =</span> <span class="cn" style="color: #8f5902;
background-color: null;
font-style: inherit;">NA</span>),</span>
<span id="cb1-16">          <span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">panel.background =</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">element_rect</span>(<span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">fill =</span> te_paper, <span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">colour =</span> <span class="cn" style="color: #8f5902;
background-color: null;
font-style: inherit;">NA</span>),</span>
<span id="cb1-17">          <span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">panel.grid.major =</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">element_line</span>(<span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">colour =</span> te_line, <span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">linewidth =</span> <span class="fl" style="color: #AD0000;
background-color: null;
font-style: inherit;">0.3</span>),</span>
<span id="cb1-18">          <span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">panel.grid.minor =</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">element_blank</span>(),</span>
<span id="cb1-19">          <span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">text             =</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">element_text</span>(<span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">colour =</span> te_body),</span>
<span id="cb1-20">          <span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">axis.text        =</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">element_text</span>(<span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">colour =</span> te_body),</span>
<span id="cb1-21">          <span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">strip.text       =</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">element_text</span>(<span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">colour =</span> te_ink, <span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">face =</span> <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"bold"</span>))</span>
<span id="cb1-22">}</span></code></pre></div></div>
</div>
<section id="a-workbook-to-read" class="level2">
<h2 id="a-workbook-to-read-h" class="anchored" data-anchor-id="a-workbook-to-read">A workbook to read</h2>
<p>The counts are made on Sundays, one of 26 consecutive Sundays from the start of October to late March for each row, and the rows are in date order, as a sheet typed up during the season would be. Counts start at 1, because a species with no birds gets no row.</p>
<div class="cell">
<div class="code-copy-outer-scaffold"><div class="sourceCode cell-code" id="cb2" style="background: #f1f3f5;"><pre class="sourceCode r code-with-copy"><code class="sourceCode r"><span id="cb2-1"><span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">set.seed</span>(<span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">2410</span>)</span>
<span id="cb2-2">n_rows <span class="ot" style="color: #003B4F;
background-color: null;
font-style: inherit;">&lt;-</span> <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">1500</span></span>
<span id="cb2-3">sundays <span class="ot" style="color: #003B4F;
background-color: null;
font-style: inherit;">&lt;-</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">seq</span>(<span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">as.Date</span>(<span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"2023-10-01"</span>), <span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">by =</span> <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"week"</span>, <span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">length.out =</span> <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">26</span>)</span>
<span id="cb2-4"><span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">stopifnot</span>(<span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">all</span>(<span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">as.POSIXlt</span>(sundays)<span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">$</span>wday <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">==</span> <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">0</span>))   <span class="co" style="color: #5E5E5E;
background-color: null;
font-style: inherit;"># 0 is Sunday</span></span>
<span id="cb2-5"></span>
<span id="cb2-6">visit_true <span class="ot" style="color: #003B4F;
background-color: null;
font-style: inherit;">&lt;-</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">sort</span>(<span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">sample</span>(sundays, n_rows, <span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">replace =</span> <span class="cn" style="color: #8f5902;
background-color: null;
font-style: inherit;">TRUE</span>))</span>
<span id="cb2-7">species    <span class="ot" style="color: #003B4F;
background-color: null;
font-style: inherit;">&lt;-</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">sample</span>(<span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">c</span>(<span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"teal"</span>, <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"wigeon"</span>, <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"mallard"</span>, <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"lapwing"</span>, <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"golden plover"</span>),</span>
<span id="cb2-8">                     n_rows, <span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">replace =</span> <span class="cn" style="color: #8f5902;
background-color: null;
font-style: inherit;">TRUE</span>)</span>
<span id="cb2-9">count_pool <span class="ot" style="color: #003B4F;
background-color: null;
font-style: inherit;">&lt;-</span> <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">1</span> <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">+</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">rnbinom</span>(n_rows, <span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">mu =</span> <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">19</span>, <span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">size =</span> <span class="fl" style="color: #AD0000;
background-color: null;
font-style: inherit;">1.5</span>)</span></code></pre></div></div>
</div>
<p>Sixty rows after row 1000 hold the text entries. The function below writes the sheet with openxlsx: the counts as numbers, then the chosen cells overwritten with text, then five dates overwritten with <code>not recorded</code>. Your own data would already be a file, <code>data/counts.xlsx</code>, and the first line of your script would be the <code>read_excel()</code> call in the next section.</p>
<div class="cell">
<div class="code-copy-outer-scaffold"><div class="sourceCode cell-code" id="cb3" style="background: #f1f3f5;"><pre class="sourceCode r code-with-copy"><code class="sourceCode r"><span id="cb3-1">n_text   <span class="ot" style="color: #003B4F;
background-color: null;
font-style: inherit;">&lt;-</span> <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">60</span></span>
<span id="cb3-2">text_row <span class="ot" style="color: #003B4F;
background-color: null;
font-style: inherit;">&lt;-</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">sort</span>(<span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">1000</span> <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">+</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">sample</span>(n_rows <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">-</span> <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">1000</span>, n_text))   <span class="co" style="color: #5E5E5E;
background-color: null;
font-style: inherit;"># data rows 1001 to 1500</span></span>
<span id="cb3-3">no_date  <span class="ot" style="color: #003B4F;
background-color: null;
font-style: inherit;">&lt;-</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">sort</span>(<span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">sample</span>(<span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">1000</span>, <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">5</span>))                         <span class="co" style="color: #5E5E5E;
background-color: null;
font-style: inherit;"># lost dates, all in the first 1000 rows</span></span>
<span id="cb3-4"></span>
<span id="cb3-5">build_sheet <span class="ot" style="color: #003B4F;
background-color: null;
font-style: inherit;">&lt;-</span> <span class="cf" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">function</span>(count, text_row, text_entry, file_name) {</span>
<span id="cb3-6">  wb <span class="ot" style="color: #003B4F;
background-color: null;
font-style: inherit;">&lt;-</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">createWorkbook</span>()</span>
<span id="cb3-7">  <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">addWorksheet</span>(wb, <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"counts"</span>)</span>
<span id="cb3-8">  <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">writeData</span>(wb, <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"counts"</span>, <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">data.frame</span>(<span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">visit =</span> visit_true, <span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">species =</span> species, <span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">count =</span> count))</span>
<span id="cb3-9">  <span class="cf" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">for</span> (k <span class="cf" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">in</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">seq_along</span>(text_row)) {       <span class="co" style="color: #5E5E5E;
background-color: null;
font-style: inherit;"># + 1 because row 1 of the sheet is the header</span></span>
<span id="cb3-10">    <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">writeData</span>(wb, <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"counts"</span>, text_entry[k], <span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">startCol =</span> <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">3</span>, <span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">startRow =</span> text_row[k] <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">+</span> <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">1</span>, <span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">colNames =</span> <span class="cn" style="color: #8f5902;
background-color: null;
font-style: inherit;">FALSE</span>)</span>
<span id="cb3-11">  }</span>
<span id="cb3-12">  <span class="cf" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">for</span> (k <span class="cf" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">in</span> no_date) {</span>
<span id="cb3-13">    <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">writeData</span>(wb, <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"counts"</span>, <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"not recorded"</span>, <span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">startCol =</span> <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">1</span>, <span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">startRow =</span> k <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">+</span> <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">1</span>, <span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">colNames =</span> <span class="cn" style="color: #8f5902;
background-color: null;
font-style: inherit;">FALSE</span>)</span>
<span id="cb3-14">  }</span>
<span id="cb3-15">  path <span class="ot" style="color: #003B4F;
background-color: null;
font-style: inherit;">&lt;-</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">file.path</span>(<span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">tempdir</span>(), file_name)</span>
<span id="cb3-16">  <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">saveWorkbook</span>(wb, path, <span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">overwrite =</span> <span class="cn" style="color: #8f5902;
background-color: null;
font-style: inherit;">TRUE</span>)</span>
<span id="cb3-17">  path</span>
<span id="cb3-18">}</span></code></pre></div></div>
</div>
<p>In the first sheet the estimates are the big flocks. The 60 largest counts go to the 60 text rows, and each is written the way a counter writes a flock that cannot be counted bird by bird: rounded to ten, with <code>c.</code> in front. <code>sheet_value</code> holds the number each counter meant.</p>
<div class="cell">
<div class="code-copy-outer-scaffold"><div class="sourceCode cell-code" id="cb4" style="background: #f1f3f5;"><pre class="sourceCode r code-with-copy"><code class="sourceCode r"><span id="cb4-1">big_first <span class="ot" style="color: #003B4F;
background-color: null;
font-style: inherit;">&lt;-</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">order</span>(count_pool, <span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">decreasing =</span> <span class="cn" style="color: #8f5902;
background-color: null;
font-style: inherit;">TRUE</span>)</span>
<span id="cb4-2">count_big <span class="ot" style="color: #003B4F;
background-color: null;
font-style: inherit;">&lt;-</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">integer</span>(n_rows)</span>
<span id="cb4-3">count_big[text_row]  <span class="ot" style="color: #003B4F;
background-color: null;
font-style: inherit;">&lt;-</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">sample</span>(count_pool[big_first[<span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">1</span><span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">:</span>n_text]])       <span class="co" style="color: #5E5E5E;
background-color: null;
font-style: inherit;"># sample() shuffles</span></span>
<span id="cb4-4">count_big[<span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">-</span>text_row] <span class="ot" style="color: #003B4F;
background-color: null;
font-style: inherit;">&lt;-</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">sample</span>(count_pool[big_first[<span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">-</span>(<span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">1</span><span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">:</span>n_text)]])</span>
<span id="cb4-5">flock_value <span class="ot" style="color: #003B4F;
background-color: null;
font-style: inherit;">&lt;-</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">pmax</span>(<span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">10</span>, <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">round</span>(count_big[text_row], <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">-</span><span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">1</span>))</span>
<span id="cb4-6"></span>
<span id="cb4-7">sheet_value <span class="ot" style="color: #003B4F;
background-color: null;
font-style: inherit;">&lt;-</span> count_big</span>
<span id="cb4-8">sheet_value[text_row] <span class="ot" style="color: #003B4F;
background-color: null;
font-style: inherit;">&lt;-</span> flock_value</span>
<span id="cb4-9">path_flocks <span class="ot" style="color: #003B4F;
background-color: null;
font-style: inherit;">&lt;-</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">build_sheet</span>(count_big, text_row, <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">paste</span>(<span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"c."</span>, flock_value), <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"counts.xlsx"</span>)</span>
<span id="cb4-10"><span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">head</span>(<span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">paste</span>(<span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"c."</span>, flock_value))</span></code></pre></div></div>
<div class="cell-output cell-output-stdout">
<pre><code>[1] "c. 100" "c. 70"  "c. 70"  "c. 60"  "c. 60"  "c. 60" </code></pre>
</div>
</div>
<p>The estimates run from c.&nbsp;50 to c.&nbsp;120, and every plain count left on the sheet is at most 54.</p>
</section>
<section id="read_excel-guesses-from-the-first-1000-rows" class="level2">
<h2 id="read_excel-guesses-from-the-first-1000-rows-h" class="anchored" data-anchor-id="read_excel-guesses-from-the-first-1000-rows">read_excel() guesses from the first 1000 rows</h2>
<p>A plain call, as the first line of a script would make it. The warnings are collected into a vector here so that the page stays readable. At the console R reports warnings once the call returns, but more than ten arrive as a single line telling you to run <code>warnings()</code>, which then lists only the first 50. A rendered report with warnings turned off shows none of them.</p>
<div class="cell">
<div class="code-copy-outer-scaffold"><div class="sourceCode cell-code" id="cb6" style="background: #f1f3f5;"><pre class="sourceCode r code-with-copy"><code class="sourceCode r"><span id="cb6-1">read_quietly <span class="ot" style="color: #003B4F;
background-color: null;
font-style: inherit;">&lt;-</span> <span class="cf" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">function</span>(...) {</span>
<span id="cb6-2">  caught <span class="ot" style="color: #003B4F;
background-color: null;
font-style: inherit;">&lt;-</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">character</span>(<span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">0</span>)</span>
<span id="cb6-3">  out <span class="ot" style="color: #003B4F;
background-color: null;
font-style: inherit;">&lt;-</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">withCallingHandlers</span>(<span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">read_excel</span>(...), <span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">warning =</span> <span class="cf" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">function</span>(w) {</span>
<span id="cb6-4">    caught <span class="ot" style="color: #003B4F;
background-color: null;
font-style: inherit;">&lt;&lt;-</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">c</span>(caught, <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">conditionMessage</span>(w))</span>
<span id="cb6-5">    <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">invokeRestart</span>(<span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"muffleWarning"</span>)</span>
<span id="cb6-6">  })</span>
<span id="cb6-7">  <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">list</span>(<span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">data =</span> out, <span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">warnings =</span> caught)</span>
<span id="cb6-8">}</span>
<span id="cb6-9"></span>
<span id="cb6-10">default_read <span class="ot" style="color: #003B4F;
background-color: null;
font-style: inherit;">&lt;-</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">read_quietly</span>(path_flocks)</span>
<span id="cb6-11">counts <span class="ot" style="color: #003B4F;
background-color: null;
font-style: inherit;">&lt;-</span> default_read<span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">$</span>data</span>
<span id="cb6-12"><span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">str</span>(counts)</span></code></pre></div></div>
<div class="cell-output cell-output-stdout">
<pre><code>tibble [1,500 × 3] (S3: tbl_df/tbl/data.frame)
 $ visit  : chr [1:1500] "45200" "45200" "45200" "45200" ...
 $ species: chr [1:1500] "teal" "lapwing" "golden plover" "teal" ...
 $ count  : num [1:1500] 25 4 15 16 13 4 26 11 12 6 ...</code></pre>
</div>
<div class="code-copy-outer-scaffold"><div class="sourceCode cell-code" id="cb8" style="background: #f1f3f5;"><pre class="sourceCode r code-with-copy"><code class="sourceCode r"><span id="cb8-1"><span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">length</span>(default_read<span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">$</span>warnings)</span></code></pre></div></div>
<div class="cell-output cell-output-stdout">
<pre><code>[1] 60</code></pre>
</div>
<div class="code-copy-outer-scaffold"><div class="sourceCode cell-code" id="cb10" style="background: #f1f3f5;"><pre class="sourceCode r code-with-copy"><code class="sourceCode r"><span id="cb10-1"><span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">head</span>(default_read<span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">$</span>warnings, <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">2</span>)</span></code></pre></div></div>
<div class="cell-output cell-output-stdout">
<pre><code>[1] "Expecting numeric in C1002 / R1002C3: got 'c. 100'"
[2] "Expecting numeric in C1003 / R1003C3: got 'c. 70'" </code></pre>
</div>
<div class="code-copy-outer-scaffold"><div class="sourceCode cell-code" id="cb12" style="background: #f1f3f5;"><pre class="sourceCode r code-with-copy"><code class="sourceCode r"><span id="cb12-1"><span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">stopifnot</span>(<span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">packageVersion</span>(<span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"readxl"</span>) <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">&gt;=</span> <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"1.4.0"</span>,</span>
<span id="cb12-2">          <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">identical</span>(<span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">formals</span>(read_excel)<span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">$</span>guess_max, <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">quote</span>(<span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">min</span>(<span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">1000</span>, n_max))),</span>
<span id="cb12-3">          <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">identical</span>(<span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">formals</span>(read_excel)<span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">$</span>n_max, <span class="cn" style="color: #8f5902;
background-color: null;
font-style: inherit;">Inf</span>),</span>
<span id="cb12-4">          <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">is.numeric</span>(counts<span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">$</span>count), <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">sum</span>(<span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">is.na</span>(counts<span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">$</span>count)) <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">==</span> n_text,</span>
<span id="cb12-5">          <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">length</span>(default_read<span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">$</span>warnings) <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">==</span> n_text,</span>
<span id="cb12-6">          <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">all</span>(<span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">is.na</span>(counts<span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">$</span>count[text_row])), <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">!</span><span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">anyNA</span>(counts<span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">$</span>count[<span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">-</span>text_row]),</span>
<span id="cb12-7">          <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">getOption</span>(<span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"nwarnings"</span>) <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">==</span> <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">50</span>)   <span class="co" style="color: #5E5E5E;
background-color: null;
font-style: inherit;"># warnings() keeps at most 50</span></span></code></pre></div></div>
</div>
<p>The count column came back as numbers, and 60 of its 1500 values are <code>NA</code>: exactly the 60 cells that held an estimate. readxl reads the first <code>guess_max</code> rows to decide a column’s type, and the default is <code>min(1000, n_max)</code>, so 1000 rows for a whole sheet (this is readxl 1.5.0.1 here, and the source of readxl 1.5.0 has the same default). The readxl article on cell and column types (Wickham and Bryan 2026) describes the rest of the rule: a column with text among its guessed rows becomes text, the type of last resort. All 1000 of those rows held plain numbers, so the column became numeric. Each later cell that could not be a number was set to <code>NA</code>, and each one produced a warning naming the cell, 60 warnings in all.</p>
<div class="cell">
<div class="code-copy-outer-scaffold"><div class="sourceCode cell-code" id="cb13" style="background: #f1f3f5;"><pre class="sourceCode r code-with-copy"><code class="sourceCode r"><span id="cb13-1">plot_rows <span class="ot" style="color: #003B4F;
background-color: null;
font-style: inherit;">&lt;-</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">data.frame</span>(<span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">row =</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">seq_len</span>(n_rows), <span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">value =</span> sheet_value,</span>
<span id="cb13-2">                        <span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">status =</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">ifelse</span>(<span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">is.na</span>(counts<span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">$</span>count), <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"typed as text: read as NA"</span>, <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"number: read"</span>))</span>
<span id="cb13-3"></span>
<span id="cb13-4"><span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">ggplot</span>(plot_rows, <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">aes</span>(row, value)) <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">+</span></span>
<span id="cb13-5">  <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">annotate</span>(<span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"rect"</span>, <span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">xmin =</span> <span class="fl" style="color: #AD0000;
background-color: null;
font-style: inherit;">0.5</span>, <span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">xmax =</span> <span class="fl" style="color: #AD0000;
background-color: null;
font-style: inherit;">1000.5</span>, <span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">ymin =</span> <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">1</span>, <span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">ymax =</span> <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">400</span>, <span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">fill =</span> te_line, <span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">alpha =</span> <span class="fl" style="color: #AD0000;
background-color: null;
font-style: inherit;">0.6</span>) <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">+</span></span>
<span id="cb13-6">  <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">annotate</span>(<span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"text"</span>, <span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">x =</span> <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">500</span>, <span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">y =</span> <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">330</span>, <span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">label =</span> <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"guess window: rows 1 to 1000"</span>,</span>
<span id="cb13-7">           <span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">colour =</span> te_ink, <span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">size =</span> <span class="fl" style="color: #AD0000;
background-color: null;
font-style: inherit;">3.8</span>) <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">+</span></span>
<span id="cb13-8">  <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">geom_point</span>(<span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">aes</span>(<span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">colour =</span> status, <span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">size =</span> status), <span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">alpha =</span> <span class="fl" style="color: #AD0000;
background-color: null;
font-style: inherit;">0.75</span>) <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">+</span></span>
<span id="cb13-9">  <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">scale_colour_manual</span>(<span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">values =</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">c</span>(<span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"number: read"</span> <span class="ot" style="color: #003B4F;
background-color: null;
font-style: inherit;">=</span> te_forest, <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"typed as text: read as NA"</span> <span class="ot" style="color: #003B4F;
background-color: null;
font-style: inherit;">=</span> te_rust)) <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">+</span></span>
<span id="cb13-10">  <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">scale_size_manual</span>(<span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">values =</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">c</span>(<span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"number: read"</span> <span class="ot" style="color: #003B4F;
background-color: null;
font-style: inherit;">=</span> <span class="fl" style="color: #AD0000;
background-color: null;
font-style: inherit;">0.9</span>, <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"typed as text: read as NA"</span> <span class="ot" style="color: #003B4F;
background-color: null;
font-style: inherit;">=</span> <span class="fl" style="color: #AD0000;
background-color: null;
font-style: inherit;">1.9</span>)) <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">+</span></span>
<span id="cb13-11">  <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">scale_y_log10</span>(<span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">limits =</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">c</span>(<span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">1</span>, <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">400</span>)) <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">+</span></span>
<span id="cb13-12">  <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">labs</span>(<span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">x =</span> <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"row of the sheet"</span>, <span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">y =</span> <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"birds counted (log scale)"</span>, <span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">colour =</span> <span class="cn" style="color: #8f5902;
background-color: null;
font-style: inherit;">NULL</span>, <span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">size =</span> <span class="cn" style="color: #8f5902;
background-color: null;
font-style: inherit;">NULL</span>) <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">+</span></span>
<span id="cb13-13">  <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">theme_datasheet</span>() <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">+</span></span>
<span id="cb13-14">  <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">theme</span>(<span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">legend.position =</span> <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"top"</span>)</span></code></pre></div></div>
<div class="cell-output-display">
<div id="fig-guess-window" class="quarto-float quarto-figure quarto-figure-center anchored" alt="Scatter of bird counts against row number from 1 to 1500 on a log-scaled count axis. Rows 1 to 1000 sit on a pale shaded band labelled as the guess window. Green points, the counts that were read, fill the lower part of the plot across all rows. Sixty rust points, all between rows 1000 and 1500, sit along the top of the point cloud at counts from 50 to 120 and are labelled as read as NA.">
<figure class="quarto-float quarto-float-fig figure">
<div aria-describedby="fig-guess-window-caption-0ceaefa1-69ba-4598-a22c-09a6ac19f8ca">
<img src="https://tidyecology.com/posts/reading-excel-field-sheets-into-r/index_files/figure-html/fig-guess-window-1.png" class="img-fluid figure-img" alt="Scatter of bird counts against row number from 1 to 1500 on a log-scaled count axis. Rows 1 to 1000 sit on a pale shaded band labelled as the guess window. Green points, the counts that were read, fill the lower part of the plot across all rows. Sixty rust points, all between rows 1000 and 1500, sit along the top of the point cloud at counts from 50 to 120 and are labelled as read as NA." width="672">
</div>
<figcaption class="quarto-float-caption-bottom quarto-float-caption quarto-float-fig" id="fig-guess-window-caption-0ceaefa1-69ba-4598-a22c-09a6ac19f8ca">
Figure&nbsp;1: The count column of the simulated bird sheet against its row number. readxl guessed the column type from the shaded first 1000 rows, which held only plain numbers. The rust points are the 60 flocks typed as estimates after row 1000, plotted at the number the counter wrote: every one of them came back as NA.
</figcaption>
</figure>
</div>
</div>
</div>
<p>The <code>NA</code> then travels. <code>mean(count, na.rm = TRUE)</code> skips it without a word, and so does every summary that drops missing values (<a href="https://tidyecology.com/posts/missing-values-in-summaries/">Missing values in summaries</a> measures what that does to a total).</p>
<div class="cell">
<div class="code-copy-outer-scaffold"><div class="sourceCode cell-code" id="cb14" style="background: #f1f3f5;"><pre class="sourceCode r code-with-copy"><code class="sourceCode r"><span id="cb14-1">mean_sheet <span class="ot" style="color: #003B4F;
background-color: null;
font-style: inherit;">&lt;-</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">mean</span>(sheet_value)</span>
<span id="cb14-2">mean_read  <span class="ot" style="color: #003B4F;
background-color: null;
font-style: inherit;">&lt;-</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">mean</span>(counts<span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">$</span>count, <span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">na.rm =</span> <span class="cn" style="color: #8f5902;
background-color: null;
font-style: inherit;">TRUE</span>)</span>
<span id="cb14-3"><span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">round</span>(<span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">c</span>(<span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">on_the_sheet =</span> mean_sheet, <span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">as_read =</span> mean_read,</span>
<span id="cb14-4">        <span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">change_per_cent =</span> <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">100</span> <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">*</span> (mean_read <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">/</span> mean_sheet <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">-</span> <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">1</span>)), <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">2</span>)</span></code></pre></div></div>
<div class="cell-output cell-output-stdout">
<pre><code>   on_the_sheet         as_read change_per_cent 
          19.96           17.86          -10.52 </code></pre>
</div>
<div class="code-copy-outer-scaffold"><div class="sourceCode cell-code" id="cb16" style="background: #f1f3f5;"><pre class="sourceCode r code-with-copy"><code class="sourceCode r"><span id="cb16-1">mean_text <span class="ot" style="color: #003B4F;
background-color: null;
font-style: inherit;">&lt;-</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">mean</span>(sheet_value[text_row])</span>
<span id="cb16-2"><span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">stopifnot</span>(<span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">isTRUE</span>(<span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">all.equal</span>(mean_read,</span>
<span id="cb16-3">                           mean_sheet <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">-</span> n_text <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">/</span> (n_rows <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">-</span> n_text) <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">*</span> (mean_text <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">-</span> mean_sheet))))</span></code></pre></div></div>
</div>
<p>The counters meant a mean of 19.96 birds per row. The column as read gives 17.86, 10.5 per cent less, because the rows that were lost are the biggest flocks of the winter. The size of the drop is arithmetic, not a property of readxl. Take <code>k</code> values with mean <code>m_text</code> away from <code>n</code> values with mean <code>m</code>, and the mean of the rest is <code>m - k * (m_text - m) / (n - k)</code>. Here <code>k</code> is 60, <code>n</code> is 1500 and the lost estimates average 70.33 birds, which gives the 17.86 above; the last line of the chunk checks it.</p>
</section>
<section id="which-cells-became-na-sets-the-direction" class="level2">
<h2 id="which-cells-became-na-sets-the-direction-h" class="anchored" data-anchor-id="which-cells-became-na-sets-the-direction">Which cells became NA sets the direction</h2>
<p>A smaller mean is not a rule. The column loses whichever rows were typed as text, and the mean moves towards the rows that are left. In a second sheet, the same 60 rows hold the smallest counts instead, typed with a question mark by a counter who was unsure of the number (<code>2?</code>).</p>
<div class="cell">
<div class="code-copy-outer-scaffold"><div class="sourceCode cell-code" id="cb17" style="background: #f1f3f5;"><pre class="sourceCode r code-with-copy"><code class="sourceCode r"><span id="cb17-1">small_first <span class="ot" style="color: #003B4F;
background-color: null;
font-style: inherit;">&lt;-</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">order</span>(count_pool)</span>
<span id="cb17-2">count_small <span class="ot" style="color: #003B4F;
background-color: null;
font-style: inherit;">&lt;-</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">integer</span>(n_rows)</span>
<span id="cb17-3">count_small[text_row]  <span class="ot" style="color: #003B4F;
background-color: null;
font-style: inherit;">&lt;-</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">sample</span>(count_pool[small_first[<span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">1</span><span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">:</span>n_text]])</span>
<span id="cb17-4">count_small[<span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">-</span>text_row] <span class="ot" style="color: #003B4F;
background-color: null;
font-style: inherit;">&lt;-</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">sample</span>(count_pool[small_first[<span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">-</span>(<span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">1</span><span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">:</span>n_text)]])</span>
<span id="cb17-5">path_unsure <span class="ot" style="color: #003B4F;
background-color: null;
font-style: inherit;">&lt;-</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">build_sheet</span>(count_small, text_row, <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">paste0</span>(count_small[text_row], <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"?"</span>), <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"counts_unsure.xlsx"</span>)</span>
<span id="cb17-6"></span>
<span id="cb17-7">unsure_read <span class="ot" style="color: #003B4F;
background-color: null;
font-style: inherit;">&lt;-</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">read_quietly</span>(path_unsure)</span>
<span id="cb17-8">mean_sheet_unsure <span class="ot" style="color: #003B4F;
background-color: null;
font-style: inherit;">&lt;-</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">mean</span>(count_small)</span>
<span id="cb17-9">mean_read_unsure  <span class="ot" style="color: #003B4F;
background-color: null;
font-style: inherit;">&lt;-</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">mean</span>(unsure_read<span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">$</span>data<span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">$</span>count, <span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">na.rm =</span> <span class="cn" style="color: #8f5902;
background-color: null;
font-style: inherit;">TRUE</span>)</span>
<span id="cb17-10"><span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">round</span>(<span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">c</span>(<span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">on_the_sheet =</span> mean_sheet_unsure, <span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">as_read =</span> mean_read_unsure,</span>
<span id="cb17-11">        <span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">change_per_cent =</span> <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">100</span> <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">*</span> (mean_read_unsure <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">/</span> mean_sheet_unsure <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">-</span> <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">1</span>)), <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">2</span>)</span></code></pre></div></div>
<div class="cell-output cell-output-stdout">
<pre><code>   on_the_sheet         as_read change_per_cent 
          19.93           20.70            3.85 </code></pre>
</div>
<div class="code-copy-outer-scaffold"><div class="sourceCode cell-code" id="cb19" style="background: #f1f3f5;"><pre class="sourceCode r code-with-copy"><code class="sourceCode r"><span id="cb19-1"><span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">stopifnot</span>(<span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">sum</span>(<span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">is.na</span>(unsure_read<span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">$</span>data<span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">$</span>count)) <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">==</span> n_text, <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">length</span>(unsure_read<span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">$</span>warnings) <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">==</span> n_text,</span>
<span id="cb19-2">          mean_read_unsure <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">&gt;</span> mean_sheet_unsure, mean_read <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">&lt;</span> mean_sheet)</span></code></pre></div></div>
</div>
<p>Again 60 values are <code>NA</code> and 60 warnings were raised, and this time the mean goes up, from 19.93 to 20.70. The same reading step moves the mean one way on one sheet and the other way on the next, and the size of the move depends on how many cells were text and how far their values sit from the rest. The lost values cannot be recovered from the data frame afterwards: an <code>NA</code> marks where a value was, not what it was, and only the warnings kept the text.</p>
<div class="cell">
<div class="code-copy-outer-scaffold"><div class="sourceCode cell-code" id="cb20" style="background: #f1f3f5;"><pre class="sourceCode r code-with-copy"><code class="sourceCode r"><span id="cb20-1">means_long <span class="ot" style="color: #003B4F;
background-color: null;
font-style: inherit;">&lt;-</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">data.frame</span>(</span>
<span id="cb20-2">  <span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">sheet  =</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">rep</span>(<span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">c</span>(<span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"big flocks typed as 'c. 60'"</span>, <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"small counts typed as '2?'"</span>), <span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">times =</span> <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">2</span>),</span>
<span id="cb20-3">  <span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">source =</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">rep</span>(<span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">c</span>(<span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"numbers the counters wrote"</span>, <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"column as read by read_excel()"</span>), <span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">each =</span> <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">2</span>),</span>
<span id="cb20-4">  <span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">value  =</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">c</span>(mean_sheet, mean_sheet_unsure, mean_read, mean_read_unsure))</span>
<span id="cb20-5"></span>
<span id="cb20-6"><span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">ggplot</span>(means_long, <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">aes</span>(value, sheet)) <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">+</span></span>
<span id="cb20-7">  <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">geom_line</span>(<span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">aes</span>(<span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">group =</span> sheet), <span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">colour =</span> te_line, <span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">linewidth =</span> <span class="fl" style="color: #AD0000;
background-color: null;
font-style: inherit;">1.4</span>) <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">+</span></span>
<span id="cb20-8">  <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">geom_point</span>(<span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">aes</span>(<span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">colour =</span> source), <span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">size =</span> <span class="fl" style="color: #AD0000;
background-color: null;
font-style: inherit;">3.6</span>) <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">+</span></span>
<span id="cb20-9">  <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">scale_colour_manual</span>(<span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">values =</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">c</span>(<span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"numbers the counters wrote"</span> <span class="ot" style="color: #003B4F;
background-color: null;
font-style: inherit;">=</span> te_forest,</span>
<span id="cb20-10">                                 <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"column as read by read_excel()"</span> <span class="ot" style="color: #003B4F;
background-color: null;
font-style: inherit;">=</span> te_rust)) <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">+</span></span>
<span id="cb20-11">  <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">labs</span>(<span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">x =</span> <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"mean birds per row"</span>, <span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">y =</span> <span class="cn" style="color: #8f5902;
background-color: null;
font-style: inherit;">NULL</span>, <span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">colour =</span> <span class="cn" style="color: #8f5902;
background-color: null;
font-style: inherit;">NULL</span>) <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">+</span></span>
<span id="cb20-12">  <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">theme_datasheet</span>() <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">+</span></span>
<span id="cb20-13">  <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">theme</span>(<span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">legend.position =</span> <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"top"</span>)</span></code></pre></div></div>
<div class="cell-output-display">
<div id="fig-direction" class="quarto-float quarto-figure quarto-figure-center anchored" alt="Dot plot with two rows. Top row, small counts typed with a question mark: a rust dot for the mean as read sits to the right of a green dot for the sheet mean, joined by a grey line. Bottom row, big flocks typed as c. estimates: the green dot sits to the right of the rust dot. The horizontal axis is mean birds per row, from below 18 to above 20.">
<figure class="quarto-float quarto-float-fig figure">
<div aria-describedby="fig-direction-caption-0ceaefa1-69ba-4598-a22c-09a6ac19f8ca">
<img src="https://tidyecology.com/posts/reading-excel-field-sheets-into-r/index_files/figure-html/fig-direction-1.png" class="img-fluid figure-img" alt="Dot plot with two rows. Top row, small counts typed with a question mark: a rust dot for the mean as read sits to the right of a green dot for the sheet mean, joined by a grey line. Bottom row, big flocks typed as c. estimates: the green dot sits to the right of the rust dot. The horizontal axis is mean birds per row, from below 18 to above 20." width="672">
</div>
<figcaption class="quarto-float-caption-bottom quarto-float-caption quarto-float-fig" id="fig-direction-caption-0ceaefa1-69ba-4598-a22c-09a6ac19f8ca">
Figure&nbsp;2: Mean count per row on two simulated sheets with the same 60 text rows after row 1000: on one they hold the 60 largest counts, typed as c.&nbsp;estimates, on the other the 60 smallest, typed with a question mark. Dark green: the mean of the numbers the counters wrote. Rust: the mean of the column as read_excel() returned it, with the text cells as NA and skipped. Losing the big flocks lowers the mean; losing the smallest counts raises it.
</figcaption>
</figure>
</div>
</div>
</div>
</section>
<section id="one-text-cell-early-changes-the-whole-column" class="level2">
<h2 id="one-text-cell-early-changes-the-whole-column-h" class="anchored" data-anchor-id="one-text-cell-early-changes-the-whole-column">One text cell early changes the whole column</h2>
<p>Now move a single estimate from the second half of the flock sheet into the first 1000 rows, to row 500.</p>
<div class="cell">
<div class="code-copy-outer-scaffold"><div class="sourceCode cell-code" id="cb21" style="background: #f1f3f5;"><pre class="sourceCode r code-with-copy"><code class="sourceCode r"><span id="cb21-1">early_row <span class="ot" style="color: #003B4F;
background-color: null;
font-style: inherit;">&lt;-</span> text_row</span>
<span id="cb21-2">early_row[<span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">1</span>] <span class="ot" style="color: #003B4F;
background-color: null;
font-style: inherit;">&lt;-</span> <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">500</span></span>
<span id="cb21-3">count_early <span class="ot" style="color: #003B4F;
background-color: null;
font-style: inherit;">&lt;-</span> count_big</span>
<span id="cb21-4">count_early[<span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">c</span>(<span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">500</span>, text_row[<span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">1</span>])] <span class="ot" style="color: #003B4F;
background-color: null;
font-style: inherit;">&lt;-</span> count_big[<span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">c</span>(text_row[<span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">1</span>], <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">500</span>)]</span>
<span id="cb21-5">path_early <span class="ot" style="color: #003B4F;
background-color: null;
font-style: inherit;">&lt;-</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">build_sheet</span>(count_early, early_row, <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">paste</span>(<span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"c."</span>, flock_value), <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"counts_early.xlsx"</span>)</span>
<span id="cb21-6"></span>
<span id="cb21-7">early_read <span class="ot" style="color: #003B4F;
background-color: null;
font-style: inherit;">&lt;-</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">read_quietly</span>(path_early)</span>
<span id="cb21-8"><span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">class</span>(early_read<span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">$</span>data<span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">$</span>count)</span></code></pre></div></div>
<div class="cell-output cell-output-stdout">
<pre><code>[1] "character"</code></pre>
</div>
<div class="code-copy-outer-scaffold"><div class="sourceCode cell-code" id="cb23" style="background: #f1f3f5;"><pre class="sourceCode r code-with-copy"><code class="sourceCode r"><span id="cb23-1"><span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">length</span>(early_read<span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">$</span>warnings)</span></code></pre></div></div>
<div class="cell-output cell-output-stdout">
<pre><code>[1] 0</code></pre>
</div>
<div class="code-copy-outer-scaffold"><div class="sourceCode cell-code" id="cb25" style="background: #f1f3f5;"><pre class="sourceCode r code-with-copy"><code class="sourceCode r"><span id="cb25-1">sum_attempt <span class="ot" style="color: #003B4F;
background-color: null;
font-style: inherit;">&lt;-</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">try</span>(<span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">sum</span>(early_read<span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">$</span>data<span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">$</span>count), <span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">silent =</span> <span class="cn" style="color: #8f5902;
background-color: null;
font-style: inherit;">TRUE</span>)</span>
<span id="cb25-2"><span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">conditionMessage</span>(<span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">attr</span>(sum_attempt, <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"condition"</span>))</span></code></pre></div></div>
<div class="cell-output cell-output-stdout">
<pre><code>[1] "invalid 'type' (character) of argument"</code></pre>
</div>
<div class="code-copy-outer-scaffold"><div class="sourceCode cell-code" id="cb27" style="background: #f1f3f5;"><pre class="sourceCode r code-with-copy"><code class="sourceCode r"><span id="cb27-1"><span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">stopifnot</span>(<span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">is.character</span>(early_read<span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">$</span>data<span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">$</span>count), <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">length</span>(early_read<span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">$</span>warnings) <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">==</span> <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">0</span>,</span>
<span id="cb27-2">          <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">inherits</span>(<span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">try</span>(<span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">sum</span>(early_read<span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">$</span>data<span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">$</span>count), <span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">silent =</span> <span class="cn" style="color: #8f5902;
background-color: null;
font-style: inherit;">TRUE</span>), <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"try-error"</span>))</span></code></pre></div></div>
</div>
<p>One text cell inside the guess window is enough: the column comes back as text, with 0 warnings, and <code>sum()</code> fails exactly as it does after <code>read.csv()</code>. This is the better outcome. The failure is loud and it happens at the first calculation, while the column that came back as numbers in the previous section ran every calculation without an error.</p>
</section>
<section id="tell-read_excel-what-the-columns-are" class="level2">
<h2 id="tell-read_excel-what-the-columns-are-h" class="anchored" data-anchor-id="tell-read_excel-what-the-columns-are">Tell read_excel() what the columns are</h2>
<p>Two arguments deal with the guess. <code>guess_max</code> can be raised so that the guess looks at every row; a value larger than the sheet, such as 100000, is enough (<code>Inf</code> also works, with a warning that it has been lowered to a large finite number).</p>
<div class="cell">
<div class="code-copy-outer-scaffold"><div class="sourceCode cell-code" id="cb28" style="background: #f1f3f5;"><pre class="sourceCode r code-with-copy"><code class="sourceCode r"><span id="cb28-1">whole_guess <span class="ot" style="color: #003B4F;
background-color: null;
font-style: inherit;">&lt;-</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">read_quietly</span>(path_flocks, <span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">guess_max =</span> <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">100000</span>)</span>
<span id="cb28-2"><span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">class</span>(whole_guess<span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">$</span>data<span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">$</span>count)</span></code></pre></div></div>
<div class="cell-output cell-output-stdout">
<pre><code>[1] "character"</code></pre>
</div>
<div class="code-copy-outer-scaffold"><div class="sourceCode cell-code" id="cb30" style="background: #f1f3f5;"><pre class="sourceCode r code-with-copy"><code class="sourceCode r"><span id="cb30-1"><span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">length</span>(whole_guess<span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">$</span>warnings)</span></code></pre></div></div>
<div class="cell-output cell-output-stdout">
<pre><code>[1] 0</code></pre>
</div>
<div class="code-copy-outer-scaffold"><div class="sourceCode cell-code" id="cb32" style="background: #f1f3f5;"><pre class="sourceCode r code-with-copy"><code class="sourceCode r"><span id="cb32-1">inf_guess <span class="ot" style="color: #003B4F;
background-color: null;
font-style: inherit;">&lt;-</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">read_quietly</span>(path_flocks, <span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">guess_max =</span> <span class="cn" style="color: #8f5902;
background-color: null;
font-style: inherit;">Inf</span>)</span>
<span id="cb32-2"><span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">stopifnot</span>(<span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">is.character</span>(whole_guess<span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">$</span>data<span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">$</span>count), <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">length</span>(whole_guess<span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">$</span>warnings) <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">==</span> <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">0</span>,</span>
<span id="cb32-3">          <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">is.character</span>(inf_guess<span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">$</span>data<span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">$</span>count), <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">length</span>(inf_guess<span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">$</span>warnings) <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">==</span> <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">1</span>,</span>
<span id="cb32-4">          <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">grepl</span>(<span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"guess_max"</span>, inf_guess<span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">$</span>warnings[<span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">1</span>]))</span></code></pre></div></div>
</div>
<p>With every row in the guess, the flock column comes back as text. That is safe, but it is still a guess. <code>col_types</code> states the types outright, one per column, and <code>na</code> lists the entries that mean missing. The date column is declared as a date and the count column as text, so that each estimate can be dealt with on purpose:</p>
<div class="cell">
<div class="code-copy-outer-scaffold"><div class="sourceCode cell-code" id="cb33" style="background: #f1f3f5;"><pre class="sourceCode r code-with-copy"><code class="sourceCode r"><span id="cb33-1">typed_read <span class="ot" style="color: #003B4F;
background-color: null;
font-style: inherit;">&lt;-</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">read_quietly</span>(path_flocks, <span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">col_types =</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">c</span>(<span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"date"</span>, <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"text"</span>, <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"text"</span>),</span>
<span id="cb33-2">                           <span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">na =</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">c</span>(<span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">""</span>, <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"not recorded"</span>))</span>
<span id="cb33-3">typed <span class="ot" style="color: #003B4F;
background-color: null;
font-style: inherit;">&lt;-</span> typed_read<span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">$</span>data</span>
<span id="cb33-4"><span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">length</span>(typed_read<span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">$</span>warnings)</span></code></pre></div></div>
<div class="cell-output cell-output-stdout">
<pre><code>[1] 0</code></pre>
</div>
<div class="code-copy-outer-scaffold"><div class="sourceCode cell-code" id="cb35" style="background: #f1f3f5;"><pre class="sourceCode r code-with-copy"><code class="sourceCode r"><span id="cb35-1">typed<span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">$</span>is_estimate <span class="ot" style="color: #003B4F;
background-color: null;
font-style: inherit;">&lt;-</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">grepl</span>(<span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"^c</span><span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">\\</span><span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">."</span>, typed<span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">$</span>count)</span>
<span id="cb35-2">typed<span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">$</span>birds <span class="ot" style="color: #003B4F;
background-color: null;
font-style: inherit;">&lt;-</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">as.numeric</span>(<span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">sub</span>(<span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"^c</span><span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">\\</span><span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">.</span><span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">\\</span><span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">s*"</span>, <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">""</span>, typed<span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">$</span>count))</span>
<span id="cb35-3"><span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">c</span>(<span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">estimates =</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">sum</span>(typed<span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">$</span>is_estimate), <span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">missing_counts =</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">sum</span>(<span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">is.na</span>(typed<span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">$</span>birds)))</span></code></pre></div></div>
<div class="cell-output cell-output-stdout">
<pre><code>     estimates missing_counts 
            60              0 </code></pre>
</div>
<div class="code-copy-outer-scaffold"><div class="sourceCode cell-code" id="cb37" style="background: #f1f3f5;"><pre class="sourceCode r code-with-copy"><code class="sourceCode r"><span id="cb37-1"><span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">round</span>(<span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">mean</span>(typed<span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">$</span>birds), <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">2</span>)</span></code></pre></div></div>
<div class="cell-output cell-output-stdout">
<pre><code>[1] 19.96</code></pre>
</div>
<div class="code-copy-outer-scaffold"><div class="sourceCode cell-code" id="cb39" style="background: #f1f3f5;"><pre class="sourceCode r code-with-copy"><code class="sourceCode r"><span id="cb39-1"><span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">stopifnot</span>(<span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">length</span>(typed_read<span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">$</span>warnings) <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">==</span> <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">0</span>, <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">sum</span>(typed<span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">$</span>is_estimate) <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">==</span> n_text,</span>
<span id="cb39-2">          <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">!</span><span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">anyNA</span>(typed<span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">$</span>birds), <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">isTRUE</span>(<span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">all.equal</span>(<span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">mean</span>(typed<span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">$</span>birds), mean_sheet)),</span>
<span id="cb39-3">          <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">sum</span>(<span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">is.na</span>(typed<span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">$</span>visit)) <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">==</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">length</span>(no_date))</span></code></pre></div></div>
</div>
<p>No warnings, 60 estimates found and kept as numbers, 0 missing counts, and the mean is the 19.96 birds per row that the counters meant. The <code>is_estimate</code> column keeps the information the <code>c.</code> carried, so an analysis can still leave the estimates out or give them their own error, but that is now a decision in the script rather than a side effect of the reader. If a pattern like <code>^c\.</code> is new to you, <a href="https://tidyecology.com/posts/text-and-regular-expressions/">Text and regular expressions in R</a> covers it.</p>
</section>
<section id="dates-that-arrive-as-serial-numbers" class="level2">
<h2 id="dates-that-arrive-as-serial-numbers-h" class="anchored" data-anchor-id="dates-that-arrive-as-serial-numbers">Dates that arrive as serial numbers</h2>
<p>Back to the plain <code>read_excel()</code> call. Look at its first column.</p>
<div class="cell">
<div class="code-copy-outer-scaffold"><div class="sourceCode cell-code" id="cb40" style="background: #f1f3f5;"><pre class="sourceCode r code-with-copy"><code class="sourceCode r"><span id="cb40-1"><span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">class</span>(counts<span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">$</span>visit)</span></code></pre></div></div>
<div class="cell-output cell-output-stdout">
<pre><code>[1] "character"</code></pre>
</div>
<div class="code-copy-outer-scaffold"><div class="sourceCode cell-code" id="cb42" style="background: #f1f3f5;"><pre class="sourceCode r code-with-copy"><code class="sourceCode r"><span id="cb42-1"><span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">head</span>(counts<span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">$</span>visit, <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">4</span>)</span></code></pre></div></div>
<div class="cell-output cell-output-stdout">
<pre><code>[1] "45200" "45200" "45200" "45200"</code></pre>
</div>
<div class="code-copy-outer-scaffold"><div class="sourceCode cell-code" id="cb44" style="background: #f1f3f5;"><pre class="sourceCode r code-with-copy"><code class="sourceCode r"><span id="cb44-1"><span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">stopifnot</span>(<span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">is.character</span>(counts<span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">$</span>visit), <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">sum</span>(counts<span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">$</span>visit <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">==</span> <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"not recorded"</span>) <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">==</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">length</span>(no_date),</span>
<span id="cb44-2">          <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">all</span>(<span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">grepl</span>(<span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"^[0-9]{5}$"</span>, counts<span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">$</span>visit[<span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">-</span>no_date])))</span></code></pre></div></div>
</div>
<p>The visit dates came back as text: apart from the five <code>not recorded</code> cells, every entry is a five-digit number such as 45200. Those five cells sit inside the first 1000 rows, so the guess for the column was text, and a date cell in a text column arrives as the number Excel stores behind it: the date serial, a count of days. With <code>na = c("", "not recorded")</code> in the call, as in the typed read above, the same column arrives as a date-time:</p>
<div class="cell">
<div class="code-copy-outer-scaffold"><div class="sourceCode cell-code" id="cb45" style="background: #f1f3f5;"><pre class="sourceCode r code-with-copy"><code class="sourceCode r"><span id="cb45-1"><span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">class</span>(typed<span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">$</span>visit)</span></code></pre></div></div>
<div class="cell-output cell-output-stdout">
<pre><code>[1] "POSIXct" "POSIXt" </code></pre>
</div>
<div class="code-copy-outer-scaffold"><div class="sourceCode cell-code" id="cb47" style="background: #f1f3f5;"><pre class="sourceCode r code-with-copy"><code class="sourceCode r"><span id="cb47-1"><span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">attr</span>(typed<span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">$</span>visit, <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"tzone"</span>)</span></code></pre></div></div>
<div class="cell-output cell-output-stdout">
<pre><code>[1] "UTC"</code></pre>
</div>
<div class="code-copy-outer-scaffold"><div class="sourceCode cell-code" id="cb49" style="background: #f1f3f5;"><pre class="sourceCode r code-with-copy"><code class="sourceCode r"><span id="cb49-1">visit_read <span class="ot" style="color: #003B4F;
background-color: null;
font-style: inherit;">&lt;-</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">as.Date</span>(typed<span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">$</span>visit)</span>
<span id="cb49-2"><span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">stopifnot</span>(<span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">inherits</span>(typed<span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">$</span>visit, <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"POSIXct"</span>), <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">identical</span>(<span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">attr</span>(typed<span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">$</span>visit, <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"tzone"</span>), <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"UTC"</span>),</span>
<span id="cb49-3">          <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">all</span>(visit_read[<span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">-</span>no_date] <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">==</span> visit_true[<span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">-</span>no_date]))</span></code></pre></div></div>
</div>
<p>readxl returns dates as date-times in UTC, and <code>as.Date()</code> turns them into plain dates; all 1495 of them match the true visit dates. When a file has already been read and you have the serials as text, the conversion needs an origin, the day R counts the serials from. For dates from March 1900 on in Excel’s default 1900 date system, that day is 30 December 1899 (why not 1 January 1900 is explained below):</p>
<div class="cell">
<div class="code-copy-outer-scaffold"><div class="sourceCode cell-code" id="cb50" style="background: #f1f3f5;"><pre class="sourceCode r code-with-copy"><code class="sourceCode r"><span id="cb50-1">serial <span class="ot" style="color: #003B4F;
background-color: null;
font-style: inherit;">&lt;-</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">as.numeric</span>(counts<span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">$</span>visit[<span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">-</span>no_date])</span>
<span id="cb50-2">right_origin <span class="ot" style="color: #003B4F;
background-color: null;
font-style: inherit;">&lt;-</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">as.Date</span>(serial, <span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">origin =</span> <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"1899-12-30"</span>)</span>
<span id="cb50-3">jan_origin   <span class="ot" style="color: #003B4F;
background-color: null;
font-style: inherit;">&lt;-</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">as.Date</span>(serial, <span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">origin =</span> <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"1900-01-01"</span>)</span>
<span id="cb50-4">no_origin    <span class="ot" style="color: #003B4F;
background-color: null;
font-style: inherit;">&lt;-</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">as.Date</span>(serial)</span>
<span id="cb50-5">truth        <span class="ot" style="color: #003B4F;
background-color: null;
font-style: inherit;">&lt;-</span> visit_true[<span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">-</span>no_date]</span>
<span id="cb50-6">new_year      <span class="ot" style="color: #003B4F;
background-color: null;
font-style: inherit;">&lt;-</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">sum</span>(<span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">format</span>(jan_origin, <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"%Y"</span>) <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">!=</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">format</span>(truth, <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"%Y"</span>))</span>
<span id="cb50-7">out_of_season <span class="ot" style="color: #003B4F;
background-color: null;
font-style: inherit;">&lt;-</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">sum</span>(jan_origin <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">&lt;</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">as.Date</span>(<span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"2023-10-01"</span>) <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">|</span> jan_origin <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">&gt;</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">as.Date</span>(<span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"2024-03-31"</span>))</span>
<span id="cb50-8"></span>
<span id="cb50-9"><span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">c</span>(<span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">days_off_1899_12_30 =</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">unique</span>(<span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">as.numeric</span>(right_origin <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">-</span> truth)),</span>
<span id="cb50-10">  <span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">days_off_1900_01_01 =</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">unique</span>(<span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">as.numeric</span>(jan_origin <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">-</span> truth)))</span></code></pre></div></div>
<div class="cell-output cell-output-stdout">
<pre><code>days_off_1899_12_30 days_off_1900_01_01 
                  0                   2 </code></pre>
</div>
<div class="code-copy-outer-scaffold"><div class="sourceCode cell-code" id="cb52" style="background: #f1f3f5;"><pre class="sourceCode r code-with-copy"><code class="sourceCode r"><span id="cb52-1"><span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">range</span>(<span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">format</span>(no_origin, <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"%Y"</span>))</span></code></pre></div></div>
<div class="cell-output cell-output-stdout">
<pre><code>[1] "2093" "2094"</code></pre>
</div>
<div class="code-copy-outer-scaffold"><div class="sourceCode cell-code" id="cb54" style="background: #f1f3f5;"><pre class="sourceCode r code-with-copy"><code class="sourceCode r"><span id="cb54-1"><span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">stopifnot</span>(<span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">all</span>(right_origin <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">==</span> truth), <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">all</span>(jan_origin <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">-</span> truth <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">==</span> <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">2</span>),</span>
<span id="cb54-2">          <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">getRversion</span>() <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">&gt;=</span> <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"4.3.0"</span>, <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">as.Date</span>(<span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">0</span>) <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">==</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">as.Date</span>(<span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"1970-01-01"</span>),</span>
<span id="cb54-3">          <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">getDateOrigin</span>(path_flocks) <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">==</span> <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"1900-01-01"</span>,</span>
<span id="cb54-4">          <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">all</span>(<span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">convertToDate</span>(serial, <span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">origin =</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">getDateOrigin</span>(path_flocks)) <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">==</span> truth),</span>
<span id="cb54-5">          <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">as.Date</span>(<span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">61</span>, <span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">origin =</span> <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"1899-12-30"</span>) <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">==</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">as.Date</span>(<span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"1900-03-01"</span>),</span>
<span id="cb54-6">          <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">as.Date</span>(<span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">40729</span>, <span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">origin =</span> <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"1899-12-30"</span>) <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">==</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">as.Date</span>(<span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"2011-07-05"</span>),</span>
<span id="cb54-7">          <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">as.Date</span>(<span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">39267</span>, <span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">origin =</span> <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"1904-01-01"</span>) <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">==</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">as.Date</span>(<span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"2011-07-05"</span>),</span>
<span id="cb54-8">          <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">as.numeric</span>(<span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">as.Date</span>(<span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"1904-01-01"</span>) <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">-</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">as.Date</span>(<span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"1899-12-30"</span>)) <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">==</span> <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">1462</span>,</span>
<span id="cb54-9">          new_year <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">&gt;</span> <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">0</span>, new_year <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">==</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">sum</span>(<span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">format</span>(truth, <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"%m-%d"</span>) <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">==</span> <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"12-31"</span>), out_of_season <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">==</span> <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">0</span>,</span>
<span id="cb54-10">          <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">all</span>(truth <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">-</span> <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">1462</span> <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">==</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">as.Date</span>(<span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">paste0</span>(<span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">as.numeric</span>(<span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">format</span>(truth, <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"%Y"</span>)) <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">-</span> <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">4</span>, <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">format</span>(truth, <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"-%m-%d"</span>))) <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">-</span> <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">1</span>))</span></code></pre></div></div>
</div>
<p>The origin 1899-12-30 gives every date exactly. The origin that looks right, 1 January 1900, puts every date 2 days late. And <code>as.Date()</code> with no origin at all uses 1 January 1970 (R has done so since version 4.3.0; older versions stop with an error), which moves this winter to the years 2093 to 2094. That one is easy to spot. The two-day error is not: every date is plausible, inside the field season, and wrong. The 50 rows dated 31 December have even moved into the next year.</p>
<p>The two days come from Excel itself. Excel counts 1 January 1900 as day 1, not day 0, and it treats 1900 as a leap year, so it has a 29 February 1900 that never happened (serial 60). Microsoft documents the extra leap day as a choice made for compatibility with Lotus 1-2-3 and kept ever since. From 1 March 1900 on, each serial is two more than the number of days since 1 January 1900. openxlsx (4.2.9 here; the current source does the same) has a pair of functions for this: <code>getDateOrigin()</code> reports the workbook’s date system as <code>"1900-01-01"</code>, and <code>convertToDate()</code> subtracts the two days when given that origin. Passing the output of <code>getDateOrigin()</code> straight to <code>as.Date()</code> gives the two-day error again.</p>
<p>The quickest check on converted dates is the one the design gives you for free. These counts were all made on Sundays:</p>
<div class="cell">
<div class="code-copy-outer-scaffold"><div class="sourceCode cell-code" id="cb55" style="background: #f1f3f5;"><pre class="sourceCode r code-with-copy"><code class="sourceCode r"><span id="cb55-1">day_names <span class="ot" style="color: #003B4F;
background-color: null;
font-style: inherit;">&lt;-</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">c</span>(<span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"Sun"</span>, <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"Mon"</span>, <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"Tue"</span>, <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"Wed"</span>, <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"Thu"</span>, <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"Fri"</span>, <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"Sat"</span>)</span>
<span id="cb55-2">weekday_of <span class="ot" style="color: #003B4F;
background-color: null;
font-style: inherit;">&lt;-</span> <span class="cf" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">function</span>(d) <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">factor</span>(day_names[<span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">as.POSIXlt</span>(d)<span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">$</span>wday <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">+</span> <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">1</span>], <span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">levels =</span> day_names)</span>
<span id="cb55-3"><span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">rbind</span>(<span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">origin_1899_12_30 =</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">table</span>(<span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">weekday_of</span>(right_origin)),</span>
<span id="cb55-4">      <span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">origin_1900_01_01 =</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">table</span>(<span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">weekday_of</span>(jan_origin)),</span>
<span id="cb55-5">      <span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">no_origin         =</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">table</span>(<span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">weekday_of</span>(no_origin)))</span></code></pre></div></div>
<div class="cell-output cell-output-stdout">
<pre><code>                   Sun Mon  Tue Wed Thu  Fri Sat
origin_1899_12_30 1495   0    0   0   0    0   0
origin_1900_01_01    0   0 1495   0   0    0   0
no_origin            0   0    0   0   0 1495   0</code></pre>
</div>
</div>
<div class="cell">
<div class="code-copy-outer-scaffold"><div class="sourceCode cell-code" id="cb57" style="background: #f1f3f5;"><pre class="sourceCode r code-with-copy"><code class="sourceCode r"><span id="cb57-1">weekday_long <span class="ot" style="color: #003B4F;
background-color: null;
font-style: inherit;">&lt;-</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">data.frame</span>(</span>
<span id="cb57-2">  <span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">origin  =</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">factor</span>(<span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">rep</span>(<span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">c</span>(<span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"origin 1899-12-30"</span>, <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"origin 1900-01-01"</span>, <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"no origin (1970-01-01)"</span>),</span>
<span id="cb57-3">                       <span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">each =</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">length</span>(serial)),</span>
<span id="cb57-4">                   <span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">levels =</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">c</span>(<span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"origin 1899-12-30"</span>, <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"origin 1900-01-01"</span>, <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"no origin (1970-01-01)"</span>)),</span>
<span id="cb57-5">  <span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">weekday =</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">c</span>(<span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">weekday_of</span>(right_origin), <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">weekday_of</span>(jan_origin), <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">weekday_of</span>(no_origin)))</span>
<span id="cb57-6">weekday_long<span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">$</span>correct <span class="ot" style="color: #003B4F;
background-color: null;
font-style: inherit;">&lt;-</span> weekday_long<span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">$</span>origin <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">==</span> <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"origin 1899-12-30"</span></span>
<span id="cb57-7"></span>
<span id="cb57-8"><span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">ggplot</span>(weekday_long, <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">aes</span>(weekday, <span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">fill =</span> correct)) <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">+</span></span>
<span id="cb57-9">  <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">geom_bar</span>(<span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">width =</span> <span class="fl" style="color: #AD0000;
background-color: null;
font-style: inherit;">0.7</span>) <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">+</span></span>
<span id="cb57-10">  <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">scale_x_discrete</span>(<span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">drop =</span> <span class="cn" style="color: #8f5902;
background-color: null;
font-style: inherit;">FALSE</span>) <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">+</span></span>
<span id="cb57-11">  <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">scale_fill_manual</span>(<span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">values =</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">c</span>(<span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"TRUE"</span> <span class="ot" style="color: #003B4F;
background-color: null;
font-style: inherit;">=</span> te_forest, <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"FALSE"</span> <span class="ot" style="color: #003B4F;
background-color: null;
font-style: inherit;">=</span> te_rust), <span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">guide =</span> <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"none"</span>) <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">+</span></span>
<span id="cb57-12">  <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">facet_wrap</span>(<span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">~</span> origin) <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">+</span></span>
<span id="cb57-13">  <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">labs</span>(<span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">x =</span> <span class="cn" style="color: #8f5902;
background-color: null;
font-style: inherit;">NULL</span>, <span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">y =</span> <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"visits"</span>) <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">+</span></span>
<span id="cb57-14">  <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">theme_datasheet</span>() <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">+</span></span>
<span id="cb57-15">  <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">theme</span>(<span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">axis.text.x =</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">element_text</span>(<span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">size =</span> <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">8</span>))</span></code></pre></div></div>
<div class="cell-output-display">
<div id="fig-weekdays" class="quarto-float quarto-figure quarto-figure-center anchored" alt="Three bar chart panels, one per origin, each with the seven weekdays from Sunday to Saturday on the horizontal axis. In the panel for origin 1899-12-30 a single tall green bar stands at Sunday. In the panel for 1900-01-01 a single tall rust bar stands at Tuesday. In the panel for no origin a single tall rust bar stands at Friday. All other weekdays are empty in every panel.">
<figure class="quarto-float quarto-float-fig figure">
<div aria-describedby="fig-weekdays-caption-0ceaefa1-69ba-4598-a22c-09a6ac19f8ca">
<img src="https://tidyecology.com/posts/reading-excel-field-sheets-into-r/index_files/figure-html/fig-weekdays-1.png" class="img-fluid figure-img" alt="Three bar chart panels, one per origin, each with the seven weekdays from Sunday to Saturday on the horizontal axis. In the panel for origin 1899-12-30 a single tall green bar stands at Sunday. In the panel for 1900-01-01 a single tall rust bar stands at Tuesday. In the panel for no origin a single tall rust bar stands at Friday. All other weekdays are empty in every panel." width="672">
</div>
<figcaption class="quarto-float-caption-bottom quarto-float-caption quarto-float-fig" id="fig-weekdays-caption-0ceaefa1-69ba-4598-a22c-09a6ac19f8ca">
Figure&nbsp;3: Weekday of every recorded visit date on the simulated sheet, after converting the date serials with three different origins. Every count was made on a Sunday. The origin 1899-12-30 returns Sundays; 1900-01-01 moves every date two days later, to a Tuesday; no origin (R 4.3.0 and later use 1970-01-01) moves them to Fridays in the 2090s.
</figcaption>
</figure>
</div>
</div>
</div>
<p>A table of weekdays takes one line and turns a silent two-day shift into a column of Tuesdays. The same check works for any sampling design with a fixed day. A range check against the field season is no substitute: it catches the 2090s at once, but after the two-day shift 0 of the 1495 dates fall outside October to March. Without a fixed weekday, compare a few converted dates with the paper sheets or a field diary.</p>
<p>The origin 1899-12-30 has two limits of its own. It is exact only for serials from 61 on, dates from 1 March 1900, which covers any modern field sheet. And it holds only for the 1900 date system. Workbooks set to the 1904 date system, the old default in Excel for Mac, count days from 1 January 1904, and a serial from such a file needs <code>origin = "1904-01-01"</code>. Using 1899-12-30 instead would put every date 1462 days early, four years and one day, which is the gap Microsoft gives between the two systems. Its worked example, 5 July 2011, is serial 40729 in the 1900 system and 39267 in the 1904 system, and each converts to the right day with the matching origin. <code>getDateOrigin()</code> tells you which system a file uses.</p>
</section>
<section id="what-to-check-in-your-own-data" class="level2">
<h2 id="what-to-check-in-your-own-data-h" class="anchored" data-anchor-id="what-to-check-in-your-own-data">What to check in your own data</h2>
<p>Run <code>str()</code> after every <code>read_excel()</code> call, as after <code>read.csv()</code>, and read the type of each column against what it should be. A count column that is <code>chr</code> has text in its first 1000 rows; a count column that is <code>num</code> may still have lost text entries further down, which only the warnings or a count of <code>NA</code> values will show.</p>
<p>Count the <code>NA</code> values in each column straight after reading, with <code>colSums(is.na(x))</code>, and compare them with the blank cells you expect. Every extra one is a cell the reader could not turn into the type it guessed.</p>
<p>The lasting fix is on the sheet. Broman and Woo (2018) ask for one thing in each cell, with notes in a column of their own, and for every cell to be filled, with one agreed code for missing values. On this sheet that means a plain number in the count column with a <code>yes</code> in an <code>estimate</code> column beside it, and one missing-value code in the date column, the same code everywhere, with the reason in the notes.</p>
<p>For a sheet you will read more than once, write <code>col_types</code> and <code>na</code> into the call. Read columns that mix numbers with notes as <code>"text"</code>, and parse them with a line of code that you can check.</p>
<p>Convert date serials with <code>origin = "1899-12-30"</code>, or with <code>convertToDate()</code> and <code>getDateOrigin()</code>, and then check the dates against the design: the weekday if the survey had one, otherwise a few dates against the paper sheets. A range check catches the 1970 origin, not a two-day shift.</p>
</section>
<section id="honest-limits" class="level2">
<h2 id="honest-limits-h" class="anchored" data-anchor-id="honest-limits">Honest limits</h2>
<p>The workbooks here were written by openxlsx, not by Excel, and they have one sheet, a header row and no merged cells, colours or formulas. A field workbook typed in Excel can carry all of those, and readxl’s treatment of formatted cells (a number stored as text, a date typed in a cell formatted as text) is not tested here. The 1904 date system is described from its definition, not demonstrated: openxlsx writes 1900-system workbooks. The sizes of the two mean shifts belong to these two constructed sheets; they show that the direction depends on which cells were text, and say nothing about how large the shift is in real count data.</p>
</section>
<section id="references" class="level2">
<h2 id="references-h" class="anchored" data-anchor-id="references">References</h2>
<p>Broman KW, Woo KH 2018 The American Statistician 72(1):2-10 (<a href="https://doi.org/10.1080/00031305.2017.1375989">10.1080/00031305.2017.1375989</a>)</p>
<p>Wickham H, Bryan J 2026 readxl 1.5.0 documentation: Cell and column types (https://readxl.tidyverse.org/articles/cell-and-column-types.html)</p>
<p>Microsoft 2026 Excel troubleshooting: Excel incorrectly assumes that the year 1900 is a leap year (https://learn.microsoft.com/en-us/troubleshoot/microsoft-365-apps/excel/wrongly-assumes-1900-is-leap-year)</p>
<p>Microsoft 2024 Excel help: Date systems in Excel (https://support.microsoft.com/en-us/office/date-systems-in-excel-e7fe7167-48a9-4b96-bb53-5612a800b487)</p>
</section>
<section id="related-tutorials" class="level2">
<h2 id="related-tutorials-h" class="anchored" data-anchor-id="related-tutorials">Related tutorials</h2>
<ul>
<li><a href="https://tidyecology.com/posts/reading-field-data-into-r/">Reading field data into R</a></li>
<li><a href="https://tidyecology.com/posts/dates-and-times-in-ecological-data/">Dates and times in ecological data</a></li>
<li><a href="https://tidyecology.com/posts/missing-values-in-summaries/">Missing values in summaries: na.rm and false zeros</a></li>
<li><a href="https://tidyecology.com/posts/what-a-csv-loses/">What a CSV loses: archiving an R analysis</a></li>
</ul>
<details class="te-repro" data-pagefind-ignore="">
<summary>Reproducibility</summary>
<ul>
<li>Code last run: 2026-10-15</li>
<li>R version 4.5.3 (2026-03-11), aarch64-apple-darwin20</li>
<li>Packages: ggplot2 4.0.3, openxlsx 4.2.9, readxl 1.5.0.1</li>
</ul>
</details>


<!-- -->

</section>

 ]]></description>
  <category>R</category>
  <category>data import</category>
  <category>readxl</category>
  <category>missing data</category>
  <category>data cleaning</category>
  <category>ecology tutorial</category>
  <guid isPermaLink="false">https://tidyecology.com/posts/reading-excel-field-sheets-into-r/</guid>
  <pubDate>Sun, 27 Sep 2026 05:00:00 GMT</pubDate>
  <media:content url="https://tidyecology.com/posts/reading-excel-field-sheets-into-r/thumbnail.png" medium="image" type="image/png" height="104" width="144"/>
</item>
<item>
  <title>Moran’s I on residuals: moran.test or lm.morantest</title>
  <dc:creator>Tidy Ecology</dc:creator>
  <link>https://tidyecology.com/posts/morans-i-on-regression-residuals/</link>
  <description><![CDATA[ 





<p>A hundred and fifty vegetation plots lie scattered over a limestone plateau, and the response is the log of shrub cover. The model has an intercept, one plot-level covariate, and a handful of Moran eigenvector maps added to take up the broad spatial trend. The last line of the script is the check that spatial tutorials teach: Moran’s I on the residuals, with <code>moran.test(residuals(fit), lw)</code> or its permutation twin <code>moran.mc()</code>. A p-value well above 0.05 comes back, and the residuals are declared spatially clean.</p>
<p>That line asks the wrong question. <code>moran.test()</code> treats whatever vector it is given as raw data, and under its null hypothesis the expected value of I is minus one over (n minus one), the value for independent observations of the statistic Moran (1950) introduced. Regression residuals are not raw data: they are the part of the response that is orthogonal to every column of the design matrix, and when those columns are themselves smooth maps the residuals are forced to be rough. Their Moran’s I has a lower mean under the null, and a test centred on the raw-data value then rejects too rarely. Cliff and Ord (1972) worked out the mean and variance of I for least squares residuals, and <code>spdep</code> ships that version as <code>lm.morantest()</code>. None of this is new. What this post adds is a measurement of how much the difference matters once the model carries several spatial predictors.</p>
<p>Three posts on this site run the raw-data null on residuals. <a href="https://tidyecology.com/posts/spatial-autocorrelation-morans-i/">Spatial autocorrelation and Moran’s I in R</a> tests the residuals of a one-predictor and a two-predictor model with <code>moran.mc(residuals(m1), lw, nsim = 999)</code>, shows <code>lm.morantest()</code> beside it, and closes by recommending the permutation test over the normal approximation for irregular points. <a href="https://tidyecology.com/posts/moran-eigenvector-spatial-filtering/">Moran eigenvector spatial filtering</a> writes its own <code>moran_test()</code> with <code>EI &lt;- -1 / (n - 1)</code> and uses it as the stopping rule for forward selection of up to 25 maps or tied sets of maps; the rule is applied to the residuals of <code>lm(y ~ x + maps)</code> on Poisson counts, while the reported diagnostic uses Pearson residuals of the Poisson GLM. <a href="https://tidyecology.com/posts/checking-a-spatial-regression/">Checking a spatial regression</a> reuses the same function and the same loop. The first post is where the difference is smallest, with one or two predictors; the second and third are where it is largest. <a href="https://tidyecology.com/posts/permutation-nulls-that-keep-the-map/">Permutation nulls that keep the map</a> found a site shuffle rejecting too often when it tests the association of two smooth maps; on residuals the shuffle errs the other way.</p>
<div class="cell">
<div class="code-copy-outer-scaffold"><div class="sourceCode cell-code" id="cb1" style="background: #f1f3f5;"><pre class="sourceCode r code-with-copy"><code class="sourceCode r"><span id="cb1-1"><span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">library</span>(spdep)</span>
<span id="cb1-2"><span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">library</span>(ggplot2)</span>
<span id="cb1-3"></span>
<span id="cb1-4">te_paper  <span class="ot" style="color: #003B4F;
background-color: null;
font-style: inherit;">&lt;-</span> <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"#f5f4ee"</span></span>
<span id="cb1-5">te_ink    <span class="ot" style="color: #003B4F;
background-color: null;
font-style: inherit;">&lt;-</span> <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"#16241d"</span></span>
<span id="cb1-6">te_body   <span class="ot" style="color: #003B4F;
background-color: null;
font-style: inherit;">&lt;-</span> <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"#2c3a31"</span></span>
<span id="cb1-7">te_forest <span class="ot" style="color: #003B4F;
background-color: null;
font-style: inherit;">&lt;-</span> <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"#275139"</span></span>
<span id="cb1-8">te_rust   <span class="ot" style="color: #003B4F;
background-color: null;
font-style: inherit;">&lt;-</span> <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"#b5534e"</span></span>
<span id="cb1-9">te_gold   <span class="ot" style="color: #003B4F;
background-color: null;
font-style: inherit;">&lt;-</span> <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"#c9b458"</span></span>
<span id="cb1-10">te_line   <span class="ot" style="color: #003B4F;
background-color: null;
font-style: inherit;">&lt;-</span> <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"#dad9ca"</span></span>
<span id="cb1-11"></span>
<span id="cb1-12">theme_datasheet <span class="ot" style="color: #003B4F;
background-color: null;
font-style: inherit;">&lt;-</span> <span class="cf" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">function</span>() {</span>
<span id="cb1-13">  <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">theme_minimal</span>(<span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">base_size =</span> <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">12</span>) <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">+</span></span>
<span id="cb1-14">    <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">theme</span>(<span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">plot.background  =</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">element_rect</span>(<span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">fill =</span> te_paper, <span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">colour =</span> <span class="cn" style="color: #8f5902;
background-color: null;
font-style: inherit;">NA</span>),</span>
<span id="cb1-15">          <span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">panel.background =</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">element_rect</span>(<span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">fill =</span> te_paper, <span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">colour =</span> <span class="cn" style="color: #8f5902;
background-color: null;
font-style: inherit;">NA</span>),</span>
<span id="cb1-16">          <span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">panel.grid.major =</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">element_line</span>(<span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">colour =</span> te_line, <span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">linewidth =</span> <span class="fl" style="color: #AD0000;
background-color: null;
font-style: inherit;">0.3</span>),</span>
<span id="cb1-17">          <span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">panel.grid.minor =</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">element_blank</span>(),</span>
<span id="cb1-18">          <span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">text             =</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">element_text</span>(<span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">colour =</span> te_body),</span>
<span id="cb1-19">          <span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">plot.title       =</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">element_text</span>(<span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">colour =</span> te_ink, <span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">face =</span> <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"bold"</span>),</span>
<span id="cb1-20">          <span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">plot.subtitle    =</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">element_text</span>(<span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">colour =</span> te_body),</span>
<span id="cb1-21">          <span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">axis.text        =</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">element_text</span>(<span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">colour =</span> te_body))</span>
<span id="cb1-22">}</span></code></pre></div></div>
</div>
<section id="one-plot-layout-one-graph-a-set-of-maps" class="level2">
<h2 id="one-plot-layout-one-graph-a-set-of-maps-h" class="anchored" data-anchor-id="one-plot-layout-one-graph-a-set-of-maps">One plot layout, one graph, a set of maps</h2>
<p>The plots are placed uniformly at random in a ten by ten kilometre square. Each plot is joined to its six nearest neighbours, the graph is made symmetric, and the weights are row standardised, which is the <code>style = "W"</code> default of most ecological scripts. The Moran eigenvector maps are the eigenvectors of the doubly centred binary adjacency matrix (Dray, Legendre and Peres-Neto 2006), built as in the eigenvector filtering post and sorted from the broadest pattern down. The plot-level covariate is drawn without any spatial structure.</p>
<div class="cell">
<div class="code-copy-outer-scaffold"><div class="sourceCode cell-code" id="cb2" style="background: #f1f3f5;"><pre class="sourceCode r code-with-copy"><code class="sourceCode r"><span id="cb2-1">n_plot <span class="ot" style="color: #003B4F;
background-color: null;
font-style: inherit;">&lt;-</span> <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">150</span></span>
<span id="cb2-2">k_nn   <span class="ot" style="color: #003B4F;
background-color: null;
font-style: inherit;">&lt;-</span> <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">6</span></span>
<span id="cb2-3"><span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">set.seed</span>(<span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">4102</span>)</span>
<span id="cb2-4">plot_xy <span class="ot" style="color: #003B4F;
background-color: null;
font-style: inherit;">&lt;-</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">cbind</span>(<span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">east =</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">runif</span>(n_plot, <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">0</span>, <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">10</span>), <span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">north =</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">runif</span>(n_plot, <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">0</span>, <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">10</span>))</span>
<span id="cb2-5">nb_knn  <span class="ot" style="color: #003B4F;
background-color: null;
font-style: inherit;">&lt;-</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">make.sym.nb</span>(<span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">knn2nb</span>(<span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">knearneigh</span>(plot_xy, <span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">k =</span> k_nn)))</span>
<span id="cb2-6">lw_knn  <span class="ot" style="color: #003B4F;
background-color: null;
font-style: inherit;">&lt;-</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">nb2listw</span>(nb_knn, <span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">style =</span> <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"W"</span>)</span>
<span id="cb2-7">w_mat   <span class="ot" style="color: #003B4F;
background-color: null;
font-style: inherit;">&lt;-</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">listw2mat</span>(lw_knn)</span>
<span id="cb2-8">u_mat   <span class="ot" style="color: #003B4F;
background-color: null;
font-style: inherit;">&lt;-</span> (w_mat <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">+</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">t</span>(w_mat)) <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">/</span> <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">2</span></span>
<span id="cb2-9">b_mat   <span class="ot" style="color: #003B4F;
background-color: null;
font-style: inherit;">&lt;-</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">nb2mat</span>(nb_knn, <span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">style =</span> <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"B"</span>)</span>
<span id="cb2-10">cen_mat <span class="ot" style="color: #003B4F;
background-color: null;
font-style: inherit;">&lt;-</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">diag</span>(n_plot) <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">-</span> <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">1</span> <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">/</span> n_plot</span>
<span id="cb2-11">mem_eig <span class="ot" style="color: #003B4F;
background-color: null;
font-style: inherit;">&lt;-</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">eigen</span>(cen_mat <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">%*%</span> b_mat <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">%*%</span> cen_mat, <span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">symmetric =</span> <span class="cn" style="color: #8f5902;
background-color: null;
font-style: inherit;">TRUE</span>)</span>
<span id="cb2-12">mem_all <span class="ot" style="color: #003B4F;
background-color: null;
font-style: inherit;">&lt;-</span> mem_eig<span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">$</span>vectors[, mem_eig<span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">$</span>values <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">&gt;</span> <span class="fl" style="color: #AD0000;
background-color: null;
font-style: inherit;">1e-8</span>]</span>
<span id="cb2-13">mem_moran <span class="ot" style="color: #003B4F;
background-color: null;
font-style: inherit;">&lt;-</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">colSums</span>(mem_all <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">*</span> (w_mat <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">%*%</span> mem_all))</span>
<span id="cb2-14">canopy  <span class="ot" style="color: #003B4F;
background-color: null;
font-style: inherit;">&lt;-</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">rnorm</span>(n_plot)</span>
<span id="cb2-15"><span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">stopifnot</span>(<span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">abs</span>(<span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">sum</span>(w_mat) <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">-</span> n_plot) <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">&lt;</span> <span class="fl" style="color: #AD0000;
background-color: null;
font-style: inherit;">1e-9</span>)</span>
<span id="cb2-16"></span>
<span id="cb2-17">design_mem <span class="ot" style="color: #003B4F;
background-color: null;
font-style: inherit;">&lt;-</span> <span class="cf" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">function</span>(n_map) <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">cbind</span>(<span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">1</span>, canopy, mem_all[, <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">seq_len</span>(n_map)])</span>
<span id="cb2-18">n_link  <span class="ot" style="color: #003B4F;
background-color: null;
font-style: inherit;">&lt;-</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">sum</span>(<span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">card</span>(nb_knn))</span>
<span id="cb2-19">n_pos   <span class="ot" style="color: #003B4F;
background-color: null;
font-style: inherit;">&lt;-</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">ncol</span>(mem_all)</span></code></pre></div></div>
</div>
<p>The symmetric graph has 1086 directed links, between 6 and 13 neighbours per plot, and 49 maps with positive eigenvalues. The broadest map has a Moran’s I of 0.96 under the row standardised weights, and the sixteenth 0.63.</p>
</section>
<section id="the-residual-null-has-its-own-mean" class="level2">
<h2 id="the-residual-null-has-its-own-mean-h" class="anchored" data-anchor-id="the-residual-null-has-its-own-mean">The residual null has its own mean</h2>
<p>With row standardised weights the sum of all weights equals n, and Moran’s I of a centred vector e is simply <code>I = e'We / e'e</code>. For least squares residuals, <code>e = M y</code> with <code>M = I - X (X'X)^-1 X'</code>, and under the null of independent normal errors e is <code>M</code> times a spherical normal vector. The ratio <code>e'We / e'e</code> is then independent of its denominator, so its mean is the ratio of the two means, and with <code>tr(M) = n - k</code> that gives</p>
<p><code>E[I] = tr(M W) / (n - k)</code>,</p>
<p>where k is the number of columns of X. This is the Cliff and Ord expectation, and it is what <code>lm.morantest()</code> reports as “Expectation”. Two special cases make it readable. The weights have a zero diagonal, so <code>tr(W) = 0</code> and <code>tr(M W) = -tr(H W)</code>, with H the hat matrix. Writing H through an orthonormal basis of the columns of X, <code>tr(H W)</code> is the sum of <code>q'Wq</code> over the basis vectors: the intercept column contributes exactly one, which with k = 1 gives the familiar minus one over (n minus one). Every other column contributes its own Moran-type autocorrelation. For a design of the intercept and m eigenvector maps, which are orthonormal and orthogonal to the intercept, the expectation is <code>-(1 + I_1 + ... + I_m) / (n - 1 - m)</code>, where <code>I_j</code> is the Moran’s I of map j. Adding one more map lowers the expected residual I by about its own Moran’s I divided by (n - k) (exactly, by its Moran’s I minus the current expectation, divided by n - k - 1), which for the broadest maps is close to one over (n - k); a column with no spatial structure moves it by next to nothing.</p>
<div class="cell">
<div class="code-copy-outer-scaffold"><div class="sourceCode cell-code" id="cb3" style="background: #f1f3f5;"><pre class="sourceCode r code-with-copy"><code class="sourceCode r"><span id="cb3-1">res_null <span class="ot" style="color: #003B4F;
background-color: null;
font-style: inherit;">&lt;-</span> <span class="cf" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">function</span>(X) {</span>
<span id="cb3-2">  k_col <span class="ot" style="color: #003B4F;
background-color: null;
font-style: inherit;">&lt;-</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">ncol</span>(X)</span>
<span id="cb3-3">  m_mat <span class="ot" style="color: #003B4F;
background-color: null;
font-style: inherit;">&lt;-</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">diag</span>(n_plot) <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">-</span> X <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">%*%</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">solve</span>(<span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">crossprod</span>(X), <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">t</span>(X))</span>
<span id="cb3-4">  mu    <span class="ot" style="color: #003B4F;
background-color: null;
font-style: inherit;">&lt;-</span> m_mat <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">%*%</span> u_mat</span>
<span id="cb3-5">  e_res <span class="ot" style="color: #003B4F;
background-color: null;
font-style: inherit;">&lt;-</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">sum</span>(<span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">diag</span>(mu)) <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">/</span> (n_plot <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">-</span> k_col)</span>
<span id="cb3-6">  v_res <span class="ot" style="color: #003B4F;
background-color: null;
font-style: inherit;">&lt;-</span> (<span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">2</span> <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">*</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">sum</span>(mu <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">*</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">t</span>(mu)) <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">+</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">sum</span>(<span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">diag</span>(mu))<span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">^</span><span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">2</span>) <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">/</span></span>
<span id="cb3-7">    ((n_plot <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">-</span> k_col) <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">*</span> (n_plot <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">-</span> k_col <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">+</span> <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">2</span>)) <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">-</span> e_res<span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">^</span><span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">2</span></span>
<span id="cb3-8">  <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">list</span>(<span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">m_mat =</span> m_mat, <span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">e_res =</span> e_res, <span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">v_res =</span> v_res, <span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">k_col =</span> k_col)</span>
<span id="cb3-9">}</span>
<span id="cb3-10">e_raw <span class="ot" style="color: #003B4F;
background-color: null;
font-style: inherit;">&lt;-</span> <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">-</span><span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">1</span> <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">/</span> (n_plot <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">-</span> <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">1</span>)</span>
<span id="cb3-11">s0 <span class="ot" style="color: #003B4F;
background-color: null;
font-style: inherit;">&lt;-</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">sum</span>(w_mat); s1 <span class="ot" style="color: #003B4F;
background-color: null;
font-style: inherit;">&lt;-</span> <span class="fl" style="color: #AD0000;
background-color: null;
font-style: inherit;">0.5</span> <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">*</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">sum</span>((w_mat <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">+</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">t</span>(w_mat))<span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">^</span><span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">2</span>)</span>
<span id="cb3-12">s2 <span class="ot" style="color: #003B4F;
background-color: null;
font-style: inherit;">&lt;-</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">sum</span>((<span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">rowSums</span>(w_mat) <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">+</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">colSums</span>(w_mat))<span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">^</span><span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">2</span>)</span>
<span id="cb3-13">v_raw <span class="ot" style="color: #003B4F;
background-color: null;
font-style: inherit;">&lt;-</span> <span class="cf" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">function</span>(b2) {</span>
<span id="cb3-14">  nn <span class="ot" style="color: #003B4F;
background-color: null;
font-style: inherit;">&lt;-</span> n_plot</span>
<span id="cb3-15">  (nn <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">*</span> ((nn<span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">^</span><span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">2</span> <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">-</span> <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">3</span> <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">*</span> nn <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">+</span> <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">3</span>) <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">*</span> s1 <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">-</span> nn <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">*</span> s2 <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">+</span> <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">3</span> <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">*</span> s0<span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">^</span><span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">2</span>) <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">-</span></span>
<span id="cb3-16">     b2 <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">*</span> ((nn<span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">^</span><span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">2</span> <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">-</span> nn) <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">*</span> s1 <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">-</span> <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">2</span> <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">*</span> nn <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">*</span> s2 <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">+</span> <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">6</span> <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">*</span> s0<span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">^</span><span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">2</span>)) <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">/</span></span>
<span id="cb3-17">    ((nn <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">-</span> <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">1</span>) <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">*</span> (nn <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">-</span> <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">2</span>) <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">*</span> (nn <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">-</span> <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">3</span>) <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">*</span> s0<span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">^</span><span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">2</span>) <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">-</span> e_raw<span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">^</span><span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">2</span></span>
<span id="cb3-18">}</span>
<span id="cb3-19">moran_cols <span class="ot" style="color: #003B4F;
background-color: null;
font-style: inherit;">&lt;-</span> <span class="cf" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">function</span>(r_mat) <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">colSums</span>(r_mat <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">*</span> (w_mat <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">%*%</span> r_mat)) <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">/</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">colSums</span>(r_mat<span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">^</span><span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">2</span>)</span>
<span id="cb3-20"></span>
<span id="cb3-21"><span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">set.seed</span>(<span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">611</span>); y_chk <span class="ot" style="color: #003B4F;
background-color: null;
font-style: inherit;">&lt;-</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">rnorm</span>(n_plot)</span>
<span id="cb3-22">x_chk   <span class="ot" style="color: #003B4F;
background-color: null;
font-style: inherit;">&lt;-</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">design_mem</span>(<span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">8</span>)</span>
<span id="cb3-23">fit_chk <span class="ot" style="color: #003B4F;
background-color: null;
font-style: inherit;">&lt;-</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">lm</span>(y_chk <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">~</span> x_chk <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">-</span> <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">1</span>); r_chk <span class="ot" style="color: #003B4F;
background-color: null;
font-style: inherit;">&lt;-</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">residuals</span>(fit_chk)</span>
<span id="cb3-24">lmt_chk <span class="ot" style="color: #003B4F;
background-color: null;
font-style: inherit;">&lt;-</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">lm.morantest</span>(fit_chk, lw_knn); mt_chk <span class="ot" style="color: #003B4F;
background-color: null;
font-style: inherit;">&lt;-</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">moran.test</span>(r_chk, lw_knn)</span>
<span id="cb3-25">nul_chk <span class="ot" style="color: #003B4F;
background-color: null;
font-style: inherit;">&lt;-</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">res_null</span>(x_chk)</span>
<span id="cb3-26">b2_chk  <span class="ot" style="color: #003B4F;
background-color: null;
font-style: inherit;">&lt;-</span> n_plot <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">*</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">sum</span>(r_chk<span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">^</span><span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">4</span>) <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">/</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">sum</span>(r_chk<span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">^</span><span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">2</span>)<span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">^</span><span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">2</span></span>
<span id="cb3-27">est_l <span class="ot" style="color: #003B4F;
background-color: null;
font-style: inherit;">&lt;-</span> lmt_chk<span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">$</span>estimate; est_m <span class="ot" style="color: #003B4F;
background-color: null;
font-style: inherit;">&lt;-</span> mt_chk<span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">$</span>estimate</span>
<span id="cb3-28"><span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">stopifnot</span>(<span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">abs</span>(est_l[[<span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"Expectation"</span>]] <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">-</span> nul_chk<span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">$</span>e_res) <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">&lt;</span> <span class="fl" style="color: #AD0000;
background-color: null;
font-style: inherit;">1e-12</span>, <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">abs</span>(est_l[[<span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"Variance"</span>]] <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">-</span> nul_chk<span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">$</span>v_res) <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">&lt;</span> <span class="fl" style="color: #AD0000;
background-color: null;
font-style: inherit;">1e-12</span>,</span>
<span id="cb3-29">  <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">abs</span>(est_m[[<span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"Expectation"</span>]] <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">-</span> e_raw) <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">&lt;</span> <span class="fl" style="color: #AD0000;
background-color: null;
font-style: inherit;">1e-15</span>, <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">abs</span>(est_m[[<span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"Variance"</span>]] <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">-</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">v_raw</span>(b2_chk)) <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">&lt;</span> <span class="fl" style="color: #AD0000;
background-color: null;
font-style: inherit;">1e-12</span>,</span>
<span id="cb3-30">  <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">abs</span>(est_l[[<span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"Observed Moran I"</span>]] <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">-</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">moran_cols</span>(<span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">matrix</span>(r_chk))) <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">&lt;</span> <span class="fl" style="color: #AD0000;
background-color: null;
font-style: inherit;">1e-12</span>,</span>
<span id="cb3-31">  <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">isTRUE</span>(<span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">formals</span>(moran.test)<span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">$</span>randomisation), <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">identical</span>(<span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">formals</span>(moran.test)<span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">$</span>alternative, <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"greater"</span>),</span>
<span id="cb3-32">  <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">identical</span>(<span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">formals</span>(lm.morantest)<span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">$</span>alternative, <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"greater"</span>))</span>
<span id="cb3-33"></span>
<span id="cb3-34">x_only   <span class="ot" style="color: #003B4F;
background-color: null;
font-style: inherit;">&lt;-</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">cbind</span>(<span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">1</span>, mem_all[, <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">1</span><span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">:</span><span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">16</span>])</span>
<span id="cb3-35">e_decomp <span class="ot" style="color: #003B4F;
background-color: null;
font-style: inherit;">&lt;-</span> <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">-</span>(<span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">1</span> <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">+</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">sum</span>(mem_moran[<span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">1</span><span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">:</span><span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">16</span>])) <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">/</span> (n_plot <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">-</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">ncol</span>(x_only))</span>
<span id="cb3-36">e_plus17 <span class="ot" style="color: #003B4F;
background-color: null;
font-style: inherit;">&lt;-</span> e_decomp <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">-</span> (mem_moran[<span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">17</span>] <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">-</span> e_decomp) <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">/</span> (n_plot <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">-</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">ncol</span>(x_only) <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">-</span> <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">1</span>)</span>
<span id="cb3-37"><span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">stopifnot</span>(<span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">abs</span>(<span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">res_null</span>(x_only)<span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">$</span>e_res <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">-</span> e_decomp) <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">&lt;</span> <span class="fl" style="color: #AD0000;
background-color: null;
font-style: inherit;">1e-12</span>,</span>
<span id="cb3-38">          <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">abs</span>(<span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">res_null</span>(<span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">cbind</span>(x_only, mem_all[, <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">17</span>]))<span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">$</span>e_res <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">-</span> e_plus17) <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">&lt;</span> <span class="fl" style="color: #AD0000;
background-color: null;
font-style: inherit;">1e-12</span>)</span>
<span id="cb3-39">spdep_ver <span class="ot" style="color: #003B4F;
background-color: null;
font-style: inherit;">&lt;-</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">as.character</span>(<span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">packageVersion</span>(<span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"spdep"</span>))</span></code></pre></div></div>
</div>
<p>The chunk checks the hand version against <code>spdep</code> 1.4.2 to machine precision: on one fitted model with eight maps, <code>lm.morantest()</code> reports an expectation of -0.0598, identical to the trace formula, while <code>moran.test()</code> on the same residuals reports -0.0067, the raw-data value, whatever the vector is. The decomposition matches as well: for the intercept and the first sixteen maps alone, without the covariate, it gives -0.1078 from the sum of the maps’ own Moran’s I, and adding a seventeenth map moves it by exactly the increment above. The <code>stopifnot()</code> line also records the defaults this post relies on, <code>randomisation = TRUE</code> and a one-sided alternative of <code>"greater"</code> in both functions; they are the same in the current development source of <code>spdep</code> (version 1.4-3 on GitHub), where the expectation line of <code>moran.test()</code> is still <code>EI &lt;- (-1) / wc$n1</code>.</p>
<div class="cell">
<div class="code-copy-outer-scaffold"><div class="sourceCode cell-code" id="cb4" style="background: #f1f3f5;"><pre class="sourceCode r code-with-copy"><code class="sourceCode r"><span id="cb4-1">map_grid <span class="ot" style="color: #003B4F;
background-color: null;
font-style: inherit;">&lt;-</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">c</span>(<span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">0</span>, <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">2</span>, <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">4</span>, <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">8</span>, <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">12</span>, <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">16</span>)</span>
<span id="cb4-2">n_rep    <span class="ot" style="color: #003B4F;
background-color: null;
font-style: inherit;">&lt;-</span> <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">4000</span></span>
<span id="cb4-3"><span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">set.seed</span>(<span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">8830</span>)</span>
<span id="cb4-4">eps_null <span class="ot" style="color: #003B4F;
background-color: null;
font-style: inherit;">&lt;-</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">matrix</span>(<span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">rnorm</span>(n_plot <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">*</span> n_rep), n_plot)</span>
<span id="cb4-5">noise_cols <span class="ot" style="color: #003B4F;
background-color: null;
font-style: inherit;">&lt;-</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">matrix</span>(<span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">rnorm</span>(n_plot <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">*</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">max</span>(map_grid)), n_plot)</span>
<span id="cb4-6">trend_deg  <span class="ot" style="color: #003B4F;
background-color: null;
font-style: inherit;">&lt;-</span> <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">1</span><span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">:</span><span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">4</span></span>
<span id="cb4-7"></span>
<span id="cb4-8">fam_row <span class="ot" style="color: #003B4F;
background-color: null;
font-style: inherit;">&lt;-</span> <span class="cf" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">function</span>(X, family, n_extra) {</span>
<span id="cb4-9">  nul   <span class="ot" style="color: #003B4F;
background-color: null;
font-style: inherit;">&lt;-</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">res_null</span>(X)</span>
<span id="cb4-10">  i_sim <span class="ot" style="color: #003B4F;
background-color: null;
font-style: inherit;">&lt;-</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">moran_cols</span>(nul<span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">$</span>m_mat <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">%*%</span> eps_null)</span>
<span id="cb4-11">  <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">data.frame</span>(<span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">family =</span> family, <span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">n_extra =</span> n_extra, <span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">e_res =</span> nul<span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">$</span>e_res,</span>
<span id="cb4-12">             <span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">sim_mean =</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">mean</span>(i_sim), <span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">sim_se =</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">sd</span>(i_sim) <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">/</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">sqrt</span>(n_rep))</span>
<span id="cb4-13">}</span>
<span id="cb4-14">fam_tab <span class="ot" style="color: #003B4F;
background-color: null;
font-style: inherit;">&lt;-</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">rbind</span>(</span>
<span id="cb4-15">  <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">do.call</span>(rbind, <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">lapply</span>(map_grid, <span class="cf" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">function</span>(m) <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">fam_row</span>(<span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">design_mem</span>(m), <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"eigenvector maps"</span>, m))),</span>
<span id="cb4-16">  <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">do.call</span>(rbind, <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">lapply</span>(map_grid, <span class="cf" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">function</span>(m)</span>
<span id="cb4-17">    <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">fam_row</span>(<span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">cbind</span>(<span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">1</span>, canopy, noise_cols[, <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">seq_len</span>(m)]), <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"unstructured covariates"</span>, m))),</span>
<span id="cb4-18">  <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">do.call</span>(rbind, <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">lapply</span>(trend_deg, <span class="cf" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">function</span>(d)</span>
<span id="cb4-19">    <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">fam_row</span>(<span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">cbind</span>(<span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">1</span>, canopy, <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">poly</span>(plot_xy[, <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">1</span>], plot_xy[, <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">2</span>], <span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">degree =</span> d)),</span>
<span id="cb4-20">            <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"trend surface"</span>, d <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">*</span> (d <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">+</span> <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">3</span>) <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">/</span> <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">2</span>))))</span>
<span id="cb4-21">fam_z   <span class="ot" style="color: #003B4F;
background-color: null;
font-style: inherit;">&lt;-</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">max</span>(<span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">abs</span>(fam_tab<span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">$</span>sim_mean <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">-</span> fam_tab<span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">$</span>e_res) <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">/</span> fam_tab<span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">$</span>sim_se)</span>
<span id="cb4-22">e_map16 <span class="ot" style="color: #003B4F;
background-color: null;
font-style: inherit;">&lt;-</span> fam_tab<span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">$</span>e_res[fam_tab<span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">$</span>family <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">==</span> <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"eigenvector maps"</span> <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">&amp;</span> fam_tab<span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">$</span>n_extra <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">==</span> <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">16</span>]</span>
<span id="cb4-23">e_noi16 <span class="ot" style="color: #003B4F;
background-color: null;
font-style: inherit;">&lt;-</span> fam_tab<span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">$</span>e_res[fam_tab<span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">$</span>family <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">==</span> <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"unstructured covariates"</span> <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">&amp;</span> fam_tab<span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">$</span>n_extra <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">==</span> <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">16</span>]</span>
<span id="cb4-24">e_tr14  <span class="ot" style="color: #003B4F;
background-color: null;
font-style: inherit;">&lt;-</span> fam_tab<span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">$</span>e_res[fam_tab<span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">$</span>family <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">==</span> <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"trend surface"</span> <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">&amp;</span> fam_tab<span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">$</span>n_extra <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">==</span> <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">14</span>]</span>
<span id="cb4-25">sd_raw  <span class="ot" style="color: #003B4F;
background-color: null;
font-style: inherit;">&lt;-</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">sqrt</span>(<span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">v_raw</span>(<span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">3</span>)); shift_sd <span class="ot" style="color: #003B4F;
background-color: null;
font-style: inherit;">&lt;-</span> (e_raw <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">-</span> e_map16) <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">/</span> sd_raw</span>
<span id="cb4-26"></span>
<span id="cb4-27">n_layout <span class="ot" style="color: #003B4F;
background-color: null;
font-style: inherit;">&lt;-</span> <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">20</span>; <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">set.seed</span>(<span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">2213</span>)</span>
<span id="cb4-28">layout_e <span class="ot" style="color: #003B4F;
background-color: null;
font-style: inherit;">&lt;-</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">vapply</span>(<span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">seq_len</span>(n_layout), <span class="cf" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">function</span>(i) {</span>
<span id="cb4-29">  xy_i <span class="ot" style="color: #003B4F;
background-color: null;
font-style: inherit;">&lt;-</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">cbind</span>(<span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">runif</span>(n_plot, <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">0</span>, <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">10</span>), <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">runif</span>(n_plot, <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">0</span>, <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">10</span>))</span>
<span id="cb4-30">  nb_i <span class="ot" style="color: #003B4F;
background-color: null;
font-style: inherit;">&lt;-</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">make.sym.nb</span>(<span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">knn2nb</span>(<span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">knearneigh</span>(xy_i, <span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">k =</span> k_nn)))</span>
<span id="cb4-31">  w_i  <span class="ot" style="color: #003B4F;
background-color: null;
font-style: inherit;">&lt;-</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">listw2mat</span>(<span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">nb2listw</span>(nb_i, <span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">style =</span> <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"W"</span>))</span>
<span id="cb4-32">  b_i  <span class="ot" style="color: #003B4F;
background-color: null;
font-style: inherit;">&lt;-</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">nb2mat</span>(nb_i, <span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">style =</span> <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"B"</span>)</span>
<span id="cb4-33">  ev_i <span class="ot" style="color: #003B4F;
background-color: null;
font-style: inherit;">&lt;-</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">eigen</span>(cen_mat <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">%*%</span> b_i <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">%*%</span> cen_mat, <span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">symmetric =</span> <span class="cn" style="color: #8f5902;
background-color: null;
font-style: inherit;">TRUE</span>)<span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">$</span>vectors[, <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">1</span><span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">:</span><span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">16</span>]</span>
<span id="cb4-34">  x_i  <span class="ot" style="color: #003B4F;
background-color: null;
font-style: inherit;">&lt;-</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">cbind</span>(<span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">1</span>, <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">rnorm</span>(n_plot), ev_i)</span>
<span id="cb4-35">  m_i  <span class="ot" style="color: #003B4F;
background-color: null;
font-style: inherit;">&lt;-</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">diag</span>(n_plot) <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">-</span> x_i <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">%*%</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">solve</span>(<span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">crossprod</span>(x_i), <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">t</span>(x_i))</span>
<span id="cb4-36">  <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">sum</span>(<span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">diag</span>(m_i <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">%*%</span> w_i)) <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">/</span> (n_plot <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">-</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">ncol</span>(x_i))</span>
<span id="cb4-37">}, <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">numeric</span>(<span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">1</span>))</span></code></pre></div></div>
</div>
<p>Three families of extra columns were added to the intercept and the covariate: the broadest eigenvector maps, the terms of a polynomial trend surface in the coordinates of degree one to four, and columns of pure noise. Over 4000 null datasets the simulated mean of the residual I agrees with the trace formula in every design, to within 1.1 Monte Carlo standard errors at worst. With sixteen maps the expectation is -0.1076, against -0.0067 for raw data; a quartic trend surface with fourteen terms gives -0.0774; sixteen noise columns give -0.0053. The gap between the sixteen-map value and the raw-data value is 2.4 times the standard deviation that <code>moran.test()</code> itself attaches to I for normal data, so the shift is large against the spread of the null, not a detail of its centre. Across 20 further random layouts of the same size and graph, the sixteen-map expectation ranges from -0.1115 to -0.1066.</p>
<div class="cell">
<div class="code-copy-outer-scaffold"><div class="sourceCode cell-code" id="cb5" style="background: #f1f3f5;"><pre class="sourceCode r code-with-copy"><code class="sourceCode r"><span id="cb5-1">fam_plot <span class="ot" style="color: #003B4F;
background-color: null;
font-style: inherit;">&lt;-</span> fam_tab</span>
<span id="cb5-2">fam_plot<span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">$</span>family <span class="ot" style="color: #003B4F;
background-color: null;
font-style: inherit;">&lt;-</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">factor</span>(fam_plot<span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">$</span>family,</span>
<span id="cb5-3">  <span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">levels =</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">c</span>(<span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"unstructured covariates"</span>, <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"trend surface"</span>, <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"eigenvector maps"</span>))</span>
<span id="cb5-4"><span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">ggplot</span>(fam_plot, <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">aes</span>(n_extra, e_res, <span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">colour =</span> family)) <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">+</span></span>
<span id="cb5-5">  <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">geom_hline</span>(<span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">yintercept =</span> e_raw, <span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">linetype =</span> <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"dashed"</span>, <span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">colour =</span> te_body, <span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">linewidth =</span> <span class="fl" style="color: #AD0000;
background-color: null;
font-style: inherit;">0.6</span>) <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">+</span></span>
<span id="cb5-6">  <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">geom_line</span>(<span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">linewidth =</span> <span class="fl" style="color: #AD0000;
background-color: null;
font-style: inherit;">0.9</span>) <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">+</span></span>
<span id="cb5-7">  <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">geom_point</span>(<span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">aes</span>(<span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">y =</span> sim_mean), <span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">size =</span> <span class="fl" style="color: #AD0000;
background-color: null;
font-style: inherit;">2.4</span>) <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">+</span></span>
<span id="cb5-8">  <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">annotate</span>(<span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"text"</span>, <span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">x =</span> <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">16</span>, <span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">y =</span> e_raw, <span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">vjust =</span> <span class="fl" style="color: #AD0000;
background-color: null;
font-style: inherit;">1.8</span>, <span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">hjust =</span> <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">1</span>, <span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">size =</span> <span class="fl" style="color: #AD0000;
background-color: null;
font-style: inherit;">3.4</span>,</span>
<span id="cb5-9">           <span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">colour =</span> te_body, <span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">label =</span> <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"moran.test: -1/(n - 1)"</span>) <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">+</span></span>
<span id="cb5-10">  <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">scale_colour_manual</span>(<span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">values =</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">c</span>(te_gold, te_forest, te_rust), <span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">name =</span> <span class="cn" style="color: #8f5902;
background-color: null;
font-style: inherit;">NULL</span>) <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">+</span></span>
<span id="cb5-11">  <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">scale_x_continuous</span>(<span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">breaks =</span> map_grid) <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">+</span></span>
<span id="cb5-12">  <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">labs</span>(<span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">x =</span> <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"extra columns in the model (beyond intercept and covariate)"</span>,</span>
<span id="cb5-13">       <span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">y =</span> <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"expected residual Moran's I"</span>,</span>
<span id="cb5-14">       <span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">title =</span> <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"Smooth predictors pull the residual null down"</span>,</span>
<span id="cb5-15">       <span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">subtitle =</span> <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"150 plots, symmetric 6-nearest-neighbour graph, row standardised"</span>) <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">+</span></span>
<span id="cb5-16">  <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">theme_datasheet</span>() <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">+</span></span>
<span id="cb5-17">  <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">theme</span>(<span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">legend.position =</span> <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"bottom"</span>)</span></code></pre></div></div>
<div class="cell-output-display">
<div id="fig-expectation" class="quarto-float quarto-figure quarto-figure-center anchored" alt="A line chart on warm off-white paper. The horizontal axis is the number of extra columns in the model from 0 to 16, the vertical axis the expected residual Moran's I from about minus 0.11 to 0. A dashed horizontal line just below zero is labelled moran.test: -1/(n - 1). A gold line for unstructured covariates runs along the dashed line across the whole range. A dark green line for trend surface terms, with points at 2, 5, 9 and 14 columns, starts at about minus 0.02 and falls to about minus 0.077. A red line for eigenvector maps falls almost straight to about minus 0.108 at 16 maps. Round points for the simulated means sit on every line.">
<figure class="quarto-float quarto-float-fig figure">
<div aria-describedby="fig-expectation-caption-0ceaefa1-69ba-4598-a22c-09a6ac19f8ca">
<img src="https://tidyecology.com/posts/morans-i-on-regression-residuals/index_files/figure-html/fig-expectation-1.png" class="img-fluid figure-img" alt="A line chart on warm off-white paper. The horizontal axis is the number of extra columns in the model from 0 to 16, the vertical axis the expected residual Moran's I from about minus 0.11 to 0. A dashed horizontal line just below zero is labelled moran.test: -1/(n - 1). A gold line for unstructured covariates runs along the dashed line across the whole range. A dark green line for trend surface terms, with points at 2, 5, 9 and 14 columns, starts at about minus 0.02 and falls to about minus 0.077. A red line for eigenvector maps falls almost straight to about minus 0.108 at 16 maps. Round points for the simulated means sit on every line." width="672">
</div>
<figcaption class="quarto-float-caption-bottom quarto-float-caption quarto-float-fig" id="fig-expectation-caption-0ceaefa1-69ba-4598-a22c-09a6ac19f8ca">
Figure&nbsp;1: Expected Moran’s I of least squares residuals under no autocorrelation, by the number of extra columns in the model, for three kinds of column. Lines: the trace formula; points: simulated means.
</figcaption>
</figure>
</div>
</div>
</div>
</section>
<section id="what-the-raw-data-null-does-to-size-and-power" class="level2">
<h2 id="what-the-raw-data-null-does-to-size-and-power-h" class="anchored" data-anchor-id="what-the-raw-data-null-does-to-size-and-power">What the raw-data null does to size and power</h2>
<p>A null centred too high, and with many maps also too wide, makes a one-sided test reject too rarely. The simulation below fits the model with zero to sixteen maps and applies three tests to the same residuals: the <code>moran.test()</code> default, the <code>moran.mc()</code> permutation test in the next section, and <code>lm.morantest()</code>. Under the null the errors are independent normal; under the alternative they come from a simultaneous autoregressive error process with a coefficient of <code>0.4</code> on the same weights. The coefficient and the replication of 4000 datasets per cell were fixed before the first run. The residuals do not depend on the regression coefficients, because <code>M X = 0</code>, so only the errors need to be drawn.</p>
<div class="cell">
<div class="code-copy-outer-scaffold"><div class="sourceCode cell-code" id="cb6" style="background: #f1f3f5;"><pre class="sourceCode r code-with-copy"><code class="sourceCode r"><span id="cb6-1">rho_sar <span class="ot" style="color: #003B4F;
background-color: null;
font-style: inherit;">&lt;-</span> <span class="fl" style="color: #AD0000;
background-color: null;
font-style: inherit;">0.4</span></span>
<span id="cb6-2">sar_inv <span class="ot" style="color: #003B4F;
background-color: null;
font-style: inherit;">&lt;-</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">solve</span>(<span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">diag</span>(n_plot) <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">-</span> rho_sar <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">*</span> w_mat)</span>
<span id="cb6-3"><span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">set.seed</span>(<span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">3907</span>)</span>
<span id="cb6-4">eps_sar <span class="ot" style="color: #003B4F;
background-color: null;
font-style: inherit;">&lt;-</span> sar_inv <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">%*%</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">matrix</span>(<span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">rnorm</span>(n_plot <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">*</span> n_rep), n_plot)</span>
<span id="cb6-5"></span>
<span id="cb6-6">rate_cell <span class="ot" style="color: #003B4F;
background-color: null;
font-style: inherit;">&lt;-</span> <span class="cf" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">function</span>(n_map, arm) {</span>
<span id="cb6-7">  nul   <span class="ot" style="color: #003B4F;
background-color: null;
font-style: inherit;">&lt;-</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">res_null</span>(<span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">design_mem</span>(n_map))</span>
<span id="cb6-8">  r_mat <span class="ot" style="color: #003B4F;
background-color: null;
font-style: inherit;">&lt;-</span> nul<span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">$</span>m_mat <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">%*%</span> (<span class="cf" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">if</span> (arm <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">==</span> <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"size"</span>) eps_null <span class="cf" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">else</span> eps_sar)</span>
<span id="cb6-9">  i_obs <span class="ot" style="color: #003B4F;
background-color: null;
font-style: inherit;">&lt;-</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">moran_cols</span>(r_mat)</span>
<span id="cb6-10">  b2    <span class="ot" style="color: #003B4F;
background-color: null;
font-style: inherit;">&lt;-</span> n_plot <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">*</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">colSums</span>(r_mat<span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">^</span><span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">4</span>) <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">/</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">colSums</span>(r_mat<span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">^</span><span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">2</span>)<span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">^</span><span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">2</span></span>
<span id="cb6-11">  p_raw <span class="ot" style="color: #003B4F;
background-color: null;
font-style: inherit;">&lt;-</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">pnorm</span>((i_obs <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">-</span> e_raw) <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">/</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">sqrt</span>(<span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">v_raw</span>(b2)), <span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">lower.tail =</span> <span class="cn" style="color: #8f5902;
background-color: null;
font-style: inherit;">FALSE</span>)</span>
<span id="cb6-12">  p_res <span class="ot" style="color: #003B4F;
background-color: null;
font-style: inherit;">&lt;-</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">pnorm</span>((i_obs <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">-</span> nul<span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">$</span>e_res) <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">/</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">sqrt</span>(nul<span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">$</span>v_res), <span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">lower.tail =</span> <span class="cn" style="color: #8f5902;
background-color: null;
font-style: inherit;">FALSE</span>)</span>
<span id="cb6-13">  <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">list</span>(<span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">tab =</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">data.frame</span>(<span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">n_map =</span> n_map, <span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">arm =</span> arm, <span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">test =</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">c</span>(<span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"moran.test"</span>, <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"lm.morantest"</span>),</span>
<span id="cb6-14">                        <span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">rate =</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">c</span>(<span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">mean</span>(p_raw <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">&lt;</span> <span class="fl" style="color: #AD0000;
background-color: null;
font-style: inherit;">0.05</span>), <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">mean</span>(p_res <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">&lt;</span> <span class="fl" style="color: #AD0000;
background-color: null;
font-style: inherit;">0.05</span>))),</span>
<span id="cb6-15">       <span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">p_raw =</span> p_raw, <span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">p_res =</span> p_res)</span>
<span id="cb6-16">}</span>
<span id="cb6-17">cells <span class="ot" style="color: #003B4F;
background-color: null;
font-style: inherit;">&lt;-</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">expand.grid</span>(<span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">n_map =</span> map_grid, <span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">arm =</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">c</span>(<span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"size"</span>, <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"power"</span>), <span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">stringsAsFactors =</span> <span class="cn" style="color: #8f5902;
background-color: null;
font-style: inherit;">FALSE</span>)</span>
<span id="cb6-18">cell_out <span class="ot" style="color: #003B4F;
background-color: null;
font-style: inherit;">&lt;-</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">lapply</span>(<span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">seq_len</span>(<span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">nrow</span>(cells)), <span class="cf" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">function</span>(i) <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">rate_cell</span>(cells<span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">$</span>n_map[i], cells<span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">$</span>arm[i]))</span>
<span id="cb6-19">rate_tab <span class="ot" style="color: #003B4F;
background-color: null;
font-style: inherit;">&lt;-</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">do.call</span>(rbind, <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">lapply</span>(cell_out, <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">`</span><span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">[[</span><span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">`</span>, <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"tab"</span>))</span>
<span id="cb6-20">rate_tab<span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">$</span>se <span class="ot" style="color: #003B4F;
background-color: null;
font-style: inherit;">&lt;-</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">sqrt</span>(rate_tab<span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">$</span>rate <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">*</span> (<span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">1</span> <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">-</span> rate_tab<span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">$</span>rate) <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">/</span> n_rep)</span>
<span id="cb6-21"></span>
<span id="cb6-22">chk_cell <span class="ot" style="color: #003B4F;
background-color: null;
font-style: inherit;">&lt;-</span> cell_out[[<span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">which</span>(cells<span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">$</span>n_map <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">==</span> <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">8</span> <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">&amp;</span> cells<span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">$</span>arm <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">==</span> <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"power"</span>)]]</span>
<span id="cb6-23">chk_p <span class="ot" style="color: #003B4F;
background-color: null;
font-style: inherit;">&lt;-</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">t</span>(<span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">vapply</span>(<span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">1</span><span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">:</span><span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">5</span>, <span class="cf" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">function</span>(j) { y_j <span class="ot" style="color: #003B4F;
background-color: null;
font-style: inherit;">&lt;-</span> eps_sar[, j]; f_j <span class="ot" style="color: #003B4F;
background-color: null;
font-style: inherit;">&lt;-</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">lm</span>(y_j <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">~</span> x_chk <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">-</span> <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">1</span>)</span>
<span id="cb6-24">  <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">c</span>(<span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">moran.test</span>(<span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">residuals</span>(f_j), lw_knn)<span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">$</span>p.value, <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">lm.morantest</span>(f_j, lw_knn)<span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">$</span>p.value) }, <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">numeric</span>(<span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">2</span>)))</span>
<span id="cb6-25"><span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">stopifnot</span>(<span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">max</span>(<span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">abs</span>(chk_p[, <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">1</span>] <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">-</span> chk_cell<span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">$</span>p_raw[<span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">1</span><span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">:</span><span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">5</span>])) <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">&lt;</span> <span class="fl" style="color: #AD0000;
background-color: null;
font-style: inherit;">1e-10</span>,</span>
<span id="cb6-26">          <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">max</span>(<span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">abs</span>(chk_p[, <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">2</span>] <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">-</span> chk_cell<span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">$</span>p_res[<span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">1</span><span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">:</span><span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">5</span>])) <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">&lt;</span> <span class="fl" style="color: #AD0000;
background-color: null;
font-style: inherit;">1e-10</span>)</span>
<span id="cb6-27"></span>
<span id="cb6-28">get_rate <span class="ot" style="color: #003B4F;
background-color: null;
font-style: inherit;">&lt;-</span> <span class="cf" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">function</span>(m, a, tst) rate_tab<span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">$</span>rate[rate_tab<span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">$</span>n_map <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">==</span> m <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">&amp;</span> rate_tab<span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">$</span>arm <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">==</span> a <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">&amp;</span> rate_tab<span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">$</span>test <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">==</span> tst]</span>
<span id="cb6-29">se_05 <span class="ot" style="color: #003B4F;
background-color: null;
font-style: inherit;">&lt;-</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">sqrt</span>(<span class="fl" style="color: #AD0000;
background-color: null;
font-style: inherit;">0.05</span> <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">*</span> <span class="fl" style="color: #AD0000;
background-color: null;
font-style: inherit;">0.95</span> <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">/</span> n_rep)</span>
<span id="cb6-30">lmt_size <span class="ot" style="color: #003B4F;
background-color: null;
font-style: inherit;">&lt;-</span> rate_tab<span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">$</span>rate[rate_tab<span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">$</span>arm <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">==</span> <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"size"</span> <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">&amp;</span> rate_tab<span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">$</span>test <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">==</span> <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"lm.morantest"</span>]</span>
<span id="cb6-31">nul16 <span class="ot" style="color: #003B4F;
background-color: null;
font-style: inherit;">&lt;-</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">res_null</span>(<span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">design_mem</span>(<span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">16</span>)); r_16 <span class="ot" style="color: #003B4F;
background-color: null;
font-style: inherit;">&lt;-</span> nul16<span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">$</span>m_mat <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">%*%</span> eps_sar; sd_res16 <span class="ot" style="color: #003B4F;
background-color: null;
font-style: inherit;">&lt;-</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">sqrt</span>(nul16<span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">$</span>v_res)</span>
<span id="cb6-32">p_centre <span class="ot" style="color: #003B4F;
background-color: null;
font-style: inherit;">&lt;-</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">pnorm</span>((<span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">moran_cols</span>(r_16) <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">-</span> nul16<span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">$</span>e_res) <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">/</span></span>
<span id="cb6-33">  <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">sqrt</span>(<span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">v_raw</span>(n_plot <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">*</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">colSums</span>(r_16<span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">^</span><span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">4</span>) <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">/</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">colSums</span>(r_16<span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">^</span><span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">2</span>)<span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">^</span><span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">2</span>)), <span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">lower.tail =</span> <span class="cn" style="color: #8f5902;
background-color: null;
font-style: inherit;">FALSE</span>)</span>
<span id="cb6-34">pow_centre <span class="ot" style="color: #003B4F;
background-color: null;
font-style: inherit;">&lt;-</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">mean</span>(p_centre <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">&lt;</span> <span class="fl" style="color: #AD0000;
background-color: null;
font-style: inherit;">0.05</span>)</span></code></pre></div></div>
</div>
<p>The chunk checks the vectorised p-values against five calls each of <code>moran.test()</code> and <code>lm.morantest()</code> on fitted <code>lm</code> objects; they agree to ten decimal places. With no maps in the model the two tests are the same test for practical purposes: 0.057 and 0.057 under the null, 0.894 and 0.894 under the autoregressive errors. With eight maps the <code>moran.test()</code> default rejects a true null in 0.0013 of datasets and detects the autoregressive errors in 0.242; <code>lm.morantest()</code> on the same residuals gives 0.062 and 0.717. With sixteen maps the default rejects 0 of the 4000 null datasets and 4 of the autocorrelated ones, while <code>lm.morantest()</code> gives 0.057 and 0.485. The Monte Carlo standard error of a rate near five per cent is 0.0034, and no larger than 0.0079 for any rate. Two things fall with the number of maps and they should be kept apart. The power of <code>lm.morantest()</code> falls too, from 0.894 to 0.485, because the maps absorb part of the autocorrelation the errors carry: there is less of it left in the residuals to find. That loss is real and no residual test can recover it. The rest of the gap at sixteen maps, from 0.485 down to 0.0010, is the raw-data null, and both of its moments are wrong. Moving only its centre to the residual expectation brings the power back to 0.249; correcting its spread as well, a standard deviation of 0.0422 for normal data against 0.0281 for the residual null, takes it the rest of the way. At that point a residual check with the default test can hardly fail: it passes independent errors and autocorrelated ones alike.</p>
<p>The size of <code>lm.morantest()</code> is a little above five per cent in all six designs, between 0.056 and 0.062. The six rates share the same simulated errors, so they are one measurement, not six, and it sits 1.7 to 3.6 Monte Carlo standard errors above the nominal level. <code>spdep</code> also carries an exact version, <code>lm.morantest.exact()</code>, which computes the null distribution of the ratio of quadratic forms as Tiefelsdorf and Boots (1995) set it out. The chunk below compares both versions with p-values read directly off the 4000 simulated null statistics of the same design.</p>
<div class="cell">
<div class="code-copy-outer-scaffold"><div class="sourceCode cell-code" id="cb7" style="background: #f1f3f5;"><pre class="sourceCode r code-with-copy"><code class="sourceCode r"><span id="cb7-1">n_exact <span class="ot" style="color: #003B4F;
background-color: null;
font-style: inherit;">&lt;-</span> <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">200</span></span>
<span id="cb7-2">exact_cmp <span class="ot" style="color: #003B4F;
background-color: null;
font-style: inherit;">&lt;-</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">do.call</span>(rbind, <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">lapply</span>(<span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">c</span>(<span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">0</span>, <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">16</span>), <span class="cf" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">function</span>(n_map) {</span>
<span id="cb7-3">  x_d   <span class="ot" style="color: #003B4F;
background-color: null;
font-style: inherit;">&lt;-</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">design_mem</span>(n_map)</span>
<span id="cb7-4">  nul   <span class="ot" style="color: #003B4F;
background-color: null;
font-style: inherit;">&lt;-</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">res_null</span>(x_d)</span>
<span id="cb7-5">  i_ref <span class="ot" style="color: #003B4F;
background-color: null;
font-style: inherit;">&lt;-</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">moran_cols</span>(nul<span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">$</span>m_mat <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">%*%</span> eps_null)</span>
<span id="cb7-6">  skew  <span class="ot" style="color: #003B4F;
background-color: null;
font-style: inherit;">&lt;-</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">mean</span>((i_ref <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">-</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">mean</span>(i_ref))<span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">^</span><span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">3</span>) <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">/</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">sd</span>(i_ref)<span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">^</span><span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">3</span></span>
<span id="cb7-7">  <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">data.frame</span>(<span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">n_map =</span> n_map, <span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">skew =</span> skew, <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">t</span>(<span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">vapply</span>(<span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">seq_len</span>(n_exact), <span class="cf" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">function</span>(j) {</span>
<span id="cb7-8">    y_j <span class="ot" style="color: #003B4F;
background-color: null;
font-style: inherit;">&lt;-</span> eps_null[, j]</span>
<span id="cb7-9">    <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">c</span>(<span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">p_exact  =</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">lm.morantest.exact</span>(<span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">lm</span>(y_j <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">~</span> x_d <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">-</span> <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">1</span>), lw_knn)<span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">$</span>p.value,</span>
<span id="cb7-10">      <span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">p_normal =</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">pnorm</span>((i_ref[j] <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">-</span> nul<span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">$</span>e_res) <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">/</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">sqrt</span>(nul<span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">$</span>v_res), <span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">lower.tail =</span> <span class="cn" style="color: #8f5902;
background-color: null;
font-style: inherit;">FALSE</span>),</span>
<span id="cb7-11">      <span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">p_sim    =</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">mean</span>(i_ref[<span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">-</span>j] <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">&gt;=</span> i_ref[j]))</span>
<span id="cb7-12">  }, <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">numeric</span>(<span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">3</span>))))</span>
<span id="cb7-13">}))</span>
<span id="cb7-14">tail_cmp  <span class="ot" style="color: #003B4F;
background-color: null;
font-style: inherit;">&lt;-</span> exact_cmp[exact_cmp<span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">$</span>p_sim <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">&lt;</span> <span class="fl" style="color: #AD0000;
background-color: null;
font-style: inherit;">0.2</span>, ]</span>
<span id="cb7-15">se_tail   <span class="ot" style="color: #003B4F;
background-color: null;
font-style: inherit;">&lt;-</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">sqrt</span>(tail_cmp<span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">$</span>p_sim <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">*</span> (<span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">1</span> <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">-</span> tail_cmp<span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">$</span>p_sim) <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">/</span> (n_rep <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">-</span> <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">1</span>))</span>
<span id="cb7-16">z_exact   <span class="ot" style="color: #003B4F;
background-color: null;
font-style: inherit;">&lt;-</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">max</span>(<span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">abs</span>(tail_cmp<span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">$</span>p_exact <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">-</span> tail_cmp<span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">$</span>p_sim) <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">/</span> se_tail)</span>
<span id="cb7-17">z_norm    <span class="ot" style="color: #003B4F;
background-color: null;
font-style: inherit;">&lt;-</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">max</span>((tail_cmp<span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">$</span>p_sim <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">-</span> tail_cmp<span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">$</span>p_normal) <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">/</span> se_tail)</span>
<span id="cb7-18"><span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">stopifnot</span>(z_norm <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">==</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">max</span>(<span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">abs</span>(tail_cmp<span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">$</span>p_normal <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">-</span> tail_cmp<span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">$</span>p_sim) <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">/</span> se_tail))</span>
<span id="cb7-19">se_p02    <span class="ot" style="color: #003B4F;
background-color: null;
font-style: inherit;">&lt;-</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">sqrt</span>(<span class="fl" style="color: #AD0000;
background-color: null;
font-style: inherit;">0.02</span> <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">*</span> <span class="fl" style="color: #AD0000;
background-color: null;
font-style: inherit;">0.98</span> <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">/</span> (n_rep <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">-</span> <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">1</span>))</span>
<span id="cb7-20">small_ex  <span class="ot" style="color: #003B4F;
background-color: null;
font-style: inherit;">&lt;-</span> exact_cmp<span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">$</span>p_exact <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">&lt;</span> <span class="fl" style="color: #AD0000;
background-color: null;
font-style: inherit;">0.05</span></span>
<span id="cb7-21">n_small   <span class="ot" style="color: #003B4F;
background-color: null;
font-style: inherit;">&lt;-</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">tapply</span>(small_ex, exact_cmp<span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">$</span>n_map, sum)</span>
<span id="cb7-22">ratio_ne  <span class="ot" style="color: #003B4F;
background-color: null;
font-style: inherit;">&lt;-</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">tapply</span>((exact_cmp<span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">$</span>p_normal <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">/</span> exact_cmp<span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">$</span>p_exact)[small_ex], exact_cmp<span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">$</span>n_map[small_ex], mean)</span>
<span id="cb7-23">skew_ref  <span class="ot" style="color: #003B4F;
background-color: null;
font-style: inherit;">&lt;-</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">tapply</span>(exact_cmp<span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">$</span>skew, exact_cmp<span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">$</span>n_map, mean)</span></code></pre></div></div>
</div>
<p>Over the first 200 null datasets with no maps and with sixteen, 83 have a simulated p-value below 0.2, the region where a decision is made. Each simulated p-value has its own Monte Carlo standard error, about 0.0022 near p = 0.02. In those units the exact p-values differ from the simulated ones by at most 2.0 standard errors, while the largest gap of the normal approximation is 4.0 standard errors, with its p-value below the simulated one. The simulated p-values of a design all come from one reference sample, so this is one deviation of one empirical distribution, not many independent ones. The two computed versions can also be set against each other, which involves no simulation at all: where the exact p-value is below 0.05 (10 datasets with no maps, 11 with sixteen), the normal p-value is on average 0.57 and 0.59 times the exact one. The null distribution of I is skewed to the right, with a skewness of 0.31 and 0.30 over the simulated statistics, and a normal curve with the same mean and variance puts too little weight in the upper tail. That is where the small excess in the size of <code>lm.morantest()</code> comes from, and it is there with no maps at all: it belongs to the normal approximation, not to the residual null.</p>
</section>
<section id="the-permutation-route-has-the-same-null" class="level2">
<h2 id="the-permutation-route-has-the-same-null-h" class="anchored" data-anchor-id="the-permutation-route-has-the-same-null">The permutation route has the same null</h2>
<p><code>moran.mc()</code> looks like the safer choice, and the Moran’s I post recommends it for irregular points. It is not a different null. It shuffles the residuals across plots and recomputes I each time, which asks what I would look like if the same values had landed on the plots in random order. For any centred vector the average of I over all orderings is exactly minus one over (n minus one): every pair of distinct positions is equally likely to receive every pair of distinct values, and the sum of all cross products of centred values is minus their sum of squares. The shuffle forgets that the residuals were built to be orthogonal to the maps, which is exactly the constraint that moved their null.</p>
<div class="cell">
<div class="code-copy-outer-scaffold"><div class="sourceCode cell-code" id="cb8" style="background: #f1f3f5;"><pre class="sourceCode r code-with-copy"><code class="sourceCode r"><span id="cb8-1">perm_mc <span class="ot" style="color: #003B4F;
background-color: null;
font-style: inherit;">&lt;-</span> <span class="cf" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">function</span>(r, nsim) {</span>
<span id="cb8-2">  pm    <span class="ot" style="color: #003B4F;
background-color: null;
font-style: inherit;">&lt;-</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">vapply</span>(<span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">seq_len</span>(nsim), <span class="cf" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">function</span>(i) <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">sample</span>(r), <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">numeric</span>(n_plot))</span>
<span id="cb8-3">  i_all <span class="ot" style="color: #003B4F;
background-color: null;
font-style: inherit;">&lt;-</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">c</span>(<span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">colSums</span>(pm <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">*</span> (w_mat <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">%*%</span> pm)) <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">/</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">sum</span>(r<span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">^</span><span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">2</span>), <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">sum</span>(r <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">*</span> (w_mat <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">%*%</span> r)) <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">/</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">sum</span>(r<span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">^</span><span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">2</span>))</span>
<span id="cb8-4">  rk    <span class="ot" style="color: #003B4F;
background-color: null;
font-style: inherit;">&lt;-</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">rank</span>(i_all)[nsim <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">+</span> <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">1</span>]</span>
<span id="cb8-5">  <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">list</span>(<span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">p =</span> (<span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">max</span>(nsim <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">-</span> rk, <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">0</span>) <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">+</span> <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">1</span>) <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">/</span> (nsim <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">+</span> <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">1</span>), <span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">i_perm =</span> i_all[<span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">seq_len</span>(nsim)])</span>
<span id="cb8-6">}</span>
<span id="cb8-7">r_one  <span class="ot" style="color: #003B4F;
background-color: null;
font-style: inherit;">&lt;-</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">as.numeric</span>(nul16<span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">$</span>m_mat <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">%*%</span> eps_null[, <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">1</span>])</span>
<span id="cb8-8"><span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">set.seed</span>(<span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">71</span>); mc_one <span class="ot" style="color: #003B4F;
background-color: null;
font-style: inherit;">&lt;-</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">moran.mc</span>(r_one, lw_knn, <span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">nsim =</span> <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">999</span>)</span>
<span id="cb8-9"><span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">set.seed</span>(<span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">71</span>); hand_one <span class="ot" style="color: #003B4F;
background-color: null;
font-style: inherit;">&lt;-</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">perm_mc</span>(r_one, <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">999</span>)</span>
<span id="cb8-10"><span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">stopifnot</span>(<span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">abs</span>(mc_one<span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">$</span>p.value <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">-</span> hand_one<span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">$</span>p) <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">&lt;</span> <span class="fl" style="color: #AD0000;
background-color: null;
font-style: inherit;">1e-12</span>,</span>
<span id="cb8-11">          <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">max</span>(<span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">abs</span>(mc_one<span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">$</span>res[<span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">1</span><span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">:</span><span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">999</span>] <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">-</span> hand_one<span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">$</span>i_perm)) <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">&lt;</span> <span class="fl" style="color: #AD0000;
background-color: null;
font-style: inherit;">1e-12</span>)</span>
<span id="cb8-12">perm_mean <span class="ot" style="color: #003B4F;
background-color: null;
font-style: inherit;">&lt;-</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">mean</span>(hand_one<span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">$</span>i_perm)</span>
<span id="cb8-13">i_one     <span class="ot" style="color: #003B4F;
background-color: null;
font-style: inherit;">&lt;-</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">sum</span>(r_one <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">*</span> (w_mat <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">%*%</span> r_one)) <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">/</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">sum</span>(r_one<span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">^</span><span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">2</span>)</span>
<span id="cb8-14">p_one_lmt <span class="ot" style="color: #003B4F;
background-color: null;
font-style: inherit;">&lt;-</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">pnorm</span>((i_one <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">-</span> nul16<span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">$</span>e_res) <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">/</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">sqrt</span>(nul16<span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">$</span>v_res), <span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">lower.tail =</span> <span class="cn" style="color: #8f5902;
background-color: null;
font-style: inherit;">FALSE</span>)</span>
<span id="cb8-15">null16_i  <span class="ot" style="color: #003B4F;
background-color: null;
font-style: inherit;">&lt;-</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">moran_cols</span>(nul16<span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">$</span>m_mat <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">%*%</span> eps_null)</span>
<span id="cb8-16"></span>
<span id="cb8-17">n_perm_rep <span class="ot" style="color: #003B4F;
background-color: null;
font-style: inherit;">&lt;-</span> <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">500</span>; n_perm_sim <span class="ot" style="color: #003B4F;
background-color: null;
font-style: inherit;">&lt;-</span> <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">199</span>; perm_maps <span class="ot" style="color: #003B4F;
background-color: null;
font-style: inherit;">&lt;-</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">c</span>(<span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">0</span>, <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">8</span>, <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">16</span>); <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">set.seed</span>(<span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">5150</span>)</span>
<span id="cb8-18">perm_tab <span class="ot" style="color: #003B4F;
background-color: null;
font-style: inherit;">&lt;-</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">do.call</span>(rbind, <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">lapply</span>(perm_maps, <span class="cf" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">function</span>(n_map) {</span>
<span id="cb8-19">  m_mat <span class="ot" style="color: #003B4F;
background-color: null;
font-style: inherit;">&lt;-</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">res_null</span>(<span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">design_mem</span>(n_map))<span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">$</span>m_mat</span>
<span id="cb8-20">  p_n <span class="ot" style="color: #003B4F;
background-color: null;
font-style: inherit;">&lt;-</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">vapply</span>(<span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">seq_len</span>(n_perm_rep), <span class="cf" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">function</span>(j)</span>
<span id="cb8-21">    <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">perm_mc</span>(<span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">as.numeric</span>(m_mat <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">%*%</span> eps_null[, j]), n_perm_sim)<span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">$</span>p, <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">numeric</span>(<span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">1</span>))</span>
<span id="cb8-22">  p_a <span class="ot" style="color: #003B4F;
background-color: null;
font-style: inherit;">&lt;-</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">vapply</span>(<span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">seq_len</span>(n_perm_rep), <span class="cf" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">function</span>(j)</span>
<span id="cb8-23">    <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">perm_mc</span>(<span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">as.numeric</span>(m_mat <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">%*%</span> eps_sar[, j]), n_perm_sim)<span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">$</span>p, <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">numeric</span>(<span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">1</span>))</span>
<span id="cb8-24">  <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">data.frame</span>(<span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">n_map =</span> n_map, <span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">arm =</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">c</span>(<span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"size"</span>, <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"power"</span>), <span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">test =</span> <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"moran.mc on residuals"</span>,</span>
<span id="cb8-25">             <span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">rate =</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">c</span>(<span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">mean</span>(p_n <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">&lt;</span> <span class="fl" style="color: #AD0000;
background-color: null;
font-style: inherit;">0.05</span>), <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">mean</span>(p_a <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">&lt;</span> <span class="fl" style="color: #AD0000;
background-color: null;
font-style: inherit;">0.05</span>)))</span>
<span id="cb8-26">}))</span>
<span id="cb8-27">perm_tab<span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">$</span>se <span class="ot" style="color: #003B4F;
background-color: null;
font-style: inherit;">&lt;-</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">sqrt</span>(perm_tab<span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">$</span>rate <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">*</span> (<span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">1</span> <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">-</span> perm_tab<span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">$</span>rate) <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">/</span> n_perm_rep)</span>
<span id="cb8-28">get_perm <span class="ot" style="color: #003B4F;
background-color: null;
font-style: inherit;">&lt;-</span> <span class="cf" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">function</span>(m, a) perm_tab<span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">$</span>rate[perm_tab<span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">$</span>n_map <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">==</span> m <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">&amp;</span> perm_tab<span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">$</span>arm <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">==</span> a]</span></code></pre></div></div>
</div>
<p>The hand-written shuffle reproduces <code>moran.mc()</code> exactly when both start from the same random seed: the same 999 permuted statistics and the same p-value. Take one null dataset fitted with sixteen maps. Its residual I is -0.1104. The shuffled values average -0.0063, next to the exact -0.0067, and give a permutation p-value of 0.998; <code>lm.morantest()</code> gives 0.540 for the same residuals, referred to a null centred at -0.1076.</p>
<p>Over 500 datasets per cell, with 199 shuffles each, the permutation test on residuals rejects a true null in 0.052, 0.004 and 0.000 of datasets with zero, eight and sixteen maps, and detects the autoregressive errors in 0.872, 0.216 and 0.000. It tracks the <code>moran.test()</code> default, not <code>lm.morantest()</code>.</p>
<div class="cell">
<div class="code-copy-outer-scaffold"><div class="sourceCode cell-code" id="cb9" style="background: #f1f3f5;"><pre class="sourceCode r code-with-copy"><code class="sourceCode r"><span id="cb9-1">dens_df <span class="ot" style="color: #003B4F;
background-color: null;
font-style: inherit;">&lt;-</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">rbind</span>(</span>
<span id="cb9-2">  <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">data.frame</span>(<span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">i_val =</span> null16_i, <span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">what =</span> <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"residual I over 4000 null datasets"</span>),</span>
<span id="cb9-3">  <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">data.frame</span>(<span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">i_val =</span> hand_one<span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">$</span>i_perm, <span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">what =</span> <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"999 shuffles of one residual vector"</span>))</span>
<span id="cb9-4"><span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">ggplot</span>(dens_df, <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">aes</span>(i_val, <span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">fill =</span> what, <span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">colour =</span> what)) <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">+</span></span>
<span id="cb9-5">  <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">geom_density</span>(<span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">alpha =</span> <span class="fl" style="color: #AD0000;
background-color: null;
font-style: inherit;">0.35</span>, <span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">linewidth =</span> <span class="fl" style="color: #AD0000;
background-color: null;
font-style: inherit;">0.7</span>) <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">+</span></span>
<span id="cb9-6">  <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">geom_vline</span>(<span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">xintercept =</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">c</span>(nul16<span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">$</span>e_res, e_raw), <span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">linetype =</span> <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"dashed"</span>,</span>
<span id="cb9-7">             <span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">colour =</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">c</span>(te_forest, te_rust), <span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">linewidth =</span> <span class="fl" style="color: #AD0000;
background-color: null;
font-style: inherit;">0.6</span>) <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">+</span></span>
<span id="cb9-8">  <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">geom_vline</span>(<span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">xintercept =</span> i_one, <span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">colour =</span> te_ink, <span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">linewidth =</span> <span class="fl" style="color: #AD0000;
background-color: null;
font-style: inherit;">0.7</span>) <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">+</span></span>
<span id="cb9-9">  <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">scale_fill_manual</span>(<span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">values =</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">c</span>(te_rust, te_forest), <span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">name =</span> <span class="cn" style="color: #8f5902;
background-color: null;
font-style: inherit;">NULL</span>) <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">+</span></span>
<span id="cb9-10">  <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">scale_colour_manual</span>(<span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">values =</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">c</span>(te_rust, te_forest), <span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">name =</span> <span class="cn" style="color: #8f5902;
background-color: null;
font-style: inherit;">NULL</span>) <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">+</span></span>
<span id="cb9-11">  <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">labs</span>(<span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">x =</span> <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"Moran's I"</span>, <span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">y =</span> <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"density"</span>,</span>
<span id="cb9-12">       <span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">title =</span> <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"Shuffling residuals rebuilds the raw-data null"</span>,</span>
<span id="cb9-13">       <span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">subtitle =</span> <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"dashed green: tr(MW)/(n - k); dashed red: -1/(n - 1)"</span>) <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">+</span></span>
<span id="cb9-14">  <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">theme_datasheet</span>() <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">+</span></span>
<span id="cb9-15">  <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">theme</span>(<span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">legend.position =</span> <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"bottom"</span>)</span></code></pre></div></div>
<div class="cell-output-display">
<div id="fig-permnull" class="quarto-float quarto-figure quarto-figure-center anchored" alt="Two overlapping density curves on warm off-white paper, with Moran's I on the horizontal axis from about minus 0.2 to 0.13. A tall dark green curve for residual I over 4000 null datasets peaks near minus 0.11, with a dashed green line at its expectation just right of the peak. A lower, wider red curve for 999 shuffles of one residual vector is centred near zero, with a dashed red line at minus one over n minus one. A solid dark line marks the observed I of the shuffled vector near minus 0.11, in the far left tail of the red curve and at the centre of the green one.">
<figure class="quarto-float quarto-float-fig figure">
<div aria-describedby="fig-permnull-caption-0ceaefa1-69ba-4598-a22c-09a6ac19f8ca">
<img src="https://tidyecology.com/posts/morans-i-on-regression-residuals/index_files/figure-html/fig-permnull-1.png" class="img-fluid figure-img" alt="Two overlapping density curves on warm off-white paper, with Moran's I on the horizontal axis from about minus 0.2 to 0.13. A tall dark green curve for residual I over 4000 null datasets peaks near minus 0.11, with a dashed green line at its expectation just right of the peak. A lower, wider red curve for 999 shuffles of one residual vector is centred near zero, with a dashed red line at minus one over n minus one. A solid dark line marks the observed I of the shuffled vector near minus 0.11, in the far left tail of the red curve and at the centre of the green one." width="672">
</div>
<figcaption class="quarto-float-caption-bottom quarto-float-caption quarto-float-fig" id="fig-permnull-caption-0ceaefa1-69ba-4598-a22c-09a6ac19f8ca">
Figure&nbsp;2: With sixteen maps in the model: the distribution of residual Moran’s I over null datasets, and the permutation distribution of one of those residual vectors. Dashed lines mark the two expectations; the solid line is the observed I of the permuted vector.
</figcaption>
</figure>
</div>
</div>
</div>
<div class="cell">
<div class="code-copy-outer-scaffold"><div class="sourceCode cell-code" id="cb10" style="background: #f1f3f5;"><pre class="sourceCode r code-with-copy"><code class="sourceCode r"><span id="cb10-1">rates_all <span class="ot" style="color: #003B4F;
background-color: null;
font-style: inherit;">&lt;-</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">rbind</span>(rate_tab, perm_tab)</span>
<span id="cb10-2">rates_all<span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">$</span>panel <span class="ot" style="color: #003B4F;
background-color: null;
font-style: inherit;">&lt;-</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">factor</span>(<span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">ifelse</span>(rates_all<span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">$</span>arm <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">==</span> <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"size"</span>, <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"no autocorrelation (size)"</span>,</span>
<span id="cb10-3">                                 <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"autoregressive errors, 0.4 (power)"</span>),</span>
<span id="cb10-4">                          <span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">levels =</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">c</span>(<span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"no autocorrelation (size)"</span>, <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"autoregressive errors, 0.4 (power)"</span>))</span>
<span id="cb10-5">rates_all<span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">$</span>test <span class="ot" style="color: #003B4F;
background-color: null;
font-style: inherit;">&lt;-</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">factor</span>(rates_all<span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">$</span>test,</span>
<span id="cb10-6">                         <span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">levels =</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">c</span>(<span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"lm.morantest"</span>, <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"moran.test"</span>, <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"moran.mc on residuals"</span>))</span>
<span id="cb10-7">ref_df <span class="ot" style="color: #003B4F;
background-color: null;
font-style: inherit;">&lt;-</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">data.frame</span>(<span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">panel =</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">factor</span>(<span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"no autocorrelation (size)"</span>, <span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">levels =</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">levels</span>(rates_all<span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">$</span>panel)),</span>
<span id="cb10-8">                     <span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">yint =</span> <span class="fl" style="color: #AD0000;
background-color: null;
font-style: inherit;">0.05</span>)</span>
<span id="cb10-9"><span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">ggplot</span>(rates_all, <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">aes</span>(n_map, rate, <span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">colour =</span> test)) <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">+</span></span>
<span id="cb10-10">  <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">geom_hline</span>(<span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">data =</span> ref_df, <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">aes</span>(<span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">yintercept =</span> yint), <span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">linetype =</span> <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"dashed"</span>,</span>
<span id="cb10-11">             <span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">colour =</span> te_body, <span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">linewidth =</span> <span class="fl" style="color: #AD0000;
background-color: null;
font-style: inherit;">0.5</span>) <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">+</span></span>
<span id="cb10-12">  <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">geom_line</span>(<span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">data =</span> rates_all[rates_all<span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">$</span>test <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">!=</span> <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"moran.mc on residuals"</span>, ], <span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">linewidth =</span> <span class="fl" style="color: #AD0000;
background-color: null;
font-style: inherit;">0.9</span>) <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">+</span></span>
<span id="cb10-13">  <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">geom_errorbar</span>(<span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">aes</span>(<span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">ymin =</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">pmax</span>(rate <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">-</span> <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">2</span> <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">*</span> se, <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">0</span>), <span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">ymax =</span> rate <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">+</span> <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">2</span> <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">*</span> se),</span>
<span id="cb10-14">                <span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">width =</span> <span class="fl" style="color: #AD0000;
background-color: null;
font-style: inherit;">0.5</span>, <span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">linewidth =</span> <span class="fl" style="color: #AD0000;
background-color: null;
font-style: inherit;">0.5</span>) <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">+</span></span>
<span id="cb10-15">  <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">geom_point</span>(<span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">aes</span>(<span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">shape =</span> test), <span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">size =</span> <span class="fl" style="color: #AD0000;
background-color: null;
font-style: inherit;">2.4</span>) <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">+</span></span>
<span id="cb10-16">  <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">facet_wrap</span>(<span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">~</span> panel, <span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">scales =</span> <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"free_y"</span>) <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">+</span></span>
<span id="cb10-17">  <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">scale_colour_manual</span>(<span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">values =</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">c</span>(te_forest, te_rust, te_gold), <span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">name =</span> <span class="cn" style="color: #8f5902;
background-color: null;
font-style: inherit;">NULL</span>) <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">+</span></span>
<span id="cb10-18">  <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">scale_shape_manual</span>(<span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">values =</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">c</span>(<span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">16</span>, <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">16</span>, <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">17</span>), <span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">name =</span> <span class="cn" style="color: #8f5902;
background-color: null;
font-style: inherit;">NULL</span>) <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">+</span></span>
<span id="cb10-19">  <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">scale_x_continuous</span>(<span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">breaks =</span> map_grid) <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">+</span></span>
<span id="cb10-20">  <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">labs</span>(<span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">x =</span> <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"eigenvector maps in the model"</span>, <span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">y =</span> <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"rejection rate at 0.05"</span>,</span>
<span id="cb10-21">       <span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">title =</span> <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"The raw-data null stops detecting anything"</span>,</span>
<span id="cb10-22">       <span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">subtitle =</span> <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"dashed: the nominal five per cent"</span>) <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">+</span></span>
<span id="cb10-23">  <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">theme_datasheet</span>() <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">+</span></span>
<span id="cb10-24">  <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">theme</span>(<span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">legend.position =</span> <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"bottom"</span>)</span></code></pre></div></div>
<div class="cell-output-display">
<div id="fig-rates" class="quarto-float quarto-figure quarto-figure-center anchored" alt="Two panels on warm off-white paper, rejection rate against the number of eigenvector maps in the model from 0 to 16. Left panel, no autocorrelation: a dark green line for lm.morantest stays between about 0.056 and 0.062, just above a dashed line at 0.05, while a red line for moran.test starts at the same point and drops to about 0.025 at two maps, about 0.01 at four and zero from eight maps on; gold triangles for moran.mc on residuals at 0, 8 and 16 maps sit on or near the red line. Right panel, autoregressive errors: the green line falls from about 0.89 to about 0.49, the red line falls from the same start to about 0.63 at four maps, 0.24 at eight and zero at sixteen, with the gold triangles again on the red line. Short vertical bars show two Monte Carlo standard errors.">
<figure class="quarto-float quarto-float-fig figure">
<div aria-describedby="fig-rates-caption-0ceaefa1-69ba-4598-a22c-09a6ac19f8ca">
<img src="https://tidyecology.com/posts/morans-i-on-regression-residuals/index_files/figure-html/fig-rates-1.png" class="img-fluid figure-img" alt="Two panels on warm off-white paper, rejection rate against the number of eigenvector maps in the model from 0 to 16. Left panel, no autocorrelation: a dark green line for lm.morantest stays between about 0.056 and 0.062, just above a dashed line at 0.05, while a red line for moran.test starts at the same point and drops to about 0.025 at two maps, about 0.01 at four and zero from eight maps on; gold triangles for moran.mc on residuals at 0, 8 and 16 maps sit on or near the red line. Right panel, autoregressive errors: the green line falls from about 0.89 to about 0.49, the red line falls from the same start to about 0.63 at four maps, 0.24 at eight and zero at sixteen, with the gold triangles again on the red line. Short vertical bars show two Monte Carlo standard errors." width="672">
</div>
<figcaption class="quarto-float-caption-bottom quarto-float-caption quarto-float-fig" id="fig-rates-caption-0ceaefa1-69ba-4598-a22c-09a6ac19f8ca">
Figure&nbsp;3: Rejection rates of three residual autocorrelation tests at the five per cent level, by the number of eigenvector maps in the model. Left: independent errors; right: autoregressive errors. Bars: two Monte Carlo standard errors.
</figcaption>
</figure>
</div>
</div>
</div>
</section>
<section id="a-stopping-rule-built-on-the-wrong-null" class="level2">
<h2 id="a-stopping-rule-built-on-the-wrong-null-h" class="anchored" data-anchor-id="a-stopping-rule-built-on-the-wrong-null">A stopping rule built on the wrong null</h2>
<p>The eigenvector filtering post uses the residual test as a stopping rule: add the map, or tied set of maps, most correlated with the residuals, test again, stop when the residual I is no longer significant. A test that rejects too rarely stops the loop early. The simulation below repeats that loop on the plateau layout with a covariate that has no effect on the response but shares the broadest map with an unmeasured smooth field that does, which is the confounded case the filtering post was built for. The candidates are the first 40 maps, the loop is capped at 30, and each of 400 datasets is run twice, once with each test as the rule.</p>
<div class="cell">
<div class="code-copy-outer-scaffold"><div class="sourceCode cell-code" id="cb11" style="background: #f1f3f5;"><pre class="sourceCode r code-with-copy"><code class="sourceCode r"><span id="cb11-1">n_sel_rep <span class="ot" style="color: #003B4F;
background-color: null;
font-style: inherit;">&lt;-</span> <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">400</span></span>
<span id="cb11-2">cand_map  <span class="ot" style="color: #003B4F;
background-color: null;
font-style: inherit;">&lt;-</span> <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">1</span><span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">:</span><span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">40</span></span>
<span id="cb11-3">max_map   <span class="ot" style="color: #003B4F;
background-color: null;
font-style: inherit;">&lt;-</span> <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">30</span></span>
<span id="cb11-4">p_raw_one <span class="ot" style="color: #003B4F;
background-color: null;
font-style: inherit;">&lt;-</span> <span class="cf" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">function</span>(r) <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">pnorm</span>((<span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">moran_cols</span>(<span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">matrix</span>(r)) <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">-</span> e_raw) <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">/</span></span>
<span id="cb11-5">  <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">sqrt</span>(<span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">v_raw</span>(n_plot <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">*</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">sum</span>(r<span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">^</span><span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">4</span>) <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">/</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">sum</span>(r<span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">^</span><span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">2</span>)<span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">^</span><span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">2</span>)), <span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">lower.tail =</span> <span class="cn" style="color: #8f5902;
background-color: null;
font-style: inherit;">FALSE</span>)</span>
<span id="cb11-6">p_res_one <span class="ot" style="color: #003B4F;
background-color: null;
font-style: inherit;">&lt;-</span> <span class="cf" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">function</span>(r, X) { nul <span class="ot" style="color: #003B4F;
background-color: null;
font-style: inherit;">&lt;-</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">res_null</span>(X)</span>
<span id="cb11-7">  <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">pnorm</span>((<span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">moran_cols</span>(<span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">matrix</span>(r)) <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">-</span> nul<span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">$</span>e_res) <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">/</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">sqrt</span>(nul<span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">$</span>v_res), <span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">lower.tail =</span> <span class="cn" style="color: #8f5902;
background-color: null;
font-style: inherit;">FALSE</span>) }</span>
<span id="cb11-8">run_select <span class="ot" style="color: #003B4F;
background-color: null;
font-style: inherit;">&lt;-</span> <span class="cf" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">function</span>(y, x, rule) {</span>
<span id="cb11-9">  sel <span class="ot" style="color: #003B4F;
background-color: null;
font-style: inherit;">&lt;-</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">integer</span>(<span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">0</span>)</span>
<span id="cb11-10">  <span class="cf" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">repeat</span> {</span>
<span id="cb11-11">    X <span class="ot" style="color: #003B4F;
background-color: null;
font-style: inherit;">&lt;-</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">cbind</span>(<span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">1</span>, x, mem_all[, sel, <span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">drop =</span> <span class="cn" style="color: #8f5902;
background-color: null;
font-style: inherit;">FALSE</span>])</span>
<span id="cb11-12">    r <span class="ot" style="color: #003B4F;
background-color: null;
font-style: inherit;">&lt;-</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">as.numeric</span>(y <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">-</span> X <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">%*%</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">qr.coef</span>(<span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">qr</span>(X), y))</span>
<span id="cb11-13">    p <span class="ot" style="color: #003B4F;
background-color: null;
font-style: inherit;">&lt;-</span> <span class="cf" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">if</span> (rule <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">==</span> <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"raw"</span>) <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">p_raw_one</span>(r) <span class="cf" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">else</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">p_res_one</span>(r, X)</span>
<span id="cb11-14">    <span class="cf" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">if</span> (p <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">&gt;</span> <span class="fl" style="color: #AD0000;
background-color: null;
font-style: inherit;">0.05</span> <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">||</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">length</span>(sel) <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">&gt;=</span> max_map) <span class="cf" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">break</span></span>
<span id="cb11-15">    left <span class="ot" style="color: #003B4F;
background-color: null;
font-style: inherit;">&lt;-</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">setdiff</span>(cand_map, sel)</span>
<span id="cb11-16">    sel  <span class="ot" style="color: #003B4F;
background-color: null;
font-style: inherit;">&lt;-</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">c</span>(sel, left[<span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">which.max</span>(<span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">abs</span>(<span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">cor</span>(mem_all[, left], r)))])</span>
<span id="cb11-17">  }</span>
<span id="cb11-18">  X   <span class="ot" style="color: #003B4F;
background-color: null;
font-style: inherit;">&lt;-</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">cbind</span>(<span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">1</span>, x, mem_all[, sel, <span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">drop =</span> <span class="cn" style="color: #8f5902;
background-color: null;
font-style: inherit;">FALSE</span>])</span>
<span id="cb11-19">  fit <span class="ot" style="color: #003B4F;
background-color: null;
font-style: inherit;">&lt;-</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">lm</span>(y <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">~</span> X <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">-</span> <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">1</span>)</span>
<span id="cb11-20">  <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">c</span>(<span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">n_map =</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">length</span>(sel), <span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">x_fp =</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">summary</span>(fit)<span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">$</span>coefficients[<span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">2</span>, <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">4</span>] <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">&lt;</span> <span class="fl" style="color: #AD0000;
background-color: null;
font-style: inherit;">0.05</span>,</span>
<span id="cb11-21">    <span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">ac_left =</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">p_res_one</span>(<span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">residuals</span>(fit), X) <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">&lt;</span> <span class="fl" style="color: #AD0000;
background-color: null;
font-style: inherit;">0.05</span>, <span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">capped =</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">length</span>(sel) <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">&gt;=</span> max_map)</span>
<span id="cb11-22">}</span>
<span id="cb11-23"><span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">set.seed</span>(<span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">4478</span>)</span>
<span id="cb11-24">sel_out <span class="ot" style="color: #003B4F;
background-color: null;
font-style: inherit;">&lt;-</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">replicate</span>(n_sel_rep, {</span>
<span id="cb11-25">  field <span class="ot" style="color: #003B4F;
background-color: null;
font-style: inherit;">&lt;-</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">as.numeric</span>(<span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">scale</span>(mem_all[, <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">1</span>] <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">*</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">rnorm</span>(<span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">1</span>, <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">1</span>, <span class="fl" style="color: #AD0000;
background-color: null;
font-style: inherit;">0.1</span>) <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">+</span></span>
<span id="cb11-26">                              mem_all[, <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">2</span><span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">:</span><span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">12</span>] <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">%*%</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">rnorm</span>(<span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">11</span>, <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">0</span>, <span class="fl" style="color: #AD0000;
background-color: null;
font-style: inherit;">0.5</span>) <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">+</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">rnorm</span>(n_plot, <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">0</span>, <span class="fl" style="color: #AD0000;
background-color: null;
font-style: inherit;">0.2</span>)))</span>
<span id="cb11-27">  x_conf <span class="ot" style="color: #003B4F;
background-color: null;
font-style: inherit;">&lt;-</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">as.numeric</span>(<span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">scale</span>(<span class="fl" style="color: #AD0000;
background-color: null;
font-style: inherit;">0.6</span> <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">*</span> mem_all[, <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">1</span>] <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">/</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">sd</span>(mem_all[, <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">1</span>]) <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">+</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">rnorm</span>(n_plot)))</span>
<span id="cb11-28">  y_sel  <span class="ot" style="color: #003B4F;
background-color: null;
font-style: inherit;">&lt;-</span> field <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">+</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">rnorm</span>(n_plot)</span>
<span id="cb11-29">  <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">c</span>(<span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">run_select</span>(y_sel, x_conf, <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"raw"</span>), <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">run_select</span>(y_sel, x_conf, <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"res"</span>),</span>
<span id="cb11-30">    <span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">ols_fp =</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">summary</span>(<span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">lm</span>(y_sel <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">~</span> x_conf))<span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">$</span>coefficients[<span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">2</span>, <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">4</span>] <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">&lt;</span> <span class="fl" style="color: #AD0000;
background-color: null;
font-style: inherit;">0.05</span>)</span>
<span id="cb11-31">})</span>
<span id="cb11-32">sel_mean <span class="ot" style="color: #003B4F;
background-color: null;
font-style: inherit;">&lt;-</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">rowMeans</span>(sel_out)</span>
<span id="cb11-33">sel_raw_k <span class="ot" style="color: #003B4F;
background-color: null;
font-style: inherit;">&lt;-</span> sel_out[<span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">1</span>, ]</span>
<span id="cb11-34">sel_res_k <span class="ot" style="color: #003B4F;
background-color: null;
font-style: inherit;">&lt;-</span> sel_out[<span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">5</span>, ]</span>
<span id="cb11-35">fp_raw <span class="ot" style="color: #003B4F;
background-color: null;
font-style: inherit;">&lt;-</span> sel_mean[<span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">2</span>]; fp_res <span class="ot" style="color: #003B4F;
background-color: null;
font-style: inherit;">&lt;-</span> sel_mean[<span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">6</span>]; fp_ols <span class="ot" style="color: #003B4F;
background-color: null;
font-style: inherit;">&lt;-</span> sel_mean[<span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">9</span>]</span>
<span id="cb11-36">left_raw <span class="ot" style="color: #003B4F;
background-color: null;
font-style: inherit;">&lt;-</span> sel_mean[<span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">3</span>]; left_res <span class="ot" style="color: #003B4F;
background-color: null;
font-style: inherit;">&lt;-</span> sel_mean[<span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">7</span>]</span>
<span id="cb11-37">fp_diff_se <span class="ot" style="color: #003B4F;
background-color: null;
font-style: inherit;">&lt;-</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">sd</span>(sel_out[<span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">2</span>, ] <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">-</span> sel_out[<span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">6</span>, ]) <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">/</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">sqrt</span>(n_sel_rep)</span>
<span id="cb11-38">k_diff_se  <span class="ot" style="color: #003B4F;
background-color: null;
font-style: inherit;">&lt;-</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">sd</span>(sel_res_k <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">-</span> sel_raw_k) <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">/</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">sqrt</span>(n_sel_rep)</span>
<span id="cb11-39">n_capped   <span class="ot" style="color: #003B4F;
background-color: null;
font-style: inherit;">&lt;-</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">sum</span>(sel_out[<span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">4</span>, ]) <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">+</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">sum</span>(sel_out[<span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">8</span>, ])</span></code></pre></div></div>
</div>
<p>With the raw-data rule the loop keeps 1.95 maps on average and with the residual rule 2.36, a paired difference with a standard error of 0.03. The cap of 30 maps was reached in 0 of the 800 runs. After the raw-data rule has stopped, <code>lm.morantest()</code> still finds autocorrelation in the final model’s residuals in 0.338 of datasets; after the residual rule the share is 0.000, which is zero by construction, since that rule stops only when the same test passes.</p>
<p>The covariate’s false-positive rate is a different quantity and it barely moves. It is 0.2350 after the raw-data rule and 0.2325 after the residual rule, a paired difference of +0.0025 with a standard error of 0.007, and 0.282 for plain least squares with no maps at all. Both filtered rates are far above five per cent. The correct residual test makes the stopping rule honest about the residuals; it does not repair the inference for a covariate that shares its spatial pattern with an unmeasured driver. That confounding is the limit the eigenvector filtering post states itself, and no choice of residual test reaches it.</p>
<div class="cell">
<div class="code-copy-outer-scaffold"><div class="sourceCode cell-code" id="cb12" style="background: #f1f3f5;"><pre class="sourceCode r code-with-copy"><code class="sourceCode r"><span id="cb12-1">k_levels <span class="ot" style="color: #003B4F;
background-color: null;
font-style: inherit;">&lt;-</span> <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">0</span><span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">:</span><span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">max</span>(<span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">c</span>(sel_raw_k, sel_res_k))</span>
<span id="cb12-2">k_df <span class="ot" style="color: #003B4F;
background-color: null;
font-style: inherit;">&lt;-</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">rbind</span>(</span>
<span id="cb12-3">  <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">data.frame</span>(<span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">n_map =</span> k_levels, <span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">share =</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">tabulate</span>(sel_raw_k <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">+</span> <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">1</span>, <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">length</span>(k_levels)) <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">/</span> n_sel_rep,</span>
<span id="cb12-4">             <span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">rule =</span> <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"stop on moran.test (raw-data null)"</span>),</span>
<span id="cb12-5">  <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">data.frame</span>(<span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">n_map =</span> k_levels, <span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">share =</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">tabulate</span>(sel_res_k <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">+</span> <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">1</span>, <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">length</span>(k_levels)) <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">/</span> n_sel_rep,</span>
<span id="cb12-6">             <span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">rule =</span> <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"stop on lm.morantest (residual null)"</span>))</span>
<span id="cb12-7"><span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">ggplot</span>(k_df, <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">aes</span>(<span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">factor</span>(n_map), share, <span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">fill =</span> rule)) <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">+</span></span>
<span id="cb12-8">  <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">geom_col</span>(<span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">position =</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">position_dodge</span>(<span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">width =</span> <span class="fl" style="color: #AD0000;
background-color: null;
font-style: inherit;">0.8</span>), <span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">width =</span> <span class="fl" style="color: #AD0000;
background-color: null;
font-style: inherit;">0.75</span>) <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">+</span></span>
<span id="cb12-9">  <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">scale_fill_manual</span>(<span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">values =</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">c</span>(te_forest, te_rust), <span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">name =</span> <span class="cn" style="color: #8f5902;
background-color: null;
font-style: inherit;">NULL</span>) <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">+</span></span>
<span id="cb12-10">  <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">labs</span>(<span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">x =</span> <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"eigenvector maps kept"</span>, <span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">y =</span> <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"share of datasets"</span>,</span>
<span id="cb12-11">       <span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">title =</span> <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"The raw-data rule tends to stop earlier"</span>,</span>
<span id="cb12-12">       <span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">subtitle =</span> <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"same datasets, same candidate maps, same selection order"</span>) <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">+</span></span>
<span id="cb12-13">  <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">theme_datasheet</span>() <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">+</span></span>
<span id="cb12-14">  <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">theme</span>(<span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">legend.position =</span> <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"bottom"</span>, <span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">legend.direction =</span> <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"vertical"</span>)</span></code></pre></div></div>
<div class="cell-output-display">
<div id="fig-selection" class="quarto-float quarto-figure quarto-figure-center anchored" alt="Paired columns on warm off-white paper showing the share of 400 datasets against the number of eigenvector maps kept, from 0 to 8. Dark green columns are for stopping on lm.morantest and red columns for stopping on moran.test. Both rules most often keep one to three maps; the red columns are taller at zero, one and two maps (near 0.15, 0.26 and 0.27), the two are equal at three, and the green columns are taller from four maps upward, with green alone at seven and eight maps.">
<figure class="quarto-float quarto-float-fig figure">
<div aria-describedby="fig-selection-caption-0ceaefa1-69ba-4598-a22c-09a6ac19f8ca">
<img src="https://tidyecology.com/posts/morans-i-on-regression-residuals/index_files/figure-html/fig-selection-1.png" class="img-fluid figure-img" alt="Paired columns on warm off-white paper showing the share of 400 datasets against the number of eigenvector maps kept, from 0 to 8. Dark green columns are for stopping on lm.morantest and red columns for stopping on moran.test. Both rules most often keep one to three maps; the red columns are taller at zero, one and two maps (near 0.15, 0.26 and 0.27), the two are equal at three, and the green columns are taller from four maps upward, with green alone at seven and eight maps." width="672">
</div>
<figcaption class="quarto-float-caption-bottom quarto-float-caption quarto-float-fig" id="fig-selection-caption-0ceaefa1-69ba-4598-a22c-09a6ac19f8ca">
Figure&nbsp;4: Number of eigenvector maps kept by forward selection under the two stopping rules, over 400 datasets with a confounded null covariate.
</figcaption>
</figure>
</div>
</div>
</div>
</section>
<section id="what-to-report" class="level2">
<h2 id="what-to-report-h" class="anchored" data-anchor-id="what-to-report">What to report</h2>
<p>For residuals of a linear model fitted by least squares, test with <code>lm.morantest(fit, lw)</code> rather than <code>moran.test(residuals(fit), lw)</code> or <code>moran.mc(residuals(fit), lw, nsim)</code>. It takes the fitted <code>lm</code> object, not the residual vector, because it needs the design matrix, and it prints the expectation it used. Report that expectation next to the observed I, together with the number of columns in the model and the weights: an observed residual I of zero is a positive deviation when the null mean is -0.108. Where the sample is small or the p-value sits near the threshold, <code>lm.morantest.exact()</code> gives the exact version at little cost; on the design here its tail p-values matched the simulation, while those of the normal approximation ran too small.</p>
<p>With one or two predictors and no smooth terms the three tests agree closely, and a residual check run with <code>moran.test()</code> or <code>moran.mc()</code> reads the same way. The difference grows with every smooth column in the model: eigenvector maps, trend surface terms, spline bases of the coordinates, or environmental layers that are themselves smooth. A model built to remove spatial structure is the worst place for the raw-data null, because that is where the design is smoothest. When the test is a stopping rule, as in eigenvector selection, say which null was used. A rule on the raw-data null stops earlier and can leave detectable residual autocorrelation behind. Neither rule controls the error rate of a confounded covariate, which has to be argued separately.</p>
</section>
<section id="honest-limits" class="level2">
<h2 id="honest-limits-h" class="anchored" data-anchor-id="honest-limits">Honest limits</h2>
<p>Everything here is one layout of 150 random plots with one graph, the symmetric six-nearest-neighbour graph with row standardised weights. The expectation was checked over 20 further layouts and moved little, but the rates were measured on one. A binary or distance-weighted graph changes the constants, not the mechanism; the formula applies to any weights once it is multiplied by n over the sum of the weights.</p>
<p>The Cliff and Ord moments are exact for a linear model with independent normal errors. The eigenvector filtering post applies its stopping rule to <code>lm()</code> residuals of Poisson counts and reports Pearson residuals of a Poisson GLM; for those, the trace formula is an approximation, and the residual null of a GLM depends on its working weights. Nothing here measures how good that approximation is for counts. A parametric bootstrap from the fitted GLM, refitting and recomputing I each time, is the general route there and is not shown.</p>
<p>The size and power study fits the first m maps in a fixed order. Forward selection instead chooses the maps that best match the residuals, and after that choice the residuals are no longer a fixed projection of the errors: even <code>lm.morantest()</code> is not exact after selection, since it treats the selected maps as if they had been fixed in advance. The selection section measures how the two rules behave; it does not claim either one has an exact level.</p>
<p>The autoregressive alternative used one coefficient, <code>0.4</code>, on the same graph that defines the test. Autocorrelation at a scale the graph does not see, or at a coefficient near zero, gives lower power to every test, and the ranking of the tests was not checked there. The selection study has one confounding structure, one field generator and 40 candidate maps; its false-positive rates belong to that design, and only their failure to differ between the two rules is the point.</p>
</section>
<section id="references" class="level2">
<h2 id="references-h" class="anchored" data-anchor-id="references">References</h2>
<p>Moran PAP 1950 Biometrika 37(1-2):17-23 (<a href="https://doi.org/10.1093/biomet/37.1-2.17">10.1093/biomet/37.1-2.17</a>)</p>
<p>Cliff AD, Ord JK 1972 Geographical Analysis 4(3):267-284 (<a href="https://doi.org/10.1111/j.1538-4632.1972.tb00475.x">10.1111/j.1538-4632.1972.tb00475.x</a>)</p>
<p>Tiefelsdorf M, Boots B 1995 Environment and Planning A 27(6):985-999 (<a href="https://doi.org/10.1068/a270985">10.1068/a270985</a>)</p>
<p>Dray S, Legendre P, Peres-Neto PR 2006 Ecological Modelling 196(3-4):483-493 (<a href="https://doi.org/10.1016/j.ecolmodel.2006.02.015">10.1016/j.ecolmodel.2006.02.015</a>)</p>
</section>
<section id="related-tutorials" class="level2">
<h2 id="related-tutorials-h" class="anchored" data-anchor-id="related-tutorials">Related tutorials</h2>
<ul>
<li><a href="https://tidyecology.com/posts/spatial-autocorrelation-morans-i/">Spatial autocorrelation and Moran’s I in R</a></li>
<li><a href="https://tidyecology.com/posts/moran-eigenvector-spatial-filtering/">Moran eigenvector spatial filtering</a></li>
<li><a href="https://tidyecology.com/posts/checking-a-spatial-regression/">Checking a spatial regression</a></li>
<li><a href="https://tidyecology.com/posts/permutation-nulls-that-keep-the-map/">Permutation nulls that keep the map</a></li>
</ul>
<details class="te-repro" data-pagefind-ignore="">
<summary>Reproducibility</summary>
<ul>
<li>Code last run: 2026-10-15</li>
<li>R version 4.5.3 (2026-03-11), aarch64-apple-darwin20</li>
<li>Packages: ggplot2 4.0.3, spdep 1.4-2</li>
</ul>
</details>


<!-- -->

</section>

 ]]></description>
  <category>R</category>
  <category>spdep</category>
  <category>spatial</category>
  <category>autocorrelation</category>
  <category>regression</category>
  <category>model checking</category>
  <category>ecology tutorial</category>
  <guid isPermaLink="false">https://tidyecology.com/posts/morans-i-on-regression-residuals/</guid>
  <pubDate>Sat, 26 Sep 2026 11:00:00 GMT</pubDate>
  <media:content url="https://tidyecology.com/posts/morans-i-on-regression-residuals/thumbnail.png" medium="image" type="image/png" height="104" width="144"/>
</item>
<item>
  <title>Spatial cross-validation when the target is a map</title>
  <dc:creator>Tidy Ecology</dc:creator>
  <link>https://tidyecology.com/posts/which-spatial-cv-for-a-map/</link>
  <description><![CDATA[ 





<p><em>Corrected 7 October 2026: the post said that random ten-fold’s small excess on the random design had an obvious candidate cause in its smaller training set, and that almost all of the block overshoot sits in the kriging step; it now says that the smaller training set can be at most part of the cause, since NNDM, which keeps nearly every plot in training there, shows a similar excess at the shortest scale, and that most of the overshoot sits in the kriging step.</em></p>
<p>A county ecologist has 150 grassland plots, each with a measured standing biomass, and two covariates that exist for every cell of the county: a greenness index and a soil wetness index. She fits biomass on the two covariates, kriges the residuals, and publishes a map. The report needs a number for how wrong the map is. Random ten-fold cross-validation gives one number; a reviewer, pointing at a variogram with obvious structure, asks for spatial block cross-validation, and that gives a number about half as large again. Both are defensible on paper. Only one of them is the error of the map she is publishing.</p>
<p>This post is about that choice, and the answer does not come from the residuals. It comes from where the sample sits relative to the cells being mapped. <a href="https://tidyecology.com/posts/spatial-cross-validation-sdm/">Spatial cross-validation for SDMs</a> blocks because held-out points next to training points flatter a model on new ground, and it measures that optimistic direction; its closing section adds, in one sentence of prose, that random folds “may match the intended use” when the goal is to interpolate inside a well-surveyed region. <a href="https://tidyecology.com/posts/checking-a-tree-ensemble/">Checking a tree ensemble</a> compares the out-of-bag error with a blocked error on uniformly random points, and says the two answer different questions, the out-of-bag error for new plots in the sampled region and the blocked error for unsampled ground; read without that distinction, the blocking argument becomes a rule: report a blocked error, not the out-of-bag number, whenever location carries information. When the thing published is a map of the region that was sampled at random, that rule overstates the map’s error and can erase most of a real spatial term, and the check that settles which scheme to use is a comparison of two distance distributions, made before any fold is drawn.</p>
<p>The idea that a validation scheme estimates a particular quantity, and that the wrong scheme estimates a different one, is already on the site. <a href="https://tidyecology.com/posts/data-leakage-in-model-validation/">Data leakage in ecological model validation</a> says it for grouped rows: random folds “estimate a different one: the error of predicting a new visit to a site you have already characterised”. What this post adds is spatial distance in place of group membership, an exact map error as the truth, a sample-design arm that reverses the direction of the bias, and a diagnostic that is run on the coordinates alone. Kriging itself is introduced in <a href="https://tidyecology.com/posts/kriging-spatial-interpolation/">from scattered plots to a surface</a>, which scores ordinary kriging with plain leave-one-out and has no design arm.</p>
<p>None of the headline results are new. Wadoux, Heuvelink, de Bruin and Brus found in a 2021 biomass mapping experiment that spatial cross-validation was a more biased estimate of map accuracy than the standard kind, and argued that with a probability sample the design-based estimate of map accuracy is unbiased, so no spatial correction is needed (the design-based machinery is in <a href="https://tidyecology.com/posts/design-based-variance-and-spatial-balance/">design-based variance and spatial balance</a>). Ploton and colleagues showed the opposite failure on a large forest biomass map of central Africa, where a non-spatial validation suggested the model explained more than half the variation and a spatial one found almost none. Mila, Mateu, Pebesma and Meyer proposed nearest neighbour distance matching (NNDM) leave-one-out to sit between the two. This post is a demonstration of those papers on a map small enough to know the true error of every cell. What is measured here is narrower: how the block overshoot depends on the block side and on the residual range together, how far each scheme misstates the gain from the kriging term in both directions, whether the distance comparison picks the right scheme before any fold is drawn, and how much NNDM scatters when a clustered sample has only fifteen clusters.</p>
<div class="cell">
<div class="code-copy-outer-scaffold"><div class="sourceCode cell-code" id="cb1" style="background: #f1f3f5;"><pre class="sourceCode r code-with-copy"><code class="sourceCode r"><span id="cb1-1"><span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">library</span>(ggplot2)</span>
<span id="cb1-2"></span>
<span id="cb1-3">te_paper  <span class="ot" style="color: #003B4F;
background-color: null;
font-style: inherit;">&lt;-</span> <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"#f5f4ee"</span></span>
<span id="cb1-4">te_ink    <span class="ot" style="color: #003B4F;
background-color: null;
font-style: inherit;">&lt;-</span> <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"#16241d"</span></span>
<span id="cb1-5">te_body   <span class="ot" style="color: #003B4F;
background-color: null;
font-style: inherit;">&lt;-</span> <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"#2c3a31"</span></span>
<span id="cb1-6">te_forest <span class="ot" style="color: #003B4F;
background-color: null;
font-style: inherit;">&lt;-</span> <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"#275139"</span></span>
<span id="cb1-7">te_rust   <span class="ot" style="color: #003B4F;
background-color: null;
font-style: inherit;">&lt;-</span> <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"#b5534e"</span></span>
<span id="cb1-8">te_gold   <span class="ot" style="color: #003B4F;
background-color: null;
font-style: inherit;">&lt;-</span> <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"#c9b458"</span></span>
<span id="cb1-9">te_line   <span class="ot" style="color: #003B4F;
background-color: null;
font-style: inherit;">&lt;-</span> <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"#dad9ca"</span></span>
<span id="cb1-10"></span>
<span id="cb1-11">theme_datasheet <span class="ot" style="color: #003B4F;
background-color: null;
font-style: inherit;">&lt;-</span> <span class="cf" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">function</span>() {</span>
<span id="cb1-12">  <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">theme_minimal</span>(<span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">base_size =</span> <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">12</span>) <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">+</span></span>
<span id="cb1-13">    <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">theme</span>(<span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">plot.background  =</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">element_rect</span>(<span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">fill =</span> te_paper, <span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">colour =</span> <span class="cn" style="color: #8f5902;
background-color: null;
font-style: inherit;">NA</span>),</span>
<span id="cb1-14">          <span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">panel.background =</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">element_rect</span>(<span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">fill =</span> te_paper, <span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">colour =</span> <span class="cn" style="color: #8f5902;
background-color: null;
font-style: inherit;">NA</span>),</span>
<span id="cb1-15">          <span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">panel.grid.major =</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">element_line</span>(<span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">colour =</span> te_line, <span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">linewidth =</span> <span class="fl" style="color: #AD0000;
background-color: null;
font-style: inherit;">0.3</span>),</span>
<span id="cb1-16">          <span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">panel.grid.minor =</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">element_blank</span>(),</span>
<span id="cb1-17">          <span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">text             =</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">element_text</span>(<span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">colour =</span> te_body),</span>
<span id="cb1-18">          <span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">plot.title       =</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">element_text</span>(<span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">colour =</span> te_ink, <span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">face =</span> <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"bold"</span>),</span>
<span id="cb1-19">          <span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">plot.subtitle    =</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">element_text</span>(<span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">colour =</span> te_body),</span>
<span id="cb1-20">          <span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">axis.text        =</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">element_text</span>(<span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">colour =</span> te_body))</span>
<span id="cb1-21">}</span></code></pre></div></div>
</div>
<section id="a-map-two-samples-and-the-number-being-estimated" class="level2">
<h2 id="a-map-two-samples-and-the-number-being-estimated-h" class="anchored" data-anchor-id="a-map-two-samples-and-the-number-being-estimated">A map, two samples and the number being estimated</h2>
<p>The map is the unit square cut into a 64 by 64 grid of cells. Each of the two covariates is white noise smoothed by a Gaussian kernel (standard deviations 0.10 and 0.20 of the map side), standardised over the map. The residual field is built the same way with kernel standard deviation s, and the response in every cell is the first covariate plus half the second plus the residual field; a plot measurement adds independent noise with standard deviation 0.4, which plays the role of the nugget. Three residual scales are run, s = 0.03, 0.06 and 0.12.</p>
<p>Two samples of 150 plots are drawn from the cells. The random design is a simple random sample. The clustered design is fifteen clusters of ten plots each, every cluster drawn from the cells within 0.06 of a centre placed uniformly in the central part of the map, which is roughly what a survey looks like when plots follow road access or a handful of cooperating landowners.</p>
<p>The model is ordinary least squares on the two covariates followed by simple kriging of its residuals. The kriging uses the covariance of the process that generates the residual field, so the only error the cross-validation has to judge is the error of estimation, not the error of a fitted variogram; a later section refits the kernel from the data to see whether that matters. The same model without the kriging step, least squares alone, is carried along as the comparison for the gain.</p>
<div class="cell">
<div class="code-copy-outer-scaffold"><div class="sourceCode cell-code" id="cb2" style="background: #f1f3f5;"><pre class="sourceCode r code-with-copy"><code class="sourceCode r"><span id="cb2-1">g_side  <span class="ot" style="color: #003B4F;
background-color: null;
font-style: inherit;">&lt;-</span> <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">64</span></span>
<span id="cb2-2">g_torus <span class="ot" style="color: #003B4F;
background-color: null;
font-style: inherit;">&lt;-</span> <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">128</span></span>
<span id="cb2-3">cell_x  <span class="ot" style="color: #003B4F;
background-color: null;
font-style: inherit;">&lt;-</span> (<span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">rep</span>(<span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">seq_len</span>(g_side), <span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">times =</span> g_side) <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">-</span> <span class="fl" style="color: #AD0000;
background-color: null;
font-style: inherit;">0.5</span>) <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">/</span> g_side</span>
<span id="cb2-4">cell_y  <span class="ot" style="color: #003B4F;
background-color: null;
font-style: inherit;">&lt;-</span> (<span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">rep</span>(<span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">seq_len</span>(g_side), <span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">each =</span> g_side) <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">-</span> <span class="fl" style="color: #AD0000;
background-color: null;
font-style: inherit;">0.5</span>) <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">/</span> g_side</span>
<span id="cb2-5">xy_all  <span class="ot" style="color: #003B4F;
background-color: null;
font-style: inherit;">&lt;-</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">cbind</span>(cell_x, cell_y)</span>
<span id="cb2-6">n_cell  <span class="ot" style="color: #003B4F;
background-color: null;
font-style: inherit;">&lt;-</span> g_side<span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">^</span><span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">2</span></span>
<span id="cb2-7">nug_sd  <span class="ot" style="color: #003B4F;
background-color: null;
font-style: inherit;">&lt;-</span> <span class="fl" style="color: #AD0000;
background-color: null;
font-style: inherit;">0.4</span></span>
<span id="cb2-8">n_samp  <span class="ot" style="color: #003B4F;
background-color: null;
font-style: inherit;">&lt;-</span> <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">150</span></span>
<span id="cb2-9">n_clus  <span class="ot" style="color: #003B4F;
background-color: null;
font-style: inherit;">&lt;-</span> <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">15</span></span>
<span id="cb2-10">clus_r  <span class="ot" style="color: #003B4F;
background-color: null;
font-style: inherit;">&lt;-</span> <span class="fl" style="color: #AD0000;
background-color: null;
font-style: inherit;">0.06</span></span>
<span id="cb2-11"></span>
<span id="cb2-12"><span class="co" style="color: #5E5E5E;
background-color: null;
font-style: inherit;"># Gaussian-kernel smoothed white noise on a torus, cropped and standardised</span></span>
<span id="cb2-13">smooth_field <span class="ot" style="color: #003B4F;
background-color: null;
font-style: inherit;">&lt;-</span> <span class="cf" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">function</span>(s_ker) {</span>
<span id="cb2-14">  noise <span class="ot" style="color: #003B4F;
background-color: null;
font-style: inherit;">&lt;-</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">matrix</span>(<span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">rnorm</span>(g_torus <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">*</span> g_torus), g_torus)</span>
<span id="cb2-15">  lag_d   <span class="ot" style="color: #003B4F;
background-color: null;
font-style: inherit;">&lt;-</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">pmin</span>(<span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">0</span><span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">:</span>(g_torus <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">-</span> <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">1</span>), g_torus <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">-</span> <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">0</span><span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">:</span>(g_torus <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">-</span> <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">1</span>)) <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">/</span> g_side</span>
<span id="cb2-16">  kern  <span class="ot" style="color: #003B4F;
background-color: null;
font-style: inherit;">&lt;-</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">outer</span>(<span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">exp</span>(<span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">-</span>lag_d<span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">^</span><span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">2</span> <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">/</span> (<span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">2</span> <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">*</span> s_ker<span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">^</span><span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">2</span>)), <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">exp</span>(<span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">-</span>lag_d<span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">^</span><span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">2</span> <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">/</span> (<span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">2</span> <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">*</span> s_ker<span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">^</span><span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">2</span>)))</span>
<span id="cb2-17">  fld   <span class="ot" style="color: #003B4F;
background-color: null;
font-style: inherit;">&lt;-</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">Re</span>(<span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">fft</span>(<span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">fft</span>(noise) <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">*</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">fft</span>(kern), <span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">inverse =</span> <span class="cn" style="color: #8f5902;
background-color: null;
font-style: inherit;">TRUE</span>))[<span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">1</span><span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">:</span>g_side, <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">1</span><span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">:</span>g_side]</span>
<span id="cb2-18">  v <span class="ot" style="color: #003B4F;
background-color: null;
font-style: inherit;">&lt;-</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">as.vector</span>(fld)</span>
<span id="cb2-19">  (v <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">-</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">mean</span>(v)) <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">/</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">sd</span>(v)</span>
<span id="cb2-20">}</span>
<span id="cb2-21">cross_dist <span class="ot" style="color: #003B4F;
background-color: null;
font-style: inherit;">&lt;-</span> <span class="cf" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">function</span>(a, b) {</span>
<span id="cb2-22">  <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">sqrt</span>(<span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">outer</span>(a[, <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">1</span>], b[, <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">1</span>], <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"-"</span>)<span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">^</span><span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">2</span> <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">+</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">outer</span>(a[, <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">2</span>], b[, <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">2</span>], <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"-"</span>)<span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">^</span><span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">2</span>)</span>
<span id="cb2-23">}</span>
<span id="cb2-24"><span class="co" style="color: #5E5E5E;
background-color: null;
font-style: inherit;"># white noise smoothed by a Gaussian kernel of sd s has covariance exp(-d^2 / (4 s^2))</span></span>
<span id="cb2-25">cov_fun <span class="ot" style="color: #003B4F;
background-color: null;
font-style: inherit;">&lt;-</span> <span class="cf" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">function</span>(d, s_ker, <span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">sill =</span> <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">1</span>) sill <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">*</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">exp</span>(<span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">-</span>d<span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">^</span><span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">2</span> <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">/</span> (<span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">4</span> <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">*</span> s_ker<span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">^</span><span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">2</span>))</span>
<span id="cb2-26"></span>
<span id="cb2-27">draw_sample <span class="ot" style="color: #003B4F;
background-color: null;
font-style: inherit;">&lt;-</span> <span class="cf" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">function</span>(design) {</span>
<span id="cb2-28">  <span class="cf" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">if</span> (design <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">==</span> <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"random"</span>) <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">return</span>(<span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">sample</span>(n_cell, n_samp))</span>
<span id="cb2-29">  cen <span class="ot" style="color: #003B4F;
background-color: null;
font-style: inherit;">&lt;-</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">cbind</span>(<span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">runif</span>(n_clus, <span class="fl" style="color: #AD0000;
background-color: null;
font-style: inherit;">0.08</span>, <span class="fl" style="color: #AD0000;
background-color: null;
font-style: inherit;">0.92</span>), <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">runif</span>(n_clus, <span class="fl" style="color: #AD0000;
background-color: null;
font-style: inherit;">0.08</span>, <span class="fl" style="color: #AD0000;
background-color: null;
font-style: inherit;">0.92</span>))</span>
<span id="cb2-30">  idx <span class="ot" style="color: #003B4F;
background-color: null;
font-style: inherit;">&lt;-</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">integer</span>(<span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">0</span>)</span>
<span id="cb2-31">  <span class="cf" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">for</span> (k <span class="cf" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">in</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">seq_len</span>(n_clus)) {</span>
<span id="cb2-32">    d_cen <span class="ot" style="color: #003B4F;
background-color: null;
font-style: inherit;">&lt;-</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">sqrt</span>((cell_x <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">-</span> cen[k, <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">1</span>])<span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">^</span><span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">2</span> <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">+</span> (cell_y <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">-</span> cen[k, <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">2</span>])<span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">^</span><span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">2</span>)</span>
<span id="cb2-33">    cand  <span class="ot" style="color: #003B4F;
background-color: null;
font-style: inherit;">&lt;-</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">setdiff</span>(<span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">which</span>(d_cen <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">&lt;</span> clus_r), idx)</span>
<span id="cb2-34">    idx   <span class="ot" style="color: #003B4F;
background-color: null;
font-style: inherit;">&lt;-</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">c</span>(idx, cand[<span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">sample.int</span>(<span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">length</span>(cand), n_samp <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">/</span> n_clus)])</span>
<span id="cb2-35">  }</span>
<span id="cb2-36">  idx</span>
<span id="cb2-37">}</span></code></pre></div></div>
</div>
<div class="cell">
<div class="code-copy-outer-scaffold"><div class="sourceCode cell-code" id="cb3" style="background: #f1f3f5;"><pre class="sourceCode r code-with-copy"><code class="sourceCode r"><span id="cb3-1"><span class="co" style="color: #5E5E5E;
background-color: null;
font-style: inherit;"># least squares on the two covariates, then simple kriging of the residuals</span></span>
<span id="cb3-2">fit_pred <span class="ot" style="color: #003B4F;
background-color: null;
font-style: inherit;">&lt;-</span> <span class="cf" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">function</span>(itr, new_xy, new_x, s_ker, y, xmat, xy, dmat,</span>
<span id="cb3-3">                     <span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">krige =</span> <span class="cn" style="color: #8f5902;
background-color: null;
font-style: inherit;">TRUE</span>, <span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">sill =</span> <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">1</span>, <span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">nug =</span> nug_sd<span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">^</span><span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">2</span>) {</span>
<span id="cb3-4">  des  <span class="ot" style="color: #003B4F;
background-color: null;
font-style: inherit;">&lt;-</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">cbind</span>(<span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">1</span>, xmat[itr, , <span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">drop =</span> <span class="cn" style="color: #8f5902;
background-color: null;
font-style: inherit;">FALSE</span>])</span>
<span id="cb3-5">  coef_ls <span class="ot" style="color: #003B4F;
background-color: null;
font-style: inherit;">&lt;-</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">qr.solve</span>(des, y[itr])</span>
<span id="cb3-6">  resid_tr <span class="ot" style="color: #003B4F;
background-color: null;
font-style: inherit;">&lt;-</span> y[itr] <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">-</span> des <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">%*%</span> coef_ls</span>
<span id="cb3-7">  mu <span class="ot" style="color: #003B4F;
background-color: null;
font-style: inherit;">&lt;-</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">cbind</span>(<span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">1</span>, new_x) <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">%*%</span> coef_ls</span>
<span id="cb3-8">  <span class="cf" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">if</span> (<span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">!</span>krige) <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">return</span>(<span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">as.vector</span>(mu))</span>
<span id="cb3-9">  kmat <span class="ot" style="color: #003B4F;
background-color: null;
font-style: inherit;">&lt;-</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">cov_fun</span>(dmat[itr, itr], s_ker, sill)</span>
<span id="cb3-10">  <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">diag</span>(kmat) <span class="ot" style="color: #003B4F;
background-color: null;
font-style: inherit;">&lt;-</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">diag</span>(kmat) <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">+</span> nug</span>
<span id="cb3-11">  k0 <span class="ot" style="color: #003B4F;
background-color: null;
font-style: inherit;">&lt;-</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">cov_fun</span>(<span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">cross_dist</span>(new_xy, xy[itr, , <span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">drop =</span> <span class="cn" style="color: #8f5902;
background-color: null;
font-style: inherit;">FALSE</span>]), s_ker, sill)</span>
<span id="cb3-12">  <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">as.vector</span>(mu <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">+</span> k0 <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">%*%</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">solve</span>(kmat, resid_tr))</span>
<span id="cb3-13">}</span>
<span id="cb3-14">cv_rmse <span class="ot" style="color: #003B4F;
background-color: null;
font-style: inherit;">&lt;-</span> <span class="cf" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">function</span>(folds, s_ker, y, xmat, xy, dmat, <span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">krige =</span> <span class="cn" style="color: #8f5902;
background-color: null;
font-style: inherit;">TRUE</span>,</span>
<span id="cb3-15">                    <span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">sill =</span> <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">1</span>, <span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">nug =</span> nug_sd<span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">^</span><span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">2</span>) {</span>
<span id="cb3-16">  pr <span class="ot" style="color: #003B4F;
background-color: null;
font-style: inherit;">&lt;-</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">numeric</span>(<span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">length</span>(y))</span>
<span id="cb3-17">  <span class="cf" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">for</span> (f <span class="cf" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">in</span> folds) {</span>
<span id="cb3-18">    pr[f<span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">$</span>te] <span class="ot" style="color: #003B4F;
background-color: null;
font-style: inherit;">&lt;-</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">fit_pred</span>(f<span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">$</span>tr, xy[f<span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">$</span>te, , <span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">drop =</span> <span class="cn" style="color: #8f5902;
background-color: null;
font-style: inherit;">FALSE</span>], xmat[f<span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">$</span>te, , <span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">drop =</span> <span class="cn" style="color: #8f5902;
background-color: null;
font-style: inherit;">FALSE</span>],</span>
<span id="cb3-19">                         s_ker, y, xmat, xy, dmat, krige, sill, nug)</span>
<span id="cb3-20">  }</span>
<span id="cb3-21">  <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">sqrt</span>(<span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">mean</span>((pr <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">-</span> y)<span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">^</span><span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">2</span>))</span>
<span id="cb3-22">}</span></code></pre></div></div>
</div>
<p>The number every scheme is trying to estimate is fixed before any fold is drawn. The model is fitted to all 150 plots and predicts every cell that holds no plot, 3946 of them. The true map error is the root mean squared difference between those predictions and the true cell values, with the nugget variance added so that it sits on the same footing as a cross-validated error, which is scored against noisy plot measurements. It is the error of this map over this region: not over a new region, and not over the sample.</p>
<div class="cell">
<div class="code-copy-outer-scaffold"><div class="sourceCode cell-code" id="cb4" style="background: #f1f3f5;"><pre class="sourceCode r code-with-copy"><code class="sourceCode r"><span id="cb4-1">s_vals   <span class="ot" style="color: #003B4F;
background-color: null;
font-style: inherit;">&lt;-</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">c</span>(<span class="fl" style="color: #AD0000;
background-color: null;
font-style: inherit;">0.03</span>, <span class="fl" style="color: #AD0000;
background-color: null;
font-style: inherit;">0.06</span>, <span class="fl" style="color: #AD0000;
background-color: null;
font-style: inherit;">0.12</span>)</span>
<span id="cb4-2">range_05 <span class="ot" style="color: #003B4F;
background-color: null;
font-style: inherit;">&lt;-</span> <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">2</span> <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">*</span> s_vals <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">*</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">sqrt</span>(<span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">log</span>(<span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">20</span>))</span>
<span id="cb4-3"><span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">names</span>(range_05) <span class="ot" style="color: #003B4F;
background-color: null;
font-style: inherit;">&lt;-</span> s_vals</span>
<span id="cb4-4">cor_side <span class="ot" style="color: #003B4F;
background-color: null;
font-style: inherit;">&lt;-</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">exp</span>(<span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">-</span><span class="fl" style="color: #AD0000;
background-color: null;
font-style: inherit;">0.2</span><span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">^</span><span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">2</span> <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">/</span> (<span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">4</span> <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">*</span> s_vals<span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">^</span><span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">2</span>))</span>
<span id="cb4-5"><span class="co" style="color: #5E5E5E;
background-color: null;
font-style: inherit;"># each field is centred and rescaled over the map: realised correlation at a lag of 13 cells</span></span>
<span id="cb4-6"><span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">set.seed</span>(<span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">128</span>)</span>
<span id="cb4-7">lag_c <span class="ot" style="color: #003B4F;
background-color: null;
font-style: inherit;">&lt;-</span> <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">13</span></span>
<span id="cb4-8">real_cor <span class="ot" style="color: #003B4F;
background-color: null;
font-style: inherit;">&lt;-</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">mean</span>(<span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">replicate</span>(<span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">40</span>, {</span>
<span id="cb4-9">  zm <span class="ot" style="color: #003B4F;
background-color: null;
font-style: inherit;">&lt;-</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">matrix</span>(<span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">smooth_field</span>(<span class="fl" style="color: #AD0000;
background-color: null;
font-style: inherit;">0.12</span>), g_side)</span>
<span id="cb4-10">  (<span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">mean</span>(zm[<span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">1</span><span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">:</span>(g_side <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">-</span> lag_c), ] <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">*</span> zm[(<span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">1</span> <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">+</span> lag_c)<span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">:</span>g_side, ]) <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">+</span></span>
<span id="cb4-11">     <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">mean</span>(zm[, <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">1</span><span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">:</span>(g_side <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">-</span> lag_c)] <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">*</span> zm[, (<span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">1</span> <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">+</span> lag_c)<span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">:</span>g_side])) <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">/</span> <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">2</span></span>
<span id="cb4-12">}))</span>
<span id="cb4-13">proc_cor <span class="ot" style="color: #003B4F;
background-color: null;
font-style: inherit;">&lt;-</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">exp</span>(<span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">-</span>(lag_c <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">/</span> g_side)<span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">^</span><span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">2</span> <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">/</span> (<span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">4</span> <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">*</span> <span class="fl" style="color: #AD0000;
background-color: null;
font-style: inherit;">0.12</span><span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">^</span><span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">2</span>))</span></code></pre></div></div>
</div>
<p>A block side means something only against the range of the residual field, so the range has to be defined before any side is quoted. Here it is the distance at which the residual correlation, exp(-d^2 / (4 s^2)) for a Gaussian kernel of standard deviation s applied to white noise, falls to 0.05; that distance is 2 s sqrt(ln 20), which gives 0.104, 0.208 and 0.415 for the three scales. A block of side 0.2 is therefore close to one range at s = 0.06, about two ranges at s = 0.03 and about half a range at s = 0.12, where two cells 0.2 apart still have a residual correlation of 0.50 in the process. Each simulated field is then centred and rescaled over the map, which lowers the correlation a single map actually shows: at a lag of 13 cells (0.203) and s = 0.12 it averages 0.37 over 40 fields, against 0.49 for the process. The kriging uses the process covariance, so at the longest scale it assumes more correlation than the fields it is applied to actually show.</p>
<div class="cell">
<div class="code-copy-outer-scaffold"><div class="sourceCode cell-code" id="cb5" style="background: #f1f3f5;"><pre class="sourceCode r code-with-copy"><code class="sourceCode r"><span id="cb5-1">random_folds <span class="ot" style="color: #003B4F;
background-color: null;
font-style: inherit;">&lt;-</span> <span class="cf" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">function</span>(n, <span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">n_fold =</span> <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">10</span>) {</span>
<span id="cb5-2">  fr <span class="ot" style="color: #003B4F;
background-color: null;
font-style: inherit;">&lt;-</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">sample</span>(<span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">rep</span>(<span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">seq_len</span>(n_fold), <span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">length.out =</span> n))</span>
<span id="cb5-3">  <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">lapply</span>(<span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">seq_len</span>(n_fold), <span class="cf" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">function</span>(k) <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">list</span>(<span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">te =</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">which</span>(fr <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">==</span> k), <span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">tr =</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">which</span>(fr <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">!=</span> k)))</span>
<span id="cb5-4">}</span>
<span id="cb5-5"><span class="co" style="color: #5E5E5E;
background-color: null;
font-style: inherit;"># square blocks of side 1 / k_side, blocks dealt at random to five folds</span></span>
<span id="cb5-6">block_folds <span class="ot" style="color: #003B4F;
background-color: null;
font-style: inherit;">&lt;-</span> <span class="cf" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">function</span>(xy, k_side, <span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">n_fold =</span> <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">5</span>) {</span>
<span id="cb5-7">  bid <span class="ot" style="color: #003B4F;
background-color: null;
font-style: inherit;">&lt;-</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">as.integer</span>(<span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">factor</span>(<span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">paste</span>(<span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">ceiling</span>(xy[, <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">1</span>] <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">*</span> k_side), <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">ceiling</span>(xy[, <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">2</span>] <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">*</span> k_side))))</span>
<span id="cb5-8">  bf  <span class="ot" style="color: #003B4F;
background-color: null;
font-style: inherit;">&lt;-</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">sample</span>(<span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">rep</span>(<span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">seq_len</span>(n_fold), <span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">length.out =</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">max</span>(bid)))[bid]</span>
<span id="cb5-9">  <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">lapply</span>(<span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">seq_len</span>(n_fold), <span class="cf" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">function</span>(k) <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">list</span>(<span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">te =</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">which</span>(bf <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">==</span> k), <span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">tr =</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">which</span>(bf <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">!=</span> k)))</span>
<span id="cb5-10">}</span>
<span id="cb5-11"><span class="co" style="color: #5E5E5E;
background-color: null;
font-style: inherit;"># NNDM leave-one-out: a line-by-line port of the loop in CAST::nndm (Mila et al. 2022)</span></span>
<span id="cb5-12">nndm_folds <span class="ot" style="color: #003B4F;
background-color: null;
font-style: inherit;">&lt;-</span> <span class="cf" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">function</span>(dmat, gpred, <span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">min_train =</span> <span class="fl" style="color: #AD0000;
background-color: null;
font-style: inherit;">0.5</span>) {</span>
<span id="cb5-13">  n <span class="ot" style="color: #003B4F;
background-color: null;
font-style: inherit;">&lt;-</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">nrow</span>(dmat)</span>
<span id="cb5-14">  tdist <span class="ot" style="color: #003B4F;
background-color: null;
font-style: inherit;">&lt;-</span> dmat</span>
<span id="cb5-15">  <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">diag</span>(tdist) <span class="ot" style="color: #003B4F;
background-color: null;
font-style: inherit;">&lt;-</span> <span class="cn" style="color: #8f5902;
background-color: null;
font-style: inherit;">NA</span></span>
<span id="cb5-16">  phi   <span class="ot" style="color: #003B4F;
background-color: null;
font-style: inherit;">&lt;-</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">max</span>(<span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">c</span>(gpred, <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">c</span>(tdist)), <span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">na.rm =</span> <span class="cn" style="color: #8f5902;
background-color: null;
font-style: inherit;">TRUE</span>) <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">+</span> <span class="fl" style="color: #AD0000;
background-color: null;
font-style: inherit;">1e-9</span></span>
<span id="cb5-17">  gstar <span class="ot" style="color: #003B4F;
background-color: null;
font-style: inherit;">&lt;-</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">apply</span>(tdist, <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">1</span>, min, <span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">na.rm =</span> <span class="cn" style="color: #8f5902;
background-color: null;
font-style: inherit;">TRUE</span>)</span>
<span id="cb5-18">  rmin  <span class="ot" style="color: #003B4F;
background-color: null;
font-style: inherit;">&lt;-</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">min</span>(gstar)</span>
<span id="cb5-19">  jmin  <span class="ot" style="color: #003B4F;
background-color: null;
font-style: inherit;">&lt;-</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">which.min</span>(gstar)[<span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">1</span>]</span>
<span id="cb5-20">  kmin  <span class="ot" style="color: #003B4F;
background-color: null;
font-style: inherit;">&lt;-</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">which</span>(tdist[jmin, ] <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">==</span> rmin)</span>
<span id="cb5-21">  <span class="cf" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">while</span> (rmin <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">&lt;=</span> phi) {</span>
<span id="cb5-22">    <span class="cf" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">if</span> ((<span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">sum</span>(gstar <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">&lt;=</span> rmin) <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">-</span> <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">1</span>) <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">/</span> n <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">&gt;=</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">mean</span>(gpred <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">&lt;=</span> rmin) <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">&amp;&amp;</span></span>
<span id="cb5-23">        <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">sum</span>(<span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">!</span><span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">is.na</span>(tdist[jmin, ])) <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">/</span> n <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">&gt;</span> min_train) {</span>
<span id="cb5-24">      tdist[jmin, kmin] <span class="ot" style="color: #003B4F;
background-color: null;
font-style: inherit;">&lt;-</span> <span class="cn" style="color: #8f5902;
background-color: null;
font-style: inherit;">NA</span></span>
<span id="cb5-25">      gstar[jmin] <span class="ot" style="color: #003B4F;
background-color: null;
font-style: inherit;">&lt;-</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">min</span>(tdist[jmin, ], <span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">na.rm =</span> <span class="cn" style="color: #8f5902;
background-color: null;
font-style: inherit;">TRUE</span>)</span>
<span id="cb5-26">      rmin <span class="ot" style="color: #003B4F;
background-color: null;
font-style: inherit;">&lt;-</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">min</span>(gstar[gstar <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">&gt;=</span> rmin])</span>
<span id="cb5-27">    } <span class="cf" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">else</span> <span class="cf" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">if</span> (<span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">sum</span>(gstar <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">&gt;</span> rmin) <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">==</span> <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">0</span>) {</span>
<span id="cb5-28">      <span class="cf" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">break</span></span>
<span id="cb5-29">    } <span class="cf" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">else</span> {</span>
<span id="cb5-30">      rmin <span class="ot" style="color: #003B4F;
background-color: null;
font-style: inherit;">&lt;-</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">min</span>(gstar[gstar <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">&gt;</span> rmin])</span>
<span id="cb5-31">    }</span>
<span id="cb5-32">    jmin <span class="ot" style="color: #003B4F;
background-color: null;
font-style: inherit;">&lt;-</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">which</span>(gstar <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">==</span> rmin)[<span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">1</span>]</span>
<span id="cb5-33">    kmin <span class="ot" style="color: #003B4F;
background-color: null;
font-style: inherit;">&lt;-</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">which</span>(tdist[jmin, ] <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">==</span> rmin)</span>
<span id="cb5-34">  }</span>
<span id="cb5-35">  <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">lapply</span>(<span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">seq_len</span>(n), <span class="cf" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">function</span>(j) <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">list</span>(<span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">te =</span> j, <span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">tr =</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">which</span>(<span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">!</span><span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">is.na</span>(tdist[j, ]))))</span>
<span id="cb5-36">}</span>
<span id="cb5-37"><span class="co" style="color: #5E5E5E;
background-color: null;
font-style: inherit;"># distance from each held-out point to the nearest point its fold trains on</span></span>
<span id="cb5-38">test_nn <span class="ot" style="color: #003B4F;
background-color: null;
font-style: inherit;">&lt;-</span> <span class="cf" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">function</span>(folds, dmat) {</span>
<span id="cb5-39">  te_all <span class="ot" style="color: #003B4F;
background-color: null;
font-style: inherit;">&lt;-</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">unlist</span>(<span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">lapply</span>(folds, <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">`</span><span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">[[</span><span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">`</span>, <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"te"</span>))</span>
<span id="cb5-40">  nn_all <span class="ot" style="color: #003B4F;
background-color: null;
font-style: inherit;">&lt;-</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">unlist</span>(<span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">lapply</span>(folds, <span class="cf" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">function</span>(f) <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">apply</span>(dmat[f<span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">$</span>te, f<span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">$</span>tr, <span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">drop =</span> <span class="cn" style="color: #8f5902;
background-color: null;
font-style: inherit;">FALSE</span>], <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">1</span>, min)))</span>
<span id="cb5-41">  nn_all[<span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">order</span>(te_all)]</span>
<span id="cb5-42">}</span>
<span id="cb5-43"><span class="co" style="color: #5E5E5E;
background-color: null;
font-style: inherit;"># area between two empirical distribution functions (the W statistic of Mila et al.)</span></span>
<span id="cb5-44">w_stat <span class="ot" style="color: #003B4F;
background-color: null;
font-style: inherit;">&lt;-</span> <span class="cf" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">function</span>(a, b) {</span>
<span id="cb5-45">  gr <span class="ot" style="color: #003B4F;
background-color: null;
font-style: inherit;">&lt;-</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">sort</span>(<span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">unique</span>(<span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">c</span>(a, b)))</span>
<span id="cb5-46">  <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">sum</span>(<span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">abs</span>(<span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">ecdf</span>(a)(gr) <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">-</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">ecdf</span>(b)(gr))[<span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">-</span><span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">length</span>(gr)] <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">*</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">diff</span>(gr))</span>
<span id="cb5-47">}</span></code></pre></div></div>
</div>
<p>Three families of scheme are compared. Random ten-fold deals the plots to folds at random. Block five-fold cuts the map into squares of side 0.1, 0.2 or 1/3 and deals whole squares to five folds, which is what a block cross-validation package does with a regular grid. NNDM leave-one-out holds out one plot at a time, and before it predicts that plot it also removes from the training set every plot closer than it needs to be: the removals continue, smallest distance first, until the distribution of held-out-to-training distances matches the distribution of distances from the prediction cells to the sample. The function above is a line-by-line port of the loop in the <code>CAST</code> package’s <code>nndm()</code>, with its defaults (no training set shrinks below half the data, and the search runs to the largest distance in the data). Plain leave-one-out is not run and carries no number below.</p>
<p>The last two helpers are the diagnostic. <code>test_nn()</code> returns, for each plot, the distance to the nearest plot its fold trains on; <code>w_stat()</code> is the area between two empirical distribution functions, the statistic Mila and colleagues use to say how far a scheme’s distances are from the prediction distances. Neither needs a response value or a model fit.</p>
<div class="cell">
<div class="code-copy-outer-scaffold"><div class="sourceCode cell-code" id="cb6" style="background: #f1f3f5;"><pre class="sourceCode r code-with-copy"><code class="sourceCode r"><span id="cb6-1"><span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">set.seed</span>(<span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">61</span>)</span>
<span id="cb6-2">z_show  <span class="ot" style="color: #003B4F;
background-color: null;
font-style: inherit;">&lt;-</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">smooth_field</span>(<span class="fl" style="color: #AD0000;
background-color: null;
font-style: inherit;">0.06</span>)</span>
<span id="cb6-3">idx_ran <span class="ot" style="color: #003B4F;
background-color: null;
font-style: inherit;">&lt;-</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">draw_sample</span>(<span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"random"</span>)</span>
<span id="cb6-4">idx_clu <span class="ot" style="color: #003B4F;
background-color: null;
font-style: inherit;">&lt;-</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">draw_sample</span>(<span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"clustered"</span>)</span>
<span id="cb6-5">lab_ran <span class="ot" style="color: #003B4F;
background-color: null;
font-style: inherit;">&lt;-</span> <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"simple random sample"</span></span>
<span id="cb6-6">lab_clu <span class="ot" style="color: #003B4F;
background-color: null;
font-style: inherit;">&lt;-</span> <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"15 clusters of 10"</span></span>
<span id="cb6-7">field_df <span class="ot" style="color: #003B4F;
background-color: null;
font-style: inherit;">&lt;-</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">rbind</span>(<span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">data.frame</span>(<span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">x =</span> cell_x, <span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">y =</span> cell_y, <span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">z =</span> z_show, <span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">design =</span> lab_ran),</span>
<span id="cb6-8">                  <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">data.frame</span>(<span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">x =</span> cell_x, <span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">y =</span> cell_y, <span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">z =</span> z_show, <span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">design =</span> lab_clu))</span>
<span id="cb6-9">plot_df  <span class="ot" style="color: #003B4F;
background-color: null;
font-style: inherit;">&lt;-</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">rbind</span>(<span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">data.frame</span>(<span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">x =</span> cell_x[idx_ran], <span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">y =</span> cell_y[idx_ran], <span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">design =</span> lab_ran),</span>
<span id="cb6-10">                  <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">data.frame</span>(<span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">x =</span> cell_x[idx_clu], <span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">y =</span> cell_y[idx_clu], <span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">design =</span> lab_clu))</span>
<span id="cb6-11"><span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">ggplot</span>(field_df, <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">aes</span>(x, y)) <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">+</span></span>
<span id="cb6-12">  <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">geom_raster</span>(<span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">aes</span>(<span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">fill =</span> z)) <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">+</span></span>
<span id="cb6-13">  <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">geom_hline</span>(<span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">yintercept =</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">seq</span>(<span class="fl" style="color: #AD0000;
background-color: null;
font-style: inherit;">0.2</span>, <span class="fl" style="color: #AD0000;
background-color: null;
font-style: inherit;">0.8</span>, <span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">by =</span> <span class="fl" style="color: #AD0000;
background-color: null;
font-style: inherit;">0.2</span>), <span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">colour =</span> te_ink, <span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">linewidth =</span> <span class="fl" style="color: #AD0000;
background-color: null;
font-style: inherit;">0.25</span>, <span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">alpha =</span> <span class="fl" style="color: #AD0000;
background-color: null;
font-style: inherit;">0.6</span>) <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">+</span></span>
<span id="cb6-14">  <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">geom_vline</span>(<span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">xintercept =</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">seq</span>(<span class="fl" style="color: #AD0000;
background-color: null;
font-style: inherit;">0.2</span>, <span class="fl" style="color: #AD0000;
background-color: null;
font-style: inherit;">0.8</span>, <span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">by =</span> <span class="fl" style="color: #AD0000;
background-color: null;
font-style: inherit;">0.2</span>), <span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">colour =</span> te_ink, <span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">linewidth =</span> <span class="fl" style="color: #AD0000;
background-color: null;
font-style: inherit;">0.25</span>, <span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">alpha =</span> <span class="fl" style="color: #AD0000;
background-color: null;
font-style: inherit;">0.6</span>) <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">+</span></span>
<span id="cb6-15">  <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">geom_point</span>(<span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">data =</span> plot_df, <span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">shape =</span> <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">21</span>, <span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">size =</span> <span class="fl" style="color: #AD0000;
background-color: null;
font-style: inherit;">1.6</span>, <span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">fill =</span> te_ink, <span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">colour =</span> te_paper, <span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">stroke =</span> <span class="fl" style="color: #AD0000;
background-color: null;
font-style: inherit;">0.4</span>) <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">+</span></span>
<span id="cb6-16">  <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">facet_wrap</span>(<span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">~</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">factor</span>(design, <span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">levels =</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">c</span>(lab_ran, lab_clu))) <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">+</span></span>
<span id="cb6-17">  <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">scale_fill_gradient2</span>(<span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">low =</span> te_forest, <span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">mid =</span> te_paper, <span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">high =</span> te_rust, <span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">midpoint =</span> <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">0</span>,</span>
<span id="cb6-18">                       <span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">name =</span> <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"residual</span><span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">\n</span><span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">field"</span>) <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">+</span></span>
<span id="cb6-19">  <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">coord_equal</span>(<span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">expand =</span> <span class="cn" style="color: #8f5902;
background-color: null;
font-style: inherit;">FALSE</span>) <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">+</span></span>
<span id="cb6-20">  <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">labs</span>(<span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">x =</span> <span class="cn" style="color: #8f5902;
background-color: null;
font-style: inherit;">NULL</span>, <span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">y =</span> <span class="cn" style="color: #8f5902;
background-color: null;
font-style: inherit;">NULL</span>, <span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">title =</span> <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"The same map, two ways of sampling it"</span>,</span>
<span id="cb6-21">       <span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">subtitle =</span> <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"residual kernel sd 0.06; thin dark lines: blocks of side 0.2"</span>) <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">+</span></span>
<span id="cb6-22">  <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">theme_datasheet</span>() <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">+</span></span>
<span id="cb6-23">  <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">theme</span>(<span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">axis.text =</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">element_blank</span>(), <span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">panel.grid.major =</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">element_blank</span>())</span></code></pre></div></div>
<div class="cell-output-display">
<div id="fig-designs" class="quarto-float quarto-figure quarto-figure-center anchored" alt="Two square maps side by side of the same smooth residual field, shaded from dark green for negative values through off-white to red for positive values, with thin dark lines cutting each map into a five by five grid of blocks. The left map carries 150 black points spread at random over the whole square. The right map carries the same number of points bunched into fifteen tight clusters of about ten, with large parts of the map, including several red and green patches, holding no point at all.">
<figure class="quarto-float quarto-float-fig figure">
<div aria-describedby="fig-designs-caption-0ceaefa1-69ba-4598-a22c-09a6ac19f8ca">
<img src="https://tidyecology.com/posts/which-spatial-cv-for-a-map/index_files/figure-html/fig-designs-1.png" class="img-fluid figure-img" alt="Two square maps side by side of the same smooth residual field, shaded from dark green for negative values through off-white to red for positive values, with thin dark lines cutting each map into a five by five grid of blocks. The left map carries 150 black points spread at random over the whole square. The right map carries the same number of points bunched into fifteen tight clusters of about ten, with large parts of the map, including several red and green patches, holding no point at all." width="864">
</div>
<figcaption class="quarto-float-caption-bottom quarto-float-caption quarto-float-fig" id="fig-designs-caption-0ceaefa1-69ba-4598-a22c-09a6ac19f8ca">
Figure&nbsp;1: One residual field at s = 0.06 with the two sampling designs of 150 plots, and the grid of blocks of side 0.2.
</figcaption>
</figure>
</div>
</div>
</div>
</section>
<section id="five-schemes-against-the-true-map-error" class="level2">
<h2 id="five-schemes-against-the-true-map-error-h" class="anchored" data-anchor-id="five-schemes-against-the-true-map-error">Five schemes against the true map error</h2>
<p>Each draw makes new covariates, a new residual field and a new sample, fits the model once to the whole sample for the truth, and runs every scheme on the same draw, with and without the kriging step. The replication was fixed before the run: 40 draws per design at s = 0.06, the headline scale, and 20 per design at the other two scales. At s = 0.06 on the random design the draw also runs a sweep of seven block sides, and at s = 0.06 on both designs it refits the kernel, for the sections further down.</p>
<div class="cell">
<div class="code-copy-outer-scaffold"><div class="sourceCode cell-code" id="cb7" style="background: #f1f3f5;"><pre class="sourceCode r code-with-copy"><code class="sourceCode r"><span id="cb7-1">fit_kernel <span class="ot" style="color: #003B4F;
background-color: null;
font-style: inherit;">&lt;-</span> <span class="cf" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">function</span>(dmat, resid_all) {</span>
<span id="cb7-2">  s_grid   <span class="ot" style="color: #003B4F;
background-color: null;
font-style: inherit;">&lt;-</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">exp</span>(<span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">seq</span>(<span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">log</span>(<span class="fl" style="color: #AD0000;
background-color: null;
font-style: inherit;">0.01</span>), <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">log</span>(<span class="fl" style="color: #AD0000;
background-color: null;
font-style: inherit;">0.3</span>), <span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">length.out =</span> <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">25</span>))</span>
<span id="cb7-3">  tau_grid <span class="ot" style="color: #003B4F;
background-color: null;
font-style: inherit;">&lt;-</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">c</span>(<span class="fl" style="color: #AD0000;
background-color: null;
font-style: inherit;">0.02</span>, <span class="fl" style="color: #AD0000;
background-color: null;
font-style: inherit;">0.05</span>, <span class="fl" style="color: #AD0000;
background-color: null;
font-style: inherit;">0.1</span>, <span class="fl" style="color: #AD0000;
background-color: null;
font-style: inherit;">0.2</span>, <span class="fl" style="color: #AD0000;
background-color: null;
font-style: inherit;">0.4</span>, <span class="fl" style="color: #AD0000;
background-color: null;
font-style: inherit;">0.8</span>)</span>
<span id="cb7-4">  loglik <span class="ot" style="color: #003B4F;
background-color: null;
font-style: inherit;">&lt;-</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">outer</span>(s_grid, tau_grid, <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">Vectorize</span>(<span class="cf" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">function</span>(sg, tg) {</span>
<span id="cb7-5">    vm <span class="ot" style="color: #003B4F;
background-color: null;
font-style: inherit;">&lt;-</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">exp</span>(<span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">-</span>dmat<span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">^</span><span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">2</span> <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">/</span> (<span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">4</span> <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">*</span> sg<span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">^</span><span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">2</span>))</span>
<span id="cb7-6">    <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">diag</span>(vm) <span class="ot" style="color: #003B4F;
background-color: null;
font-style: inherit;">&lt;-</span> <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">1</span> <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">+</span> tg</span>
<span id="cb7-7">    ch <span class="ot" style="color: #003B4F;
background-color: null;
font-style: inherit;">&lt;-</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">chol</span>(vm)</span>
<span id="cb7-8">    u  <span class="ot" style="color: #003B4F;
background-color: null;
font-style: inherit;">&lt;-</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">backsolve</span>(ch, resid_all, <span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">transpose =</span> <span class="cn" style="color: #8f5902;
background-color: null;
font-style: inherit;">TRUE</span>)</span>
<span id="cb7-9">    <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">-</span><span class="fl" style="color: #AD0000;
background-color: null;
font-style: inherit;">0.5</span> <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">*</span> (<span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">length</span>(u) <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">*</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">log</span>(<span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">sum</span>(u<span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">^</span><span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">2</span>) <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">/</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">length</span>(u)) <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">+</span> <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">2</span> <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">*</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">sum</span>(<span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">log</span>(<span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">diag</span>(ch))))</span>
<span id="cb7-10">  }))</span>
<span id="cb7-11">  best <span class="ot" style="color: #003B4F;
background-color: null;
font-style: inherit;">&lt;-</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">which</span>(loglik <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">==</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">max</span>(loglik), <span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">arr.ind =</span> <span class="cn" style="color: #8f5902;
background-color: null;
font-style: inherit;">TRUE</span>)[<span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">1</span>, ]</span>
<span id="cb7-12">  s_hat <span class="ot" style="color: #003B4F;
background-color: null;
font-style: inherit;">&lt;-</span> s_grid[best[<span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">1</span>]]</span>
<span id="cb7-13">  tau_hat <span class="ot" style="color: #003B4F;
background-color: null;
font-style: inherit;">&lt;-</span> tau_grid[best[<span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">2</span>]]</span>
<span id="cb7-14">  vm <span class="ot" style="color: #003B4F;
background-color: null;
font-style: inherit;">&lt;-</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">exp</span>(<span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">-</span>dmat<span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">^</span><span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">2</span> <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">/</span> (<span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">4</span> <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">*</span> s_hat<span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">^</span><span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">2</span>))</span>
<span id="cb7-15">  <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">diag</span>(vm) <span class="ot" style="color: #003B4F;
background-color: null;
font-style: inherit;">&lt;-</span> <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">1</span> <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">+</span> tau_hat</span>
<span id="cb7-16">  sill_hat <span class="ot" style="color: #003B4F;
background-color: null;
font-style: inherit;">&lt;-</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">sum</span>(resid_all <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">*</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">solve</span>(vm, resid_all)) <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">/</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">length</span>(resid_all)</span>
<span id="cb7-17">  <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">c</span>(<span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">s =</span> s_hat, <span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">sill =</span> sill_hat, <span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">nug =</span> sill_hat <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">*</span> tau_hat)</span>
<span id="cb7-18">}</span>
<span id="cb7-19"></span>
<span id="cb7-20">one_draw <span class="ot" style="color: #003B4F;
background-color: null;
font-style: inherit;">&lt;-</span> <span class="cf" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">function</span>(s_ker, design, <span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">k_sides =</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">c</span>(<span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">10</span>, <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">5</span>, <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">3</span>), <span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">fitted =</span> <span class="cn" style="color: #8f5902;
background-color: null;
font-style: inherit;">FALSE</span>) {</span>
<span id="cb7-21">  x1 <span class="ot" style="color: #003B4F;
background-color: null;
font-style: inherit;">&lt;-</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">smooth_field</span>(<span class="fl" style="color: #AD0000;
background-color: null;
font-style: inherit;">0.10</span>)</span>
<span id="cb7-22">  x2 <span class="ot" style="color: #003B4F;
background-color: null;
font-style: inherit;">&lt;-</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">smooth_field</span>(<span class="fl" style="color: #AD0000;
background-color: null;
font-style: inherit;">0.20</span>)</span>
<span id="cb7-23">  z  <span class="ot" style="color: #003B4F;
background-color: null;
font-style: inherit;">&lt;-</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">smooth_field</span>(s_ker)</span>
<span id="cb7-24">  mu_all <span class="ot" style="color: #003B4F;
background-color: null;
font-style: inherit;">&lt;-</span> x1 <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">+</span> <span class="fl" style="color: #AD0000;
background-color: null;
font-style: inherit;">0.5</span> <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">*</span> x2 <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">+</span> z</span>
<span id="cb7-25">  x_all  <span class="ot" style="color: #003B4F;
background-color: null;
font-style: inherit;">&lt;-</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">cbind</span>(x1, x2)</span>
<span id="cb7-26">  idx  <span class="ot" style="color: #003B4F;
background-color: null;
font-style: inherit;">&lt;-</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">draw_sample</span>(design)</span>
<span id="cb7-27">  y    <span class="ot" style="color: #003B4F;
background-color: null;
font-style: inherit;">&lt;-</span> mu_all[idx] <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">+</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">rnorm</span>(n_samp, <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">0</span>, nug_sd)</span>
<span id="cb7-28">  xmat <span class="ot" style="color: #003B4F;
background-color: null;
font-style: inherit;">&lt;-</span> x_all[idx, ]</span>
<span id="cb7-29">  xy   <span class="ot" style="color: #003B4F;
background-color: null;
font-style: inherit;">&lt;-</span> xy_all[idx, ]</span>
<span id="cb7-30">  pc   <span class="ot" style="color: #003B4F;
background-color: null;
font-style: inherit;">&lt;-</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">setdiff</span>(<span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">seq_len</span>(n_cell), idx)</span>
<span id="cb7-31">  dmat <span class="ot" style="color: #003B4F;
background-color: null;
font-style: inherit;">&lt;-</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">as.matrix</span>(<span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">dist</span>(xy))</span>
<span id="cb7-32">  gpred <span class="ot" style="color: #003B4F;
background-color: null;
font-style: inherit;">&lt;-</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">apply</span>(<span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">cross_dist</span>(xy_all[pc, ], xy), <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">1</span>, min)</span>
<span id="cb7-33">  folds <span class="ot" style="color: #003B4F;
background-color: null;
font-style: inherit;">&lt;-</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">c</span>(<span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">list</span>(<span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">rand10 =</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">random_folds</span>(n_samp)),</span>
<span id="cb7-34">             <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">setNames</span>(<span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">lapply</span>(k_sides, <span class="cf" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">function</span>(k) <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">block_folds</span>(xy, k)),</span>
<span id="cb7-35">                      <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">paste0</span>(<span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"blk"</span>, k_sides)),</span>
<span id="cb7-36">             <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">list</span>(<span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">nndm =</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">nndm_folds</span>(dmat, gpred)))</span>
<span id="cb7-37">  w_vals <span class="ot" style="color: #003B4F;
background-color: null;
font-style: inherit;">&lt;-</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">sapply</span>(folds, <span class="cf" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">function</span>(f) <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">w_stat</span>(<span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">test_nn</span>(f, dmat), gpred))</span>
<span id="cb7-38">  out <span class="ot" style="color: #003B4F;
background-color: null;
font-style: inherit;">&lt;-</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">c</span>()</span>
<span id="cb7-39">  <span class="cf" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">for</span> (kr <span class="cf" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">in</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">c</span>(<span class="cn" style="color: #8f5902;
background-color: null;
font-style: inherit;">TRUE</span>, <span class="cn" style="color: #8f5902;
background-color: null;
font-style: inherit;">FALSE</span>)) {</span>
<span id="cb7-40">    pred  <span class="ot" style="color: #003B4F;
background-color: null;
font-style: inherit;">&lt;-</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">fit_pred</span>(<span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">seq_len</span>(n_samp), xy_all[pc, ], x_all[pc, ], s_ker,</span>
<span id="cb7-41">                      y, xmat, xy, dmat, kr)</span>
<span id="cb7-42">    truth <span class="ot" style="color: #003B4F;
background-color: null;
font-style: inherit;">&lt;-</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">sqrt</span>(<span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">mean</span>((pred <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">-</span> mu_all[pc])<span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">^</span><span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">2</span>) <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">+</span> nug_sd<span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">^</span><span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">2</span>)</span>
<span id="cb7-43">    cvs   <span class="ot" style="color: #003B4F;
background-color: null;
font-style: inherit;">&lt;-</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">sapply</span>(folds, cv_rmse, <span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">s_ker =</span> s_ker, <span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">y =</span> y, <span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">xmat =</span> xmat,</span>
<span id="cb7-44">                    <span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">xy =</span> xy, <span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">dmat =</span> dmat, <span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">krige =</span> kr)</span>
<span id="cb7-45">    out <span class="ot" style="color: #003B4F;
background-color: null;
font-style: inherit;">&lt;-</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">c</span>(out, <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">setNames</span>(<span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">c</span>(truth, cvs),</span>
<span id="cb7-46">                           <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">paste0</span>(<span class="cf" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">if</span> (kr) <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"rk_"</span> <span class="cf" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">else</span> <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"lm_"</span>, <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">c</span>(<span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"truth"</span>, <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">names</span>(folds)))))</span>
<span id="cb7-47">  }</span>
<span id="cb7-48">  out <span class="ot" style="color: #003B4F;
background-color: null;
font-style: inherit;">&lt;-</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">c</span>(out, <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">setNames</span>(w_vals, <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">paste0</span>(<span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"W_"</span>, <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">names</span>(w_vals))))</span>
<span id="cb7-49">  <span class="cf" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">if</span> (fitted) {</span>
<span id="cb7-50">    kp <span class="ot" style="color: #003B4F;
background-color: null;
font-style: inherit;">&lt;-</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">fit_kernel</span>(dmat, <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">lm.fit</span>(<span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">cbind</span>(<span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">1</span>, xmat), y)<span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">$</span>residuals)</span>
<span id="cb7-51">    pred  <span class="ot" style="color: #003B4F;
background-color: null;
font-style: inherit;">&lt;-</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">fit_pred</span>(<span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">seq_len</span>(n_samp), xy_all[pc, ], x_all[pc, ], kp[<span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"s"</span>],</span>
<span id="cb7-52">                      y, xmat, xy, dmat, <span class="cn" style="color: #8f5902;
background-color: null;
font-style: inherit;">TRUE</span>, kp[<span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"sill"</span>], kp[<span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"nug"</span>])</span>
<span id="cb7-53">    truth <span class="ot" style="color: #003B4F;
background-color: null;
font-style: inherit;">&lt;-</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">sqrt</span>(<span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">mean</span>((pred <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">-</span> mu_all[pc])<span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">^</span><span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">2</span>) <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">+</span> nug_sd<span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">^</span><span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">2</span>)</span>
<span id="cb7-54">    cvs   <span class="ot" style="color: #003B4F;
background-color: null;
font-style: inherit;">&lt;-</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">sapply</span>(folds[<span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">c</span>(<span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"rand10"</span>, <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"blk5"</span>, <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"nndm"</span>)], cv_rmse, <span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">s_ker =</span> kp[<span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"s"</span>],</span>
<span id="cb7-55">                    <span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">y =</span> y, <span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">xmat =</span> xmat, <span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">xy =</span> xy, <span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">dmat =</span> dmat, <span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">krige =</span> <span class="cn" style="color: #8f5902;
background-color: null;
font-style: inherit;">TRUE</span>,</span>
<span id="cb7-56">                    <span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">sill =</span> kp[<span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"sill"</span>], <span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">nug =</span> kp[<span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"nug"</span>])</span>
<span id="cb7-57">    out <span class="ot" style="color: #003B4F;
background-color: null;
font-style: inherit;">&lt;-</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">c</span>(out, <span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">fit_truth =</span> truth, <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">setNames</span>(cvs, <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">paste0</span>(<span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"fit_"</span>, <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">names</span>(cvs))),</span>
<span id="cb7-58">             <span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">s_hat =</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">unname</span>(kp[<span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"s"</span>]))</span>
<span id="cb7-59">  }</span>
<span id="cb7-60">  out</span>
<span id="cb7-61">}</span></code></pre></div></div>
</div>
<div class="cell">
<div class="code-copy-outer-scaffold"><div class="sourceCode cell-code" id="cb8" style="background: #f1f3f5;"><pre class="sourceCode r code-with-copy"><code class="sourceCode r"><span id="cb8-1">s_head   <span class="ot" style="color: #003B4F;
background-color: null;
font-style: inherit;">&lt;-</span> <span class="fl" style="color: #AD0000;
background-color: null;
font-style: inherit;">0.06</span></span>
<span id="cb8-2">n_head   <span class="ot" style="color: #003B4F;
background-color: null;
font-style: inherit;">&lt;-</span> <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">40</span></span>
<span id="cb8-3">n_other  <span class="ot" style="color: #003B4F;
background-color: null;
font-style: inherit;">&lt;-</span> <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">20</span></span>
<span id="cb8-4">k_sweep  <span class="ot" style="color: #003B4F;
background-color: null;
font-style: inherit;">&lt;-</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">c</span>(<span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">12</span>, <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">10</span>, <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">8</span>, <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">6</span>, <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">5</span>, <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">4</span>, <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">3</span>)</span>
<span id="cb8-5"></span>
<span id="cb8-6"><span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">set.seed</span>(<span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">3270</span>)</span>
<span id="cb8-7">cells <span class="ot" style="color: #003B4F;
background-color: null;
font-style: inherit;">&lt;-</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">list</span>()</span>
<span id="cb8-8"><span class="cf" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">for</span> (s_ker <span class="cf" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">in</span> s_vals) <span class="cf" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">for</span> (des <span class="cf" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">in</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">c</span>(<span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"random"</span>, <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"clustered"</span>)) {</span>
<span id="cb8-9">  is_head <span class="ot" style="color: #003B4F;
background-color: null;
font-style: inherit;">&lt;-</span> s_ker <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">==</span> s_head</span>
<span id="cb8-10">  ks <span class="ot" style="color: #003B4F;
background-color: null;
font-style: inherit;">&lt;-</span> <span class="cf" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">if</span> (is_head <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">&amp;&amp;</span> des <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">==</span> <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"random"</span>) k_sweep <span class="cf" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">else</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">c</span>(<span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">10</span>, <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">5</span>, <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">3</span>)</span>
<span id="cb8-11">  cells[[<span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">paste</span>(s_ker, des)]] <span class="ot" style="color: #003B4F;
background-color: null;
font-style: inherit;">&lt;-</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">t</span>(<span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">replicate</span>(<span class="cf" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">if</span> (is_head) n_head <span class="cf" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">else</span> n_other,</span>
<span id="cb8-12">                                            <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">one_draw</span>(s_ker, des, ks, <span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">fitted =</span> is_head)))</span>
<span id="cb8-13">}</span>
<span id="cb8-14">n_draw_total <span class="ot" style="color: #003B4F;
background-color: null;
font-style: inherit;">&lt;-</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">sum</span>(<span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">sapply</span>(cells, nrow))</span>
<span id="cb8-15"></span>
<span id="cb8-16">ratio_of <span class="ot" style="color: #003B4F;
background-color: null;
font-style: inherit;">&lt;-</span> <span class="cf" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">function</span>(cell, scheme, <span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">pre =</span> <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"rk"</span>) {</span>
<span id="cb8-17">  cells[[cell]][, <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">paste0</span>(pre, <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"_"</span>, scheme)] <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">/</span> cells[[cell]][, <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">paste0</span>(pre, <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"_truth"</span>)]</span>
<span id="cb8-18">}</span>
<span id="cb8-19">gain_of <span class="ot" style="color: #003B4F;
background-color: null;
font-style: inherit;">&lt;-</span> <span class="cf" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">function</span>(cell, scheme) {</span>
<span id="cb8-20">  m <span class="ot" style="color: #003B4F;
background-color: null;
font-style: inherit;">&lt;-</span> cells[[cell]]</span>
<span id="cb8-21">  (m[, <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">paste0</span>(<span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"lm_"</span>, scheme)] <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">-</span> m[, <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">paste0</span>(<span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"rk_"</span>, scheme)]) <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">/</span> (m[, <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"lm_truth"</span>] <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">-</span> m[, <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"rk_truth"</span>])</span>
<span id="cb8-22">}</span>
<span id="cb8-23">fmt_q <span class="ot" style="color: #003B4F;
background-color: null;
font-style: inherit;">&lt;-</span> <span class="cf" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">function</span>(v) <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">sprintf</span>(<span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"%.2f [%.2f, %.2f]"</span>, <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">median</span>(v), <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">min</span>(v), <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">max</span>(v))</span>
<span id="cb8-24">fmt_m <span class="ot" style="color: #003B4F;
background-color: null;
font-style: inherit;">&lt;-</span> <span class="cf" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">function</span>(v) <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">sprintf</span>(<span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"%.2f"</span>, <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">median</span>(v))</span>
<span id="cb8-25"></span>
<span id="cb8-26">scheme_lab <span class="ot" style="color: #003B4F;
background-color: null;
font-style: inherit;">&lt;-</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">c</span>(<span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">rand10 =</span> <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"random 10-fold"</span>, <span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">blk10 =</span> <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"block, side 0.1"</span>,</span>
<span id="cb8-27">                <span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">blk5 =</span> <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"block, side 0.2"</span>, <span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">blk3 =</span> <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"block, side 1/3"</span>,</span>
<span id="cb8-28">                <span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">nndm =</span> <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"NNDM leave-one-out"</span>)</span>
<span id="cb8-29">ratio_tab <span class="ot" style="color: #003B4F;
background-color: null;
font-style: inherit;">&lt;-</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">do.call</span>(rbind, <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">lapply</span>(<span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">names</span>(cells), <span class="cf" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">function</span>(cl) {</span>
<span id="cb8-30">  parts <span class="ot" style="color: #003B4F;
background-color: null;
font-style: inherit;">&lt;-</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">strsplit</span>(cl, <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">" "</span>)[[<span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">1</span>]]</span>
<span id="cb8-31">  <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">do.call</span>(rbind, <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">lapply</span>(<span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">names</span>(scheme_lab), <span class="cf" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">function</span>(sc) {</span>
<span id="cb8-32">    v <span class="ot" style="color: #003B4F;
background-color: null;
font-style: inherit;">&lt;-</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">ratio_of</span>(cl, sc)</span>
<span id="cb8-33">    <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">data.frame</span>(<span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">s_ker =</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">as.numeric</span>(parts[<span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">1</span>]), <span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">design =</span> parts[<span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">2</span>], <span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">scheme =</span> sc,</span>
<span id="cb8-34">               <span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">med =</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">median</span>(v), <span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">lo =</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">min</span>(v), <span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">hi =</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">max</span>(v))</span>
<span id="cb8-35">  }))</span>
<span id="cb8-36">}))</span></code></pre></div></div>
</div>
<div class="cell">
<div class="code-copy-outer-scaffold"><div class="sourceCode cell-code" id="cb9" style="background: #f1f3f5;"><pre class="sourceCode r code-with-copy"><code class="sourceCode r"><span id="cb9-1">q  <span class="ot" style="color: #003B4F;
background-color: null;
font-style: inherit;">&lt;-</span> <span class="cf" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">function</span>(cl, sc, <span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">pre =</span> <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"rk"</span>) <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">fmt_q</span>(<span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">ratio_of</span>(cl, sc, pre))</span>
<span id="cb9-2">qm <span class="ot" style="color: #003B4F;
background-color: null;
font-style: inherit;">&lt;-</span> <span class="cf" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">function</span>(cl, sc, <span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">pre =</span> <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"rk"</span>) <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">fmt_m</span>(<span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">ratio_of</span>(cl, sc, pre))</span>
<span id="cb9-3">gq <span class="ot" style="color: #003B4F;
background-color: null;
font-style: inherit;">&lt;-</span> <span class="cf" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">function</span>(cl, sc) <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">fmt_q</span>(<span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">gain_of</span>(cl, sc))</span>
<span id="cb9-4">gm <span class="ot" style="color: #003B4F;
background-color: null;
font-style: inherit;">&lt;-</span> <span class="cf" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">function</span>(cl, sc) <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">fmt_m</span>(<span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">gain_of</span>(cl, sc))</span>
<span id="cb9-5">n_neg <span class="ot" style="color: #003B4F;
background-color: null;
font-style: inherit;">&lt;-</span> <span class="cf" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">function</span>(cl, sc) <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">sum</span>(<span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">gain_of</span>(cl, sc) <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">&lt;</span> <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">0</span>)</span>
<span id="cb9-6">n_in  <span class="ot" style="color: #003B4F;
background-color: null;
font-style: inherit;">&lt;-</span> <span class="cf" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">function</span>(cl) <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">nrow</span>(cells[[cl]])</span>
<span id="cb9-7"></span>
<span id="cb9-8">blk_head    <span class="ot" style="color: #003B4F;
background-color: null;
font-style: inherit;">&lt;-</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">ratio_of</span>(<span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"0.06 random"</span>, <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"blk5"</span>)</span>
<span id="cb9-9">blk_head_mn <span class="ot" style="color: #003B4F;
background-color: null;
font-style: inherit;">&lt;-</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">mean</span>(blk_head)</span>
<span id="cb9-10">blk_head_se <span class="ot" style="color: #003B4F;
background-color: null;
font-style: inherit;">&lt;-</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">sd</span>(blk_head) <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">/</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">sqrt</span>(<span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">length</span>(blk_head))</span>
<span id="cb9-11">n_train_r10 <span class="ot" style="color: #003B4F;
background-color: null;
font-style: inherit;">&lt;-</span> n_samp <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">*</span> <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">9</span> <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">/</span> <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">10</span></span>
<span id="cb9-12">n_train_b5  <span class="ot" style="color: #003B4F;
background-color: null;
font-style: inherit;">&lt;-</span> n_samp <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">*</span> <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">4</span> <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">/</span> <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">5</span></span>
<span id="cb9-13">nndm_clu    <span class="ot" style="color: #003B4F;
background-color: null;
font-style: inherit;">&lt;-</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">unlist</span>(<span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">lapply</span>(<span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">paste</span>(s_vals, <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"clustered"</span>), ratio_of, <span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">scheme =</span> <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"nndm"</span>))</span>
<span id="cb9-14">nndm_clu_lo <span class="ot" style="color: #003B4F;
background-color: null;
font-style: inherit;">&lt;-</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">min</span>(nndm_clu)</span>
<span id="cb9-15">nndm_clu_hi <span class="ot" style="color: #003B4F;
background-color: null;
font-style: inherit;">&lt;-</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">max</span>(nndm_clu)</span>
<span id="cb9-16"><span class="co" style="color: #5E5E5E;
background-color: null;
font-style: inherit;"># distribution-free 95 per cent interval for a median from order statistics</span></span>
<span id="cb9-17">med_ci <span class="ot" style="color: #003B4F;
background-color: null;
font-style: inherit;">&lt;-</span> <span class="cf" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">function</span>(v) {</span>
<span id="cb9-18">  v <span class="ot" style="color: #003B4F;
background-color: null;
font-style: inherit;">&lt;-</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">sort</span>(v)</span>
<span id="cb9-19">  k <span class="ot" style="color: #003B4F;
background-color: null;
font-style: inherit;">&lt;-</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">qbinom</span>(<span class="fl" style="color: #AD0000;
background-color: null;
font-style: inherit;">0.025</span>, <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">length</span>(v), <span class="fl" style="color: #AD0000;
background-color: null;
font-style: inherit;">0.5</span>)</span>
<span id="cb9-20">  <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">c</span>(v[k], v[<span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">length</span>(v) <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">+</span> <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">1</span> <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">-</span> k])</span>
<span id="cb9-21">}</span>
<span id="cb9-22">ci_txt <span class="ot" style="color: #003B4F;
background-color: null;
font-style: inherit;">&lt;-</span> <span class="cf" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">function</span>(ci) <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">sprintf</span>(<span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"%.2f to %.2f"</span>, ci[<span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">1</span>], ci[<span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">2</span>])</span>
<span id="cb9-23">nndm_ci <span class="ot" style="color: #003B4F;
background-color: null;
font-style: inherit;">&lt;-</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">lapply</span>(<span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">paste</span>(s_vals, <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"clustered"</span>), <span class="cf" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">function</span>(cl) <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">med_ci</span>(<span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">ratio_of</span>(cl, <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"nndm"</span>)))</span>
<span id="cb9-24"><span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">stopifnot</span>(<span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">all</span>(<span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">sapply</span>(nndm_ci, <span class="cf" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">function</span>(ci) ci[<span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">1</span>] <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">&lt;</span> <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">1</span> <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">&amp;&amp;</span> ci[<span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">2</span>] <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">&gt;</span> <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">1</span>)))</span></code></pre></div></div>
</div>
<p>On the random design the random ten-fold ratio has medians of 1.03, 1.06 and 0.99 at the three scales, and NNDM 1.04, 1.02 and 0.98. Both are within a few per cent of the truth; random ten-fold’s small excess at the two shorter scales may come partly from its smaller training set, every fold training on 135 plots rather than 150, though at s = 0.03 NNDM, which on a random sample removes few plots from training, shows a similar excess. Block cross-validation is pessimistic in median at every scale and every side. With the block side equal to the range, which here means side 0.2 at s = 0.06, it reads 1.54 [1.21, 1.95] (median, then minimum and maximum over 40 draws; the mean is 1.56 with a Monte Carlo standard error of 0.03). With side 1/3 the same scale reads 1.80 [1.47, 2.31]. The smaller training set of 120 plots can account for little of it, if the step from 150 to 135 plots under random ten-fold is any guide; the rest is that a held-out block’s plots are predicted from plots further away than a typical cell of the map is from its nearest plot, which the distance figure further down shows on one draw.</p>
<p>On the clustered design the direction flips. Random ten-fold reads 0.58 [0.49, 0.64], 0.54 [0.38, 0.63] and 0.61 [0.45, 0.79] at the three scales: it reports an error little more than half the true one, and in no draw at any scale does it reach the truth. Block side 0.2 reads 1.01 [0.74, 1.36], 0.91 [0.65, 1.41] and 0.80 [0.52, 1.50], and side 1/3 reads 1.03 [0.63, 3.25] at the long range. NNDM reads 1.02 [0.79, 1.32], 0.94 [0.63, 1.42] and 0.87 [0.68, 1.47]. Its medians are within Monte Carlo noise of one at all three ranges: a distribution-free 95 per cent interval for each median, from the order statistics of the draws, runs 0.92 to 1.07, 0.87 to 1.08 and 0.77 to 1.17, each covering one. Single draws run from 0.63 to 1.47 across the three scales. Fifteen clusters carry roughly fifteen pieces of information about the residual field between them, and no validation scheme can manufacture more.</p>
<div class="cell">
<div class="code-copy-outer-scaffold"><div class="sourceCode cell-code" id="cb10" style="background: #f1f3f5;"><pre class="sourceCode r code-with-copy"><code class="sourceCode r"><span id="cb10-1">ratio_tab<span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">$</span>scheme_f <span class="ot" style="color: #003B4F;
background-color: null;
font-style: inherit;">&lt;-</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">factor</span>(scheme_lab[ratio_tab<span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">$</span>scheme], <span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">levels =</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">rev</span>(scheme_lab))</span>
<span id="cb10-2">ratio_tab<span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">$</span>s_f <span class="ot" style="color: #003B4F;
background-color: null;
font-style: inherit;">&lt;-</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">factor</span>(<span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">sprintf</span>(<span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"s = %.2f (range %.2f)"</span>, ratio_tab<span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">$</span>s_ker,</span>
<span id="cb10-3">                                range_05[<span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">as.character</span>(ratio_tab<span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">$</span>s_ker)]))</span>
<span id="cb10-4">ratio_tab<span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">$</span>design_f <span class="ot" style="color: #003B4F;
background-color: null;
font-style: inherit;">&lt;-</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">factor</span>(<span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">ifelse</span>(ratio_tab<span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">$</span>design <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">==</span> <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"random"</span>, <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"simple random sample"</span>,</span>
<span id="cb10-5">                                    <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"15 clusters of 10"</span>),</span>
<span id="cb10-6">                             <span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">levels =</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">c</span>(<span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"simple random sample"</span>, <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"15 clusters of 10"</span>))</span>
<span id="cb10-7"><span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">ggplot</span>(ratio_tab, <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">aes</span>(med, scheme_f, <span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">colour =</span> s_f)) <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">+</span></span>
<span id="cb10-8">  <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">geom_vline</span>(<span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">xintercept =</span> <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">1</span>, <span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">linetype =</span> <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"dashed"</span>, <span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">colour =</span> te_body, <span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">linewidth =</span> <span class="fl" style="color: #AD0000;
background-color: null;
font-style: inherit;">0.6</span>) <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">+</span></span>
<span id="cb10-9">  <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">geom_errorbar</span>(<span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">aes</span>(<span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">xmin =</span> lo, <span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">xmax =</span> hi), <span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">orientation =</span> <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"y"</span>, <span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">width =</span> <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">0</span>,</span>
<span id="cb10-10">                <span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">linewidth =</span> <span class="fl" style="color: #AD0000;
background-color: null;
font-style: inherit;">0.7</span>, <span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">position =</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">position_dodge</span>(<span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">width =</span> <span class="fl" style="color: #AD0000;
background-color: null;
font-style: inherit;">0.6</span>)) <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">+</span></span>
<span id="cb10-11">  <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">geom_point</span>(<span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">size =</span> <span class="fl" style="color: #AD0000;
background-color: null;
font-style: inherit;">2.2</span>, <span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">position =</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">position_dodge</span>(<span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">width =</span> <span class="fl" style="color: #AD0000;
background-color: null;
font-style: inherit;">0.6</span>)) <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">+</span></span>
<span id="cb10-12">  <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">facet_wrap</span>(<span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">~</span> design_f) <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">+</span></span>
<span id="cb10-13">  <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">scale_x_log10</span>(<span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">breaks =</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">c</span>(<span class="fl" style="color: #AD0000;
background-color: null;
font-style: inherit;">0.4</span>, <span class="fl" style="color: #AD0000;
background-color: null;
font-style: inherit;">0.6</span>, <span class="fl" style="color: #AD0000;
background-color: null;
font-style: inherit;">0.8</span>, <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">1</span>, <span class="fl" style="color: #AD0000;
background-color: null;
font-style: inherit;">1.25</span>, <span class="fl" style="color: #AD0000;
background-color: null;
font-style: inherit;">1.6</span>, <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">2</span>, <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">3</span>)) <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">+</span></span>
<span id="cb10-14">  <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">scale_colour_manual</span>(<span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">values =</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">c</span>(te_gold, te_forest, te_rust), <span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">name =</span> <span class="cn" style="color: #8f5902;
background-color: null;
font-style: inherit;">NULL</span>) <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">+</span></span>
<span id="cb10-15">  <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">labs</span>(<span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">x =</span> <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"cross-validated RMSE / true map RMSE (log scale)"</span>, <span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">y =</span> <span class="cn" style="color: #8f5902;
background-color: null;
font-style: inherit;">NULL</span>,</span>
<span id="cb10-16">       <span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">title =</span> <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"Block folds overstate a random sample's map error"</span>,</span>
<span id="cb10-17">       <span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">subtitle =</span> <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"and random folds understate a clustered sample's"</span>) <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">+</span></span>
<span id="cb10-18">  <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">theme_datasheet</span>() <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">+</span></span>
<span id="cb10-19">  <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">theme</span>(<span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">legend.position =</span> <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"bottom"</span>)</span></code></pre></div></div>
<div class="cell-output-display">
<div id="fig-ratios" class="quarto-float quarto-figure quarto-figure-center anchored" alt="Two panels of horizontal point-and-bar markers on a logarithmic axis from 0.4 to 3, with a dashed vertical line at 1. The rows are random 10-fold, block with sides 0.1, 0.2 and 1/3, and NNDM leave-one-out; each row has three markers in gold, green and red for residual scales 0.03, 0.06 and 0.12. In the simple random sample panel, random 10-fold and NNDM sit on the dashed line while every block row sits to its right, the side 1/3 row furthest, between about 1.3 and 1.8. In the clustered panel, random 10-fold sits far to the left, near 0.55 to 0.6, with bars that never reach the line; the block rows move from left of the line towards it as the side grows, the red side 1/3 bar stretching past 3; the NNDM medians sit between about 0.85 and 1.0 with bars from about 0.65 to 1.45.">
<figure class="quarto-float quarto-float-fig figure">
<div aria-describedby="fig-ratios-caption-0ceaefa1-69ba-4598-a22c-09a6ac19f8ca">
<img src="https://tidyecology.com/posts/which-spatial-cv-for-a-map/index_files/figure-html/fig-ratios-1.png" class="img-fluid figure-img" alt="Two panels of horizontal point-and-bar markers on a logarithmic axis from 0.4 to 3, with a dashed vertical line at 1. The rows are random 10-fold, block with sides 0.1, 0.2 and 1/3, and NNDM leave-one-out; each row has three markers in gold, green and red for residual scales 0.03, 0.06 and 0.12. In the simple random sample panel, random 10-fold and NNDM sit on the dashed line while every block row sits to its right, the side 1/3 row furthest, between about 1.3 and 1.8. In the clustered panel, random 10-fold sits far to the left, near 0.55 to 0.6, with bars that never reach the line; the block rows move from left of the line towards it as the side grows, the red side 1/3 bar stretching past 3; the NNDM medians sit between about 0.85 and 1.0 with bars from about 0.65 to 1.45." width="864">
</div>
<figcaption class="quarto-float-caption-bottom quarto-float-caption quarto-float-fig" id="fig-ratios-caption-0ceaefa1-69ba-4598-a22c-09a6ac19f8ca">
Figure&nbsp;2: Cross-validated RMSE divided by the true map RMSE, by scheme, design and residual scale. Points are medians over draws, bars run from the smallest to the largest draw.
</figcaption>
</figure>
</div>
</div>
</div>
</section>
<section id="block-side-against-the-range" class="level2">
<h2 id="block-side-against-the-range-h" class="anchored" data-anchor-id="block-side-against-the-range">Block side against the range</h2>
<p>The rule for block size that most readers carry is the one in the spatial cross-validation post: set the block side near the autocorrelation range. On a random sample with a map as the target, that advice fixes the size of the overshoot rather than removing it, and the size depends on more than the ratio of side to range.</p>
<div class="cell">
<div class="code-copy-outer-scaffold"><div class="sourceCode cell-code" id="cb11" style="background: #f1f3f5;"><pre class="sourceCode r code-with-copy"><code class="sourceCode r"><span id="cb11-1">sweep_tab <span class="ot" style="color: #003B4F;
background-color: null;
font-style: inherit;">&lt;-</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">do.call</span>(rbind, <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">lapply</span>(s_vals, <span class="cf" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">function</span>(s_ker) {</span>
<span id="cb11-2">  cl <span class="ot" style="color: #003B4F;
background-color: null;
font-style: inherit;">&lt;-</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">paste</span>(s_ker, <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"random"</span>)</span>
<span id="cb11-3">  ks <span class="ot" style="color: #003B4F;
background-color: null;
font-style: inherit;">&lt;-</span> <span class="cf" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">if</span> (s_ker <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">==</span> s_head) k_sweep <span class="cf" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">else</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">c</span>(<span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">10</span>, <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">5</span>, <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">3</span>)</span>
<span id="cb11-4">  <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">do.call</span>(rbind, <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">lapply</span>(ks, <span class="cf" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">function</span>(k) {</span>
<span id="cb11-5">    v <span class="ot" style="color: #003B4F;
background-color: null;
font-style: inherit;">&lt;-</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">ratio_of</span>(cl, <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">paste0</span>(<span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"blk"</span>, k))</span>
<span id="cb11-6">    <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">data.frame</span>(<span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">s_ker =</span> s_ker, <span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">side =</span> <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">1</span> <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">/</span> k, <span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">rel =</span> (<span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">1</span> <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">/</span> k) <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">/</span> range_05[<span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">as.character</span>(s_ker)],</span>
<span id="cb11-7">               <span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">med =</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">median</span>(v), <span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">lo =</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">min</span>(v), <span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">hi =</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">max</span>(v))</span>
<span id="cb11-8">  }))</span>
<span id="cb11-9">}))</span>
<span id="cb11-10">at_range <span class="ot" style="color: #003B4F;
background-color: null;
font-style: inherit;">&lt;-</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">ratio_of</span>(<span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"0.03 random"</span>, <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"blk10"</span>)</span>
<span id="cb11-11">rel_short <span class="ot" style="color: #003B4F;
background-color: null;
font-style: inherit;">&lt;-</span> (<span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">1</span> <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">/</span> <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">10</span>) <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">/</span> range_05[<span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"0.03"</span>]</span>
<span id="cb11-12">half_06 <span class="ot" style="color: #003B4F;
background-color: null;
font-style: inherit;">&lt;-</span> sweep_tab[sweep_tab<span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">$</span>s_ker <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">==</span> <span class="fl" style="color: #AD0000;
background-color: null;
font-style: inherit;">0.06</span> <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">&amp;</span> sweep_tab<span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">$</span>side <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">==</span> <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">1</span> <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">/</span> <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">10</span>, ]</span>
<span id="cb11-13">half_12 <span class="ot" style="color: #003B4F;
background-color: null;
font-style: inherit;">&lt;-</span> sweep_tab[sweep_tab<span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">$</span>s_ker <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">==</span> <span class="fl" style="color: #AD0000;
background-color: null;
font-style: inherit;">0.12</span> <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">&amp;</span> sweep_tab<span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">$</span>side <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">==</span> <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">1</span> <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">/</span> <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">5</span>, ]</span>
<span id="cb11-14">true_gain_frac <span class="ot" style="color: #003B4F;
background-color: null;
font-style: inherit;">&lt;-</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">sapply</span>(s_vals, <span class="cf" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">function</span>(s_ker) {</span>
<span id="cb11-15">  m <span class="ot" style="color: #003B4F;
background-color: null;
font-style: inherit;">&lt;-</span> cells[[<span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">paste</span>(s_ker, <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"random"</span>)]]</span>
<span id="cb11-16">  <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">median</span>(<span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">1</span> <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">-</span> m[, <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"rk_truth"</span>] <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">/</span> m[, <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"lm_truth"</span>])</span>
<span id="cb11-17">})</span>
<span id="cb11-18">lm_blk5 <span class="ot" style="color: #003B4F;
background-color: null;
font-style: inherit;">&lt;-</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">sapply</span>(s_vals, <span class="cf" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">function</span>(s_ker) <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">median</span>(<span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">ratio_of</span>(<span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">paste</span>(s_ker, <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"random"</span>), <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"blk5"</span>, <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"lm"</span>)))</span></code></pre></div></div>
</div>
<p>At s = 0.06 the overshoot climbs steadily with the block side, from 1.24 at side 1/12 to 1.80 at side 1/3 (medians). At a side of about half the range the two longer scales agree: side 0.1 at s = 0.06 reads 1.28 and side 0.2 at s = 0.12 reads 1.26. At a side equal to the range they do not. Side 0.1 at s = 0.03, which is 0.96 ranges, reads only 1.16 [0.98, 1.51], against 1.54 for the matching side at s = 0.06.</p>
<p>The difference is how much the spatial term is worth in the first place. On the true map, kriging the residuals removes a median 21 per cent of the least squares error at s = 0.03, 45 per cent at s = 0.06 and 53 per cent at s = 0.12. Most of the overshoot sits in the kriging step: least squares alone, scored the same way with block side 0.2, reads 1.03, 1.06 and 1.09 of its own true map error at the three scales. So where the residual field is fine-grained compared with the spacing of 150 plots, kriging adds little and blocking has little to take away. Any overshoot figure is a property of the side, the range and (untested here) the sampling density together, and the next section reads it in the unit that matters to the analyst.</p>
<div class="cell">
<div class="code-copy-outer-scaffold"><div class="sourceCode cell-code" id="cb12" style="background: #f1f3f5;"><pre class="sourceCode r code-with-copy"><code class="sourceCode r"><span id="cb12-1">sweep_tab<span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">$</span>s_f <span class="ot" style="color: #003B4F;
background-color: null;
font-style: inherit;">&lt;-</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">factor</span>(<span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">sprintf</span>(<span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"s = %.2f"</span>, sweep_tab<span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">$</span>s_ker))</span>
<span id="cb12-2"><span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">ggplot</span>(sweep_tab, <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">aes</span>(rel, med, <span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">colour =</span> s_f)) <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">+</span></span>
<span id="cb12-3">  <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">geom_hline</span>(<span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">yintercept =</span> <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">1</span>, <span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">linetype =</span> <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"dashed"</span>, <span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">colour =</span> te_body, <span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">linewidth =</span> <span class="fl" style="color: #AD0000;
background-color: null;
font-style: inherit;">0.6</span>) <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">+</span></span>
<span id="cb12-4">  <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">geom_vline</span>(<span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">xintercept =</span> <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">1</span>, <span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">linetype =</span> <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"dotted"</span>, <span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">colour =</span> te_body, <span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">linewidth =</span> <span class="fl" style="color: #AD0000;
background-color: null;
font-style: inherit;">0.6</span>) <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">+</span></span>
<span id="cb12-5">  <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">geom_errorbar</span>(<span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">aes</span>(<span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">ymin =</span> lo, <span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">ymax =</span> hi), <span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">width =</span> <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">0</span>, <span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">linewidth =</span> <span class="fl" style="color: #AD0000;
background-color: null;
font-style: inherit;">0.6</span>, <span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">alpha =</span> <span class="fl" style="color: #AD0000;
background-color: null;
font-style: inherit;">0.7</span>) <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">+</span></span>
<span id="cb12-6">  <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">geom_line</span>(<span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">linewidth =</span> <span class="fl" style="color: #AD0000;
background-color: null;
font-style: inherit;">0.8</span>) <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">+</span></span>
<span id="cb12-7">  <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">geom_point</span>(<span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">size =</span> <span class="fl" style="color: #AD0000;
background-color: null;
font-style: inherit;">2.3</span>) <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">+</span></span>
<span id="cb12-8">  <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">scale_x_log10</span>(<span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">breaks =</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">c</span>(<span class="fl" style="color: #AD0000;
background-color: null;
font-style: inherit;">0.25</span>, <span class="fl" style="color: #AD0000;
background-color: null;
font-style: inherit;">0.5</span>, <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">1</span>, <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">2</span>, <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">3</span>)) <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">+</span></span>
<span id="cb12-9">  <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">scale_colour_manual</span>(<span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">values =</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">c</span>(te_gold, te_forest, te_rust), <span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">name =</span> <span class="cn" style="color: #8f5902;
background-color: null;
font-style: inherit;">NULL</span>) <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">+</span></span>
<span id="cb12-10">  <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">labs</span>(<span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">x =</span> <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"block side / residual range (log scale)"</span>,</span>
<span id="cb12-11">       <span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">y =</span> <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"block CV RMSE / true map RMSE"</span>,</span>
<span id="cb12-12">       <span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">title =</span> <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"The overshoot grows with the block side"</span>,</span>
<span id="cb12-13">       <span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">subtitle =</span> <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"random design; dotted line: side equal to the range"</span>) <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">+</span></span>
<span id="cb12-14">  <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">theme_datasheet</span>() <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">+</span></span>
<span id="cb12-15">  <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">theme</span>(<span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">legend.position =</span> <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"bottom"</span>)</span></code></pre></div></div>
<div class="cell-output-display">
<div id="fig-sweep" class="quarto-float quarto-figure quarto-figure-center anchored" alt="A line chart with block side divided by the residual range on a logarithmic horizontal axis from about 0.25 to 3, and block cross-validated error divided by the true map error on the vertical axis from about 1 to 2.4. A dashed horizontal line marks 1 and a dotted vertical line marks a side equal to the range. A green line for s 0.06 with seven points rises from about 1.24 at 0.4 ranges to about 1.54 at one range and 1.8 at 1.6 ranges. A red line for s 0.12 with three points rises from about 1.13 to 1.26, where it meets the green line at half a range, and then to 1.71 at 0.8 ranges. A gold line for s 0.03 lies lower, rising only from about 1.16 at one range to about 1.31 at three ranges. Every point carries a long vertical bar for the spread over draws.">
<figure class="quarto-float quarto-float-fig figure">
<div aria-describedby="fig-sweep-caption-0ceaefa1-69ba-4598-a22c-09a6ac19f8ca">
<img src="https://tidyecology.com/posts/which-spatial-cv-for-a-map/index_files/figure-html/fig-sweep-1.png" class="img-fluid figure-img" alt="A line chart with block side divided by the residual range on a logarithmic horizontal axis from about 0.25 to 3, and block cross-validated error divided by the true map error on the vertical axis from about 1 to 2.4. A dashed horizontal line marks 1 and a dotted vertical line marks a side equal to the range. A green line for s 0.06 with seven points rises from about 1.24 at 0.4 ranges to about 1.54 at one range and 1.8 at 1.6 ranges. A red line for s 0.12 with three points rises from about 1.13 to 1.26, where it meets the green line at half a range, and then to 1.71 at 0.8 ranges. A gold line for s 0.03 lies lower, rising only from about 1.16 at one range to about 1.31 at three ranges. Every point carries a long vertical bar for the spread over draws." width="720">
</div>
<figcaption class="quarto-float-caption-bottom quarto-float-caption quarto-float-fig" id="fig-sweep-caption-0ceaefa1-69ba-4598-a22c-09a6ac19f8ca">
Figure&nbsp;3: Block five-fold RMSE divided by the true map RMSE on the random design, against block side measured in residual ranges. Points are medians, bars the smallest to largest draw.
</figcaption>
</figure>
</div>
</div>
</div>
</section>
<section id="the-spatial-term-a-block-scheme-erases" class="level2">
<h2 id="the-spatial-term-a-block-scheme-erases-h" class="anchored" data-anchor-id="the-spatial-term-a-block-scheme-erases">The spatial term a block scheme erases</h2>
<p>A validation number is rarely reported alone. It is usually one of two numbers, the error with the spatial term and the error without it, and the difference is the evidence that the kriging step earns its place. The quantity that matters to the analyst is therefore the reported gain, the least squares error minus the regression-kriging error under a scheme, divided by the true gain on the map.</p>
<div class="cell">
<div class="code-copy-outer-scaffold"><div class="sourceCode cell-code" id="cb13" style="background: #f1f3f5;"><pre class="sourceCode r code-with-copy"><code class="sourceCode r"><span id="cb13-1">gain_tab <span class="ot" style="color: #003B4F;
background-color: null;
font-style: inherit;">&lt;-</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">do.call</span>(rbind, <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">lapply</span>(<span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">names</span>(cells), <span class="cf" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">function</span>(cl) {</span>
<span id="cb13-2">  parts <span class="ot" style="color: #003B4F;
background-color: null;
font-style: inherit;">&lt;-</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">strsplit</span>(cl, <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">" "</span>)[[<span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">1</span>]]</span>
<span id="cb13-3">  <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">do.call</span>(rbind, <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">lapply</span>(<span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">c</span>(<span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"rand10"</span>, <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"blk5"</span>, <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"blk3"</span>, <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"nndm"</span>), <span class="cf" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">function</span>(sc) {</span>
<span id="cb13-4">    v <span class="ot" style="color: #003B4F;
background-color: null;
font-style: inherit;">&lt;-</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">gain_of</span>(cl, sc)</span>
<span id="cb13-5">    <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">data.frame</span>(<span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">s_ker =</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">as.numeric</span>(parts[<span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">1</span>]), <span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">design =</span> parts[<span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">2</span>], <span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">scheme =</span> sc,</span>
<span id="cb13-6">               <span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">med =</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">median</span>(v), <span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">q1 =</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">unname</span>(<span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">quantile</span>(v, <span class="fl" style="color: #AD0000;
background-color: null;
font-style: inherit;">0.25</span>)),</span>
<span id="cb13-7">               <span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">q3 =</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">unname</span>(<span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">quantile</span>(v, <span class="fl" style="color: #AD0000;
background-color: null;
font-style: inherit;">0.75</span>)))</span>
<span id="cb13-8">  }))</span>
<span id="cb13-9">}))</span>
<span id="cb13-10">n_neg_b3 <span class="ot" style="color: #003B4F;
background-color: null;
font-style: inherit;">&lt;-</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">n_neg</span>(<span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"0.06 clustered"</span>, <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"blk3"</span>)</span>
<span id="cb13-11">nndm_gain_med <span class="ot" style="color: #003B4F;
background-color: null;
font-style: inherit;">&lt;-</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">sapply</span>(<span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">paste</span>(s_vals, <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"clustered"</span>), <span class="cf" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">function</span>(cl) <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">median</span>(<span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">gain_of</span>(cl, <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"nndm"</span>)))</span></code></pre></div></div>
</div>
<p>On the random design, block side 0.2 reports 0.21 [-0.01, 0.67] of the true gain at s = 0.03 and 0.41 [0.18, 1.01] at s = 0.06; at s = 0.03 it reports a negative gain in 1 of 20 draws, so on that draw the reviewer’s scheme would have told her to drop a spatial term that was doing real work. Side 1/3 does worse, 0.14 and 0.27 in median. Random ten-fold reports medians of 0.85, 0.97 and 0.98 of the true gain at the three scales, and NNDM 0.85, 1.00 and 0.98.</p>
<p>On the clustered design random ten-fold inflates the gain, to a median 4.34 times the true value at s = 0.03, 2.30 at s = 0.06 and 1.22 at s = 0.12. The plots inside a cluster predict each other through the kriging term, so the term looks far more valuable than it is for the cells between clusters. NNDM reads 1.13 [0.44, 2.70], 1.04 [-0.04, 2.22] and 0.84 [0.44, 5.55]: medians between 0.84 and 1.13, wide in any single draw.</p>
<p>None of this is a ranking reversal in the usual sense. Every scheme prefers the kriging model in nearly every draw; the one place a scheme often picks the wrong model is block side 1/3 on the clustered sample at s = 0.06, which reports a negative gain in 8 of 40 draws. The common failure is quieter: a correct model choice carried by a gain that is often misstated by a factor of two or more, in a direction set by the sampling design.</p>
<div class="cell">
<div class="code-copy-outer-scaffold"><div class="sourceCode cell-code" id="cb14" style="background: #f1f3f5;"><pre class="sourceCode r code-with-copy"><code class="sourceCode r"><span id="cb14-1">gain_tab<span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">$</span>scheme_f <span class="ot" style="color: #003B4F;
background-color: null;
font-style: inherit;">&lt;-</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">factor</span>(scheme_lab[gain_tab<span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">$</span>scheme], <span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">levels =</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">rev</span>(scheme_lab))</span>
<span id="cb14-2">gain_tab<span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">$</span>s_f <span class="ot" style="color: #003B4F;
background-color: null;
font-style: inherit;">&lt;-</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">factor</span>(<span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">sprintf</span>(<span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"s = %.2f"</span>, gain_tab<span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">$</span>s_ker))</span>
<span id="cb14-3">gain_tab<span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">$</span>design_f <span class="ot" style="color: #003B4F;
background-color: null;
font-style: inherit;">&lt;-</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">factor</span>(<span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">ifelse</span>(gain_tab<span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">$</span>design <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">==</span> <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"random"</span>, <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"simple random sample"</span>,</span>
<span id="cb14-4">                                   <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"15 clusters of 10"</span>),</span>
<span id="cb14-5">                            <span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">levels =</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">c</span>(<span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"simple random sample"</span>, <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"15 clusters of 10"</span>))</span>
<span id="cb14-6"><span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">ggplot</span>(gain_tab, <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">aes</span>(med, scheme_f, <span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">colour =</span> s_f)) <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">+</span></span>
<span id="cb14-7">  <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">geom_vline</span>(<span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">xintercept =</span> <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">1</span>, <span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">linetype =</span> <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"dashed"</span>, <span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">colour =</span> te_body, <span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">linewidth =</span> <span class="fl" style="color: #AD0000;
background-color: null;
font-style: inherit;">0.6</span>) <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">+</span></span>
<span id="cb14-8">  <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">geom_vline</span>(<span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">xintercept =</span> <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">0</span>, <span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">colour =</span> te_line, <span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">linewidth =</span> <span class="fl" style="color: #AD0000;
background-color: null;
font-style: inherit;">0.8</span>) <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">+</span></span>
<span id="cb14-9">  <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">geom_errorbar</span>(<span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">aes</span>(<span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">xmin =</span> q1, <span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">xmax =</span> q3), <span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">orientation =</span> <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"y"</span>, <span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">width =</span> <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">0</span>,</span>
<span id="cb14-10">                <span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">linewidth =</span> <span class="fl" style="color: #AD0000;
background-color: null;
font-style: inherit;">0.7</span>, <span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">position =</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">position_dodge</span>(<span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">width =</span> <span class="fl" style="color: #AD0000;
background-color: null;
font-style: inherit;">0.6</span>)) <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">+</span></span>
<span id="cb14-11">  <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">geom_point</span>(<span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">size =</span> <span class="fl" style="color: #AD0000;
background-color: null;
font-style: inherit;">2.2</span>, <span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">position =</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">position_dodge</span>(<span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">width =</span> <span class="fl" style="color: #AD0000;
background-color: null;
font-style: inherit;">0.6</span>)) <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">+</span></span>
<span id="cb14-12">  <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">facet_wrap</span>(<span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">~</span> design_f) <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">+</span></span>
<span id="cb14-13">  <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">scale_colour_manual</span>(<span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">values =</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">c</span>(te_gold, te_forest, te_rust), <span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">name =</span> <span class="cn" style="color: #8f5902;
background-color: null;
font-style: inherit;">NULL</span>) <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">+</span></span>
<span id="cb14-14">  <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">labs</span>(<span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">x =</span> <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"reported gain / true gain"</span>, <span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">y =</span> <span class="cn" style="color: #8f5902;
background-color: null;
font-style: inherit;">NULL</span>,</span>
<span id="cb14-15">       <span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">title =</span> <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"The kriging gain, misstated in both directions"</span>,</span>
<span id="cb14-16">       <span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">subtitle =</span> <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"dashed line: the gain the map really has"</span>) <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">+</span></span>
<span id="cb14-17">  <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">theme_datasheet</span>() <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">+</span></span>
<span id="cb14-18">  <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">theme</span>(<span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">legend.position =</span> <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"bottom"</span>)</span></code></pre></div></div>
<div class="cell-output-display">
<div id="fig-gain" class="quarto-float quarto-figure quarto-figure-center anchored" alt="Two panels of horizontal point-and-bar markers for reported kriging gain divided by true gain, on a linear axis from 0 to 5 with a dashed line at 1. The rows are random 10-fold, block side 0.2, block side 1/3 and NNDM leave-one-out, with gold, green and red markers for the three residual scales. In the simple random sample panel random 10-fold and NNDM sit near 1, while both block rows sit well to the left, between about 0.15 and 0.85, lowest at the smallest scale. In the clustered panel random 10-fold sits far to the right, at about 4.3 for the smallest scale, 2.3 for the middle one and 1.2 for the largest, while the block and NNDM rows sit between about 0.5 and 1.3.">
<figure class="quarto-float quarto-float-fig figure">
<div aria-describedby="fig-gain-caption-0ceaefa1-69ba-4598-a22c-09a6ac19f8ca">
<img src="https://tidyecology.com/posts/which-spatial-cv-for-a-map/index_files/figure-html/fig-gain-1.png" class="img-fluid figure-img" alt="Two panels of horizontal point-and-bar markers for reported kriging gain divided by true gain, on a linear axis from 0 to 5 with a dashed line at 1. The rows are random 10-fold, block side 0.2, block side 1/3 and NNDM leave-one-out, with gold, green and red markers for the three residual scales. In the simple random sample panel random 10-fold and NNDM sit near 1, while both block rows sit well to the left, between about 0.15 and 0.85, lowest at the smallest scale. In the clustered panel random 10-fold sits far to the right, at about 4.3 for the smallest scale, 2.3 for the middle one and 1.2 for the largest, while the block and NNDM rows sit between about 0.5 and 1.3." width="864">
</div>
<figcaption class="quarto-float-caption-bottom quarto-float-caption quarto-float-fig" id="fig-gain-caption-0ceaefa1-69ba-4598-a22c-09a6ac19f8ca">
Figure&nbsp;4: Reported kriging gain divided by the true gain on the map, by scheme and design. Points are medians over draws, bars the interquartile range.
</figcaption>
</figure>
</div>
</div>
</div>
</section>
<section id="the-check-to-run-before-any-fold-is-drawn" class="level2">
<h2 id="the-check-to-run-before-any-fold-is-drawn-h" class="anchored" data-anchor-id="the-check-to-run-before-any-fold-is-drawn">The check to run before any fold is drawn</h2>
<p>Everything above follows from one comparison, and that comparison needs only the coordinates. A scheme scores each held-out plot at the distance to training data the scheme leaves it; the map’s error is set by the distances from the prediction cells to the sample. Plotting the two empirical distribution functions on one panel shows which scheme matches the map before any model is fitted.</p>
<div class="cell">
<div class="code-copy-outer-scaffold"><div class="sourceCode cell-code" id="cb15" style="background: #f1f3f5;"><pre class="sourceCode r code-with-copy"><code class="sourceCode r"><span id="cb15-1"><span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">set.seed</span>(<span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">606</span>)</span>
<span id="cb15-2">ecdf_list <span class="ot" style="color: #003B4F;
background-color: null;
font-style: inherit;">&lt;-</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">lapply</span>(<span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">c</span>(<span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"random"</span>, <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"clustered"</span>), <span class="cf" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">function</span>(des) {</span>
<span id="cb15-3">  idx  <span class="ot" style="color: #003B4F;
background-color: null;
font-style: inherit;">&lt;-</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">draw_sample</span>(des)</span>
<span id="cb15-4">  xy   <span class="ot" style="color: #003B4F;
background-color: null;
font-style: inherit;">&lt;-</span> xy_all[idx, ]</span>
<span id="cb15-5">  pc   <span class="ot" style="color: #003B4F;
background-color: null;
font-style: inherit;">&lt;-</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">setdiff</span>(<span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">seq_len</span>(n_cell), idx)</span>
<span id="cb15-6">  dmat <span class="ot" style="color: #003B4F;
background-color: null;
font-style: inherit;">&lt;-</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">as.matrix</span>(<span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">dist</span>(xy))</span>
<span id="cb15-7">  gpred <span class="ot" style="color: #003B4F;
background-color: null;
font-style: inherit;">&lt;-</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">apply</span>(<span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">cross_dist</span>(xy_all[pc, ], xy), <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">1</span>, min)</span>
<span id="cb15-8">  fl <span class="ot" style="color: #003B4F;
background-color: null;
font-style: inherit;">&lt;-</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">list</span>(<span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">rand10 =</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">random_folds</span>(n_samp), <span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">blk5 =</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">block_folds</span>(xy, <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">5</span>),</span>
<span id="cb15-9">             <span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">nndm =</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">nndm_folds</span>(dmat, gpred))</span>
<span id="cb15-10">  lab <span class="ot" style="color: #003B4F;
background-color: null;
font-style: inherit;">&lt;-</span> <span class="cf" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">if</span> (des <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">==</span> <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"random"</span>) <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"simple random sample"</span> <span class="cf" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">else</span> <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"15 clusters of 10"</span></span>
<span id="cb15-11">  rows <span class="ot" style="color: #003B4F;
background-color: null;
font-style: inherit;">&lt;-</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">rbind</span>(<span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">data.frame</span>(<span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">design =</span> lab, <span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">curve =</span> <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"prediction cells to sample"</span>, <span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">d =</span> gpred),</span>
<span id="cb15-12">                <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">do.call</span>(rbind, <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">lapply</span>(<span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">names</span>(fl), <span class="cf" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">function</span>(nm)</span>
<span id="cb15-13">                  <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">data.frame</span>(<span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">design =</span> lab, <span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">curve =</span> scheme_lab[[nm]], <span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">d =</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">test_nn</span>(fl[[nm]], dmat)))))</span>
<span id="cb15-14">  <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">list</span>(<span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">rows =</span> rows, <span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">w =</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">sapply</span>(fl, <span class="cf" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">function</span>(f) <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">w_stat</span>(<span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">test_nn</span>(f, dmat), gpred)),</span>
<span id="cb15-15">       <span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">med_pred =</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">median</span>(gpred), <span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">med_r10 =</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">median</span>(<span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">test_nn</span>(fl<span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">$</span>rand10, dmat)),</span>
<span id="cb15-16">       <span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">med_b5 =</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">median</span>(<span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">test_nn</span>(fl<span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">$</span>blk5, dmat)))</span>
<span id="cb15-17">})</span>
<span id="cb15-18">ecdf_rows <span class="ot" style="color: #003B4F;
background-color: null;
font-style: inherit;">&lt;-</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">do.call</span>(rbind, <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">lapply</span>(ecdf_list, <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">`</span><span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">[[</span><span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">`</span>, <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"rows"</span>))</span>
<span id="cb15-19">w_ran <span class="ot" style="color: #003B4F;
background-color: null;
font-style: inherit;">&lt;-</span> ecdf_list[[<span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">1</span>]]<span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">$</span>w</span>
<span id="cb15-20">w_clu <span class="ot" style="color: #003B4F;
background-color: null;
font-style: inherit;">&lt;-</span> ecdf_list[[<span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">2</span>]]<span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">$</span>w</span></code></pre></div></div>
</div>
<p>On the random draw shown, the median distance from a cell to its nearest plot is 0.035; random ten-fold leaves each held-out plot a median 0.044 from its nearest training plot, and block side 0.2 leaves 0.091. On the clustered draw the cells sit a median 0.078 from the nearest plot, while random ten-fold leaves a held-out plot only 0.022 from a training plot in its own cluster. The areas between the curves say the same in one number each: 0.0030 for random ten-fold and 0.0510 for block side 0.2 on the random draw, 0.0674 and 0.0217 on the clustered one. NNDM, which builds the match, gets 0.0010 and 0.0016.</p>
<div class="cell">
<div class="code-copy-outer-scaffold"><div class="sourceCode cell-code" id="cb16" style="background: #f1f3f5;"><pre class="sourceCode r code-with-copy"><code class="sourceCode r"><span id="cb16-1">curve_lev <span class="ot" style="color: #003B4F;
background-color: null;
font-style: inherit;">&lt;-</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">c</span>(<span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"prediction cells to sample"</span>, scheme_lab[<span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">c</span>(<span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"rand10"</span>, <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"blk5"</span>, <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"nndm"</span>)])</span>
<span id="cb16-2">ecdf_rows<span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">$</span>curve <span class="ot" style="color: #003B4F;
background-color: null;
font-style: inherit;">&lt;-</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">factor</span>(ecdf_rows<span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">$</span>curve, <span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">levels =</span> curve_lev)</span>
<span id="cb16-3">ecdf_rows<span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">$</span>design <span class="ot" style="color: #003B4F;
background-color: null;
font-style: inherit;">&lt;-</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">factor</span>(ecdf_rows<span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">$</span>design, <span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">levels =</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">c</span>(<span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"simple random sample"</span>, <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"15 clusters of 10"</span>))</span>
<span id="cb16-4"><span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">ggplot</span>(ecdf_rows, <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">aes</span>(d, <span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">colour =</span> curve, <span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">linetype =</span> curve)) <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">+</span></span>
<span id="cb16-5">  <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">stat_ecdf</span>(<span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">linewidth =</span> <span class="fl" style="color: #AD0000;
background-color: null;
font-style: inherit;">0.9</span>, <span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">pad =</span> <span class="cn" style="color: #8f5902;
background-color: null;
font-style: inherit;">FALSE</span>) <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">+</span></span>
<span id="cb16-6">  <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">facet_wrap</span>(<span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">~</span> design, <span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">scales =</span> <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"free_x"</span>) <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">+</span></span>
<span id="cb16-7">  <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">scale_colour_manual</span>(<span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">values =</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">c</span>(te_ink, te_gold, te_forest, te_rust), <span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">name =</span> <span class="cn" style="color: #8f5902;
background-color: null;
font-style: inherit;">NULL</span>) <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">+</span></span>
<span id="cb16-8">  <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">scale_linetype_manual</span>(<span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">values =</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">c</span>(<span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"solid"</span>, <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"solid"</span>, <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"solid"</span>, <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"22"</span>), <span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">name =</span> <span class="cn" style="color: #8f5902;
background-color: null;
font-style: inherit;">NULL</span>) <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">+</span></span>
<span id="cb16-9">  <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">labs</span>(<span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">x =</span> <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"distance to the nearest sample or training plot (map side = 1)"</span>,</span>
<span id="cb16-10">       <span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">y =</span> <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"cumulative proportion"</span>,</span>
<span id="cb16-11">       <span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">title =</span> <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"Match the black curve before choosing a scheme"</span>,</span>
<span id="cb16-12">       <span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">subtitle =</span> <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"one draw per design; a scheme whose curve lies on the black one reads the map error"</span>) <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">+</span></span>
<span id="cb16-13">  <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">theme_datasheet</span>() <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">+</span></span>
<span id="cb16-14">  <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">theme</span>(<span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">legend.position =</span> <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"bottom"</span>) <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">+</span></span>
<span id="cb16-15">  <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">guides</span>(<span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">colour =</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">guide_legend</span>(<span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">nrow =</span> <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">2</span>), <span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">linetype =</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">guide_legend</span>(<span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">nrow =</span> <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">2</span>))</span></code></pre></div></div>
<div class="cell-output-display">
<div id="fig-ecdf" class="quarto-float quarto-figure quarto-figure-center anchored" alt="Two panels of step curves of cumulative proportion against distance. In the simple random sample panel, with distances up to about 0.2, a black curve for prediction cells to sample rises steeply and reaches one by about 0.12; a gold random 10-fold curve and a dashed red NNDM curve lie almost on top of it, while a green block side 0.2 curve lies far to the right and reaches one only near 0.2. In the clustered panel, with distances up to about 0.37, the black curve rises gradually; the gold random 10-fold curve shoots up at the far left, starting near one half at the smallest distance and reaching one by about 0.07; the dashed red NNDM curve follows the black one closely all the way, and the green block curve follows it below about 0.15 and then lags to the right until about 0.3.">
<figure class="quarto-float quarto-float-fig figure">
<div aria-describedby="fig-ecdf-caption-0ceaefa1-69ba-4598-a22c-09a6ac19f8ca">
<img src="https://tidyecology.com/posts/which-spatial-cv-for-a-map/index_files/figure-html/fig-ecdf-1.png" class="img-fluid figure-img" alt="Two panels of step curves of cumulative proportion against distance. In the simple random sample panel, with distances up to about 0.2, a black curve for prediction cells to sample rises steeply and reaches one by about 0.12; a gold random 10-fold curve and a dashed red NNDM curve lie almost on top of it, while a green block side 0.2 curve lies far to the right and reaches one only near 0.2. In the clustered panel, with distances up to about 0.37, the black curve rises gradually; the gold random 10-fold curve shoots up at the far left, starting near one half at the smallest distance and reaching one by about 0.07; the dashed red NNDM curve follows the black one closely all the way, and the green block curve follows it below about 0.15 and then lags to the right until about 0.3." width="864">
</div>
<figcaption class="quarto-float-caption-bottom quarto-float-caption quarto-float-fig" id="fig-ecdf-caption-0ceaefa1-69ba-4598-a22c-09a6ac19f8ca">
Figure&nbsp;5: Empirical distribution functions of the distance from each prediction cell to its nearest plot (black) and from each held-out plot to its nearest training plot under three schemes, for one draw of each design.
</figcaption>
</figure>
</div>
</div>
</div>
<p>The figure is one draw. Whether the check picks the right scheme in general can be measured on all the draws above, because every draw stored its distance statistic for every scheme. The rule tested is the one a reader can apply: among the ready-made schemes (random ten-fold and the three block sides), take the one with the smallest area between the curves.</p>
<div class="cell">
<div class="code-copy-outer-scaffold"><div class="sourceCode cell-code" id="cb17" style="background: #f1f3f5;"><pre class="sourceCode r code-with-copy"><code class="sourceCode r"><span id="cb17-1">fixed_sc <span class="ot" style="color: #003B4F;
background-color: null;
font-style: inherit;">&lt;-</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">c</span>(<span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"rand10"</span>, <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"blk10"</span>, <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"blk5"</span>, <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"blk3"</span>)</span>
<span id="cb17-2">pick_by_w <span class="ot" style="color: #003B4F;
background-color: null;
font-style: inherit;">&lt;-</span> <span class="cf" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">function</span>(cl) {</span>
<span id="cb17-3">  m <span class="ot" style="color: #003B4F;
background-color: null;
font-style: inherit;">&lt;-</span> cells[[cl]]</span>
<span id="cb17-4">  w_m <span class="ot" style="color: #003B4F;
background-color: null;
font-style: inherit;">&lt;-</span> m[, <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">paste0</span>(<span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"W_"</span>, fixed_sc), drop <span class="ot" style="color: #003B4F;
background-color: null;
font-style: inherit;">=</span> <span class="cn" style="color: #8f5902;
background-color: null;
font-style: inherit;">FALSE</span>]</span>
<span id="cb17-5">  r_m <span class="ot" style="color: #003B4F;
background-color: null;
font-style: inherit;">&lt;-</span> m[, <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">paste0</span>(<span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"rk_"</span>, fixed_sc), drop <span class="ot" style="color: #003B4F;
background-color: null;
font-style: inherit;">=</span> <span class="cn" style="color: #8f5902;
background-color: null;
font-style: inherit;">FALSE</span>] <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">/</span> m[, <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"rk_truth"</span>]</span>
<span id="cb17-6">  chosen <span class="ot" style="color: #003B4F;
background-color: null;
font-style: inherit;">&lt;-</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">apply</span>(w_m, <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">1</span>, which.min)</span>
<span id="cb17-7">  best   <span class="ot" style="color: #003B4F;
background-color: null;
font-style: inherit;">&lt;-</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">apply</span>(<span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">abs</span>(<span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">log</span>(r_m)), <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">1</span>, which.min)</span>
<span id="cb17-8">  <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">list</span>(<span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">ratio =</span> r_m[<span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">cbind</span>(<span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">seq_len</span>(<span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">nrow</span>(r_m)), chosen)],</span>
<span id="cb17-9">       <span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">agree =</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">mean</span>(chosen <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">==</span> best),</span>
<span id="cb17-10">       <span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">top =</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">names</span>(<span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">which.max</span>(<span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">table</span>(fixed_sc[chosen]))),</span>
<span id="cb17-11">       <span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">top_share =</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">max</span>(<span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">table</span>(chosen)) <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">/</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">length</span>(chosen),</span>
<span id="cb17-12">       <span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">chosen =</span> fixed_sc[chosen], <span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">best =</span> fixed_sc[best])</span>
<span id="cb17-13">}</span>
<span id="cb17-14">pick <span class="ot" style="color: #003B4F;
background-color: null;
font-style: inherit;">&lt;-</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">lapply</span>(<span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">setNames</span>(<span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">names</span>(cells), <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">names</span>(cells)), pick_by_w)</span>
<span id="cb17-15">pick_ran <span class="ot" style="color: #003B4F;
background-color: null;
font-style: inherit;">&lt;-</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">unlist</span>(<span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">lapply</span>(pick[<span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">grep</span>(<span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"random"</span>, <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">names</span>(pick))], <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">`</span><span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">[[</span><span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">`</span>, <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"ratio"</span>))</span>
<span id="cb17-16">pick_clu <span class="ot" style="color: #003B4F;
background-color: null;
font-style: inherit;">&lt;-</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">lapply</span>(pick[<span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">grep</span>(<span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"clustered"</span>, <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">names</span>(pick))], <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">`</span><span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">[[</span><span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">`</span>, <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"ratio"</span>)</span>
<span id="cb17-17">top_clu <span class="ot" style="color: #003B4F;
background-color: null;
font-style: inherit;">&lt;-</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">sapply</span>(pick[<span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">grep</span>(<span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"clustered"</span>, <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">names</span>(pick))], <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">`</span><span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">[[</span><span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">`</span>, <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"top"</span>)</span>
<span id="cb17-18"><span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">stopifnot</span>(<span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">all</span>(top_clu <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">==</span> <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"blk5"</span>))</span>
<span id="cb17-19">top_clu_share <span class="ot" style="color: #003B4F;
background-color: null;
font-style: inherit;">&lt;-</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">sapply</span>(pick[<span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">grep</span>(<span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"clustered"</span>, <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">names</span>(pick))], <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">`</span><span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">[[</span><span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">`</span>, <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"top_share"</span>)</span>
<span id="cb17-20">chosen_clu <span class="ot" style="color: #003B4F;
background-color: null;
font-style: inherit;">&lt;-</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">unlist</span>(<span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">lapply</span>(pick[<span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">grep</span>(<span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"clustered"</span>, <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">names</span>(pick))], <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">`</span><span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">[[</span><span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">`</span>, <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"chosen"</span>))</span>
<span id="cb17-21">n_r10_clu <span class="ot" style="color: #003B4F;
background-color: null;
font-style: inherit;">&lt;-</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">sum</span>(chosen_clu <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">==</span> <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"rand10"</span>)</span>
<span id="cb17-22">n_clu_draws <span class="ot" style="color: #003B4F;
background-color: null;
font-style: inherit;">&lt;-</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">length</span>(chosen_clu)</span>
<span id="cb17-23">agree_clu <span class="ot" style="color: #003B4F;
background-color: null;
font-style: inherit;">&lt;-</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">sapply</span>(pick[<span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">grep</span>(<span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"clustered"</span>, <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">names</span>(pick))], <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">`</span><span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">[[</span><span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">`</span>, <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"agree"</span>)</span>
<span id="cb17-24">n_ran_draws <span class="ot" style="color: #003B4F;
background-color: null;
font-style: inherit;">&lt;-</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">length</span>(pick_ran)</span>
<span id="cb17-25"><span class="co" style="color: #5E5E5E;
background-color: null;
font-style: inherit;"># the widest pick on the clustered design, and the draws where the pick is not the best scheme</span></span>
<span id="cb17-26">exc_i     <span class="ot" style="color: #003B4F;
background-color: null;
font-style: inherit;">&lt;-</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">which.max</span>(pick[[<span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"0.06 clustered"</span>]]<span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">$</span>ratio)</span>
<span id="cb17-27">exc_sc    <span class="ot" style="color: #003B4F;
background-color: null;
font-style: inherit;">&lt;-</span> pick[[<span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"0.06 clustered"</span>]]<span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">$</span>chosen[exc_i]</span>
<span id="cb17-28">exc_ratio <span class="ot" style="color: #003B4F;
background-color: null;
font-style: inherit;">&lt;-</span> pick[[<span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"0.06 clustered"</span>]]<span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">$</span>ratio[exc_i]</span>
<span id="cb17-29">exc_nndm  <span class="ot" style="color: #003B4F;
background-color: null;
font-style: inherit;">&lt;-</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">ratio_of</span>(<span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"0.06 clustered"</span>, <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"nndm"</span>)[exc_i]</span>
<span id="cb17-30"><span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">stopifnot</span>(exc_ratio <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">&gt;</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">max</span>(pick_clu[[<span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">1</span>]], pick_clu[[<span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">3</span>]]), exc_sc <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">==</span> <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"blk3"</span>)</span>
<span id="cb17-31">ch_clu <span class="ot" style="color: #003B4F;
background-color: null;
font-style: inherit;">&lt;-</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">unlist</span>(<span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">lapply</span>(pick[<span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">grep</span>(<span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"clustered"</span>, <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">names</span>(pick))], <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">`</span><span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">[[</span><span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">`</span>, <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"chosen"</span>))</span>
<span id="cb17-32">be_clu <span class="ot" style="color: #003B4F;
background-color: null;
font-style: inherit;">&lt;-</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">unlist</span>(<span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">lapply</span>(pick[<span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">grep</span>(<span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"clustered"</span>, <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">names</span>(pick))], <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">`</span><span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">[[</span><span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">`</span>, <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"best"</span>))</span>
<span id="cb17-33">n_dis    <span class="ot" style="color: #003B4F;
background-color: null;
font-style: inherit;">&lt;-</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">sum</span>(ch_clu <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">!=</span> be_clu)</span>
<span id="cb17-34">n_dis_bb <span class="ot" style="color: #003B4F;
background-color: null;
font-style: inherit;">&lt;-</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">sum</span>(ch_clu <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">!=</span> be_clu <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">&amp;</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">grepl</span>(<span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"blk"</span>, ch_clu) <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">&amp;</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">grepl</span>(<span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"blk"</span>, be_clu))</span>
<span id="cb17-35"><span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">stopifnot</span>(n_dis_bb <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">==</span> n_dis)</span>
<span id="cb17-36">n_r10_ran <span class="ot" style="color: #003B4F;
background-color: null;
font-style: inherit;">&lt;-</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">sum</span>(<span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">unlist</span>(<span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">lapply</span>(pick[<span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">grep</span>(<span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"random"</span>, <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">names</span>(pick))], <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">`</span><span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">[[</span><span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">`</span>, <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"chosen"</span>)) <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">==</span> <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"rand10"</span>)</span></code></pre></div></div>
</div>
<p>On the random design the rule picks random ten-fold in 80 of 80 draws, and the number it picks reads 1.02 [0.82, 1.29] of the truth across them. On the clustered design it picks block side 0.2 most often, in 60 to 78 per cent of draws depending on the scale, and random ten-fold in 0 of 80 clustered draws. The number it picks reads 1.06 [0.75, 1.41], 0.90 [0.65, 2.11] and 0.92 [0.69, 1.50] at the three scales. The systematic understatement of random ten-fold is gone, and what remains is a scatter of the same order as NNDM’s, with one wider excursion at s = 0.06, a draw where the rule chose block side 1/3 and read 2.11 while NNDM read 1.41: with at most nine blocks dealt to five folds, one fold can hold out several clusters at once.</p>
<p>The check does not find the best scheme draw by draw. Among the four ready-made schemes it names the one closest to the truth in only 35 to 60 per cent of clustered draws, and in every one of the 46 draws where it misses, both the scheme it names and the best one are block sides. What it does is refuse the scheme that is wrong in a known direction, on either design, using nothing but the coordinates of the plots and of the cells to be mapped.</p>
</section>
<section id="a-fitted-kernel-instead-of-the-known-one" class="level2">
<h2 id="a-fitted-kernel-instead-of-the-known-one-h" class="anchored" data-anchor-id="a-fitted-kernel-instead-of-the-known-one">A fitted kernel instead of the known one</h2>
<p>The kriging above was given the process covariance. In a real analysis the kernel is estimated, and a fair question is whether the ratios survive the estimation noise. At s = 0.06 every draw also fitted the kernel standard deviation, the sill and the nugget by maximum likelihood over a grid, from the least squares residuals of the whole sample, and then ran the headline schemes with the fitted kernel. The fit is made once, outside the folds, which is how most analyses do it and is itself a small leak.</p>
<div class="cell">
<div class="code-copy-outer-scaffold"><div class="sourceCode cell-code" id="cb18" style="background: #f1f3f5;"><pre class="sourceCode r code-with-copy"><code class="sourceCode r"><span id="cb18-1">s_hat_ran <span class="ot" style="color: #003B4F;
background-color: null;
font-style: inherit;">&lt;-</span> cells[[<span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"0.06 random"</span>]][, <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"s_hat"</span>]</span>
<span id="cb18-2">s_hat_clu <span class="ot" style="color: #003B4F;
background-color: null;
font-style: inherit;">&lt;-</span> cells[[<span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"0.06 clustered"</span>]][, <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"s_hat"</span>]</span></code></pre></div></div>
</div>
<p>The fitted kernel standard deviation has a median of 0.055 on the random design and 0.055 on the clustered one, against the true 0.06, with draws from 0.036 to 0.097. With it, the random design reads 1.04 [0.90, 1.25] for random ten-fold, 1.50 [1.22, 1.94] for block side 0.2 and 1.02 [0.87, 1.23] for NNDM; the clustered design reads 0.52 [0.38, 0.63], 0.90 [0.61, 1.39] and 0.94 [0.56, 1.42]. The median ratios move by a few hundredths at most. Part of the reason is that the truth is recomputed with the same fitted kernel, so a worse kernel moves both numbers together.</p>
</section>
<section id="what-to-report" class="level2">
<h2 id="what-to-report-h" class="anchored" data-anchor-id="what-to-report">What to report</h2>
<p>Say which error the number estimates. For a published map that is the error over the cells of the map, and it is the denominator every choice above was judged against. A number from a scheme that answers a different question (extrapolation to a new region, prediction of a new visit to a known site) belongs in the report only with that question attached.</p>
<p>If the plots are a probability sample, say so and use it. A simple random or stratified sample supports a design-based estimate of map accuracy, from an independent probability validation sample or, when the calibration plots are themselves the probability sample, from ordinary random cross-validation of them; no spatial blocking is needed, which is the recommendation of Wadoux and colleagues. Here, random ten-fold on a simple random sample landed close to the true map error and block cross-validation did not.</p>
<p>If the plots are not a probability sample, draw the two distance distributions before choosing a scheme and publish the figure. It costs a distance matrix, needs no model, and tells the reader why the scheme was chosen. Where no ready-made scheme matches, use NNDM leave-one-out, and report its spread honestly: with the fifteen clusters simulated here a single NNDM number was 0.94 [0.63, 1.42] of the truth across draws, so it is close to the truth in the median, with a wide error in any one survey.</p>
<p>Report the gain from the spatial term under the chosen scheme, not under a default. The size of that gain is what decides whether the kriging step appears in the methods section, and on a random sample a block scheme reported 0.41 of it in median at the medium range.</p>
</section>
<section id="honest-limits" class="level2">
<h2 id="honest-limits-h" class="anchored" data-anchor-id="honest-limits">Honest limits</h2>
<p>The kriging kernel is the process one in every arm except the fitted-kernel check, which was run only at s = 0.06 and fitted the kernel once, outside the folds. The covariance is Gaussian, the model is one linear trend plus simple kriging, and the covariates are smooth and cover the map; none of the numbers is a claim about random forests, generalised additive models or any other learner, only about the mechanism, which works through distances and is expected to carry over, though that is not tested.</p>
<p>The distance check looks only at the nearest neighbour, while kriging uses many neighbours. Whether a richer summary of the distances would name the best scheme more often draw by draw is not tested here.</p>
<p>Fifteen clusters give roughly fifteen pieces of information about the residual field, and the NNDM spread reported above is the price of that, not a coding fault. <code>CAST</code> also offers a k-fold version of the same distance matching; it was not run here, so whether it narrows the spread at fifteen clusters is untested. The NNDM function is a port of the loop in <code>CAST::nndm()</code> checked against the package source line by line, not a run of the package itself.</p>
<p>The prediction set is every unsampled cell of the map, known exactly. With presence-only data the prediction set is still the cells where the map will be read, but the model is fitted to presences and background points, and whether the distance comparison still picks the honest scheme once background sampling is part of the design is not tested here. Neither is extrapolation: a sample confined to half the map asks a question about new ground that no resampling of the sample can fully answer, and the distance comparison would show that as a black curve no scheme can reach.</p>
<p>The design-based estimate from an independent probability validation sample is described, not simulated. Wadoux and colleagues found standard cross-validation less biased than the spatial kind even on a strongly clustered biomass dataset with large differences in sampling density; the clustered design here is more extreme, every plot sitting in one of fifteen compact clusters, and on it the blocked schemes did better than random folds, so the two results describe different designs rather than contradicting each other. The ranges in brackets are the smallest and largest of 40 or 20 draws, so they widen with more draws, and the per-draw agreement percentages rest on the same small counts.</p>
</section>
<section id="references" class="level2">
<h2 id="references-h" class="anchored" data-anchor-id="references">References</h2>
<p>Wadoux AMJ-C, Heuvelink GBM, de Bruin S, Brus DJ 2021 Ecological Modelling 457:109692 (<a href="https://doi.org/10.1016/j.ecolmodel.2021.109692">10.1016/j.ecolmodel.2021.109692</a>)</p>
<p>Mila C, Mateu J, Pebesma E, Meyer H 2022 Methods in Ecology and Evolution 13(6):1304-1316 (<a href="https://doi.org/10.1111/2041-210X.13851">10.1111/2041-210X.13851</a>)</p>
<p>Ploton P, Mortier F, Rejou-Mechain M et al 2020 Nature Communications 11:4540 (<a href="https://doi.org/10.1038/s41467-020-18321-y">10.1038/s41467-020-18321-y</a>)</p>
</section>
<section id="related-tutorials" class="level2">
<h2 id="related-tutorials-h" class="anchored" data-anchor-id="related-tutorials">Related tutorials</h2>
<ul>
<li><a href="https://tidyecology.com/posts/spatial-cross-validation-sdm/">Spatial cross-validation for SDMs in R</a></li>
<li><a href="https://tidyecology.com/posts/checking-a-tree-ensemble/">Checking a tree ensemble</a></li>
<li><a href="https://tidyecology.com/posts/data-leakage-in-model-validation/">Data leakage in ecological model validation</a></li>
<li><a href="https://tidyecology.com/posts/kriging-spatial-interpolation/">From scattered plots to a surface: IDW and kriging in R</a></li>
</ul>
<details class="te-repro" data-pagefind-ignore="">
<summary>Reproducibility</summary>
<ul>
<li>Code last run: 2026-10-15</li>
<li>R version 4.5.3 (2026-03-11), aarch64-apple-darwin20</li>
<li>Packages: ggplot2 4.0.3</li>
</ul>
</details>


<!-- -->

</section>

 ]]></description>
  <category>R</category>
  <category>cross-validation</category>
  <category>spatial statistics</category>
  <category>kriging</category>
  <category>model validation</category>
  <category>ecology tutorial</category>
  <guid isPermaLink="false">https://tidyecology.com/posts/which-spatial-cv-for-a-map/</guid>
  <pubDate>Sat, 26 Sep 2026 10:00:00 GMT</pubDate>
  <media:content url="https://tidyecology.com/posts/which-spatial-cv-for-a-map/thumbnail.png" medium="image" type="image/png" height="104" width="144"/>
</item>
<item>
  <title>Geographical detector: the interaction rule</title>
  <dc:creator>Tidy Ecology</dc:creator>
  <link>https://tidyecology.com/posts/geodetector-and-the-interaction-rule/</link>
  <description><![CDATA[ 





<p><em>Corrected 1 October 2026: the post said that every dataset it simulated was checked for the inequality between the combined and the single q values; it now says that the check covers the datasets of the replicated runs that keep all three q values.</em></p>
<p>A land-cover study has an NDVI value for every cell of a raster and two candidate drivers for it, elevation and distance to the nearest road, each cut into five classes. A common next step in land-use and remote-sensing ecology is the geographical detector. Its factor detector gives each driver a q value, the share of the variance in NDVI that its classes explain. Its interaction detector then overlays the two classifications, computes q for the combined classes, and names the pair with one of five words. A verdict often seen in published tables is “nonlinear enhancement”: the two drivers together explain more than the sum of what they explain apart, and the discussion section reads that as a synergy between elevation and roads.</p>
<p>The q value itself is not the problem. It is the ratio of the between-class sum of squares to the total sum of squares, which is eta squared from a one-way analysis of variance, and it answers a sensible question about stratified heterogeneity (Wang et al.&nbsp;2010; Wang, Zhang and Fu 2016). The problem is the rule that turns three q values into a verdict. This post measures how often that rule says “nonlinear enhancement” when the two drivers act on the response purely additively, with no interaction of any kind, and what decides the answer when it does.</p>
<p>The nearest posts on this site come at it from other sides. <a href="https://tidyecology.com/posts/variance-partitioning-varpart/">Variation partitioning in R</a> warns that “Raw R-squared always rises as you add predictors, so a set with more columns looks more important purely from its size”, and splits two sets of predictors into unique and shared fractions; the shared fraction reappears below as half of the interaction rule. <a href="https://tidyecology.com/posts/interaction-terms-glm/">Interaction terms in ecological GLMs</a> reads an interaction as a difference in slopes and shows that curves fanning apart on the count scale are not evidence of one; here there are no slopes, only class means. <a href="https://tidyecology.com/posts/natural-breaks-in-qgis-and-r/">Natural breaks in QGIS and R</a> is about how a continuous layer gets cut into classes in the first place, which is the step the detector takes for granted. The spatial half of the post leans on <a href="https://tidyecology.com/posts/spatial-autocorrelation-morans-i/">Spatial autocorrelation and Moran’s I in R</a> for the diagnostic and on <a href="https://tidyecology.com/posts/two-species-point-patterns/">Two-species point patterns</a> for the toroidal shift, which that post uses on point patterns and which is tried here on rasters. <a href="https://tidyecology.com/posts/permutation-nulls-that-keep-the-map/">Permutation nulls that keep the map</a> measures map-keeping nulls for the correlation between two maps on irregular sites; the question here is an interaction between two drivers on a regular grid, and the null is the shift rather than a spectral randomisation.</p>
<div class="cell">
<div class="code-copy-outer-scaffold"><div class="sourceCode cell-code" id="cb1" style="background: #f1f3f5;"><pre class="sourceCode r code-with-copy"><code class="sourceCode r"><span id="cb1-1"><span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">library</span>(ggplot2)</span>
<span id="cb1-2"><span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">library</span>(splines)</span>
<span id="cb1-3"></span>
<span id="cb1-4">te_paper  <span class="ot" style="color: #003B4F;
background-color: null;
font-style: inherit;">&lt;-</span> <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"#f5f4ee"</span></span>
<span id="cb1-5">te_ink    <span class="ot" style="color: #003B4F;
background-color: null;
font-style: inherit;">&lt;-</span> <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"#16241d"</span></span>
<span id="cb1-6">te_body   <span class="ot" style="color: #003B4F;
background-color: null;
font-style: inherit;">&lt;-</span> <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"#2c3a31"</span></span>
<span id="cb1-7">te_forest <span class="ot" style="color: #003B4F;
background-color: null;
font-style: inherit;">&lt;-</span> <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"#275139"</span></span>
<span id="cb1-8">te_rust   <span class="ot" style="color: #003B4F;
background-color: null;
font-style: inherit;">&lt;-</span> <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"#b5534e"</span></span>
<span id="cb1-9">te_gold   <span class="ot" style="color: #003B4F;
background-color: null;
font-style: inherit;">&lt;-</span> <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"#c9b458"</span></span>
<span id="cb1-10">te_line   <span class="ot" style="color: #003B4F;
background-color: null;
font-style: inherit;">&lt;-</span> <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"#dad9ca"</span></span>
<span id="cb1-11"></span>
<span id="cb1-12">theme_datasheet <span class="ot" style="color: #003B4F;
background-color: null;
font-style: inherit;">&lt;-</span> <span class="cf" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">function</span>() {</span>
<span id="cb1-13">  <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">theme_minimal</span>(<span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">base_size =</span> <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">12</span>) <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">+</span></span>
<span id="cb1-14">    <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">theme</span>(<span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">plot.background  =</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">element_rect</span>(<span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">fill =</span> te_paper, <span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">colour =</span> <span class="cn" style="color: #8f5902;
background-color: null;
font-style: inherit;">NA</span>),</span>
<span id="cb1-15">          <span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">panel.background =</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">element_rect</span>(<span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">fill =</span> te_paper, <span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">colour =</span> <span class="cn" style="color: #8f5902;
background-color: null;
font-style: inherit;">NA</span>),</span>
<span id="cb1-16">          <span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">panel.grid.major =</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">element_line</span>(<span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">colour =</span> te_line, <span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">linewidth =</span> <span class="fl" style="color: #AD0000;
background-color: null;
font-style: inherit;">0.3</span>),</span>
<span id="cb1-17">          <span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">panel.grid.minor =</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">element_blank</span>(),</span>
<span id="cb1-18">          <span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">text             =</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">element_text</span>(<span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">colour =</span> te_body),</span>
<span id="cb1-19">          <span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">plot.title       =</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">element_text</span>(<span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">colour =</span> te_ink, <span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">face =</span> <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"bold"</span>),</span>
<span id="cb1-20">          <span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">plot.subtitle    =</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">element_text</span>(<span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">colour =</span> te_body),</span>
<span id="cb1-21">          <span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">axis.text        =</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">element_text</span>(<span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">colour =</span> te_body),</span>
<span id="cb1-22">          <span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">strip.text       =</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">element_text</span>(<span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">colour =</span> te_ink))</span>
<span id="cb1-23">}</span></code></pre></div></div>
</div>
<section id="q-is-eta-squared-of-a-classification" class="level2">
<h2 id="q-is-eta-squared-of-a-classification-h" class="anchored" data-anchor-id="q-is-eta-squared-of-a-classification">q is eta squared of a classification</h2>
<p>Wang, Zhang and Fu (2016) write the statistic for a response of N units split into L classes as q = 1 - sum_h N_h sigma_h^2 / (N sigma^2), where N_h and sigma_h^2 are the size and variance of class h and sigma^2 is the variance of the whole response. With both variances taken with their own counts as divisors, N_h sigma_h^2 is the within-class sum of squares of class h, so q is one minus the within-class sum of squares over the total: the R-squared of a linear model with the class as a factor. The function below computes it from class sums, and the chunk checks it against <code>lm()</code>.</p>
<div class="cell">
<div class="code-copy-outer-scaffold"><div class="sourceCode cell-code" id="cb2" style="background: #f1f3f5;"><pre class="sourceCode r code-with-copy"><code class="sourceCode r"><span id="cb2-1">disc_q <span class="ot" style="color: #003B4F;
background-color: null;
font-style: inherit;">&lt;-</span> <span class="cf" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">function</span>(x, n_class) {</span>
<span id="cb2-2">  brk <span class="ot" style="color: #003B4F;
background-color: null;
font-style: inherit;">&lt;-</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">quantile</span>(x, <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">seq</span>(<span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">0</span>, <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">1</span>, <span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">length.out =</span> n_class <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">+</span> <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">1</span>))</span>
<span id="cb2-3">  <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">as.integer</span>(<span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">cut</span>(x, brk, <span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">include.lowest =</span> <span class="cn" style="color: #8f5902;
background-color: null;
font-style: inherit;">TRUE</span>))</span>
<span id="cb2-4">}</span>
<span id="cb2-5">ss_within <span class="ot" style="color: #003B4F;
background-color: null;
font-style: inherit;">&lt;-</span> <span class="cf" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">function</span>(y, g) {</span>
<span id="cb2-6">  n_g <span class="ot" style="color: #003B4F;
background-color: null;
font-style: inherit;">&lt;-</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">tabulate</span>(g)</span>
<span id="cb2-7">  n_g <span class="ot" style="color: #003B4F;
background-color: null;
font-style: inherit;">&lt;-</span> n_g[n_g <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">&gt;</span> <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">0</span>]</span>
<span id="cb2-8">  <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">sum</span>(y<span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">^</span><span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">2</span>) <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">-</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">sum</span>(<span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">rowsum</span>(y, g, <span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">reorder =</span> <span class="cn" style="color: #8f5902;
background-color: null;
font-style: inherit;">TRUE</span>)<span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">^</span><span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">2</span> <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">/</span> n_g)</span>
<span id="cb2-9">}</span>
<span id="cb2-10">q_stat <span class="ot" style="color: #003B4F;
background-color: null;
font-style: inherit;">&lt;-</span> <span class="cf" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">function</span>(y, g) <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">1</span> <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">-</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">ss_within</span>(y, g) <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">/</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">sum</span>((y <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">-</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">mean</span>(y))<span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">^</span><span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">2</span>)</span>
<span id="cb2-11"></span>
<span id="cb2-12">n_class <span class="ot" style="color: #003B4F;
background-color: null;
font-style: inherit;">&lt;-</span> <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">5</span></span>
<span id="cb2-13"><span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">set.seed</span>(<span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">4301</span>)</span>
<span id="cb2-14">x_demo <span class="ot" style="color: #003B4F;
background-color: null;
font-style: inherit;">&lt;-</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">rnorm</span>(<span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">200</span>)</span>
<span id="cb2-15">y_demo <span class="ot" style="color: #003B4F;
background-color: null;
font-style: inherit;">&lt;-</span> <span class="fl" style="color: #AD0000;
background-color: null;
font-style: inherit;">0.5</span> <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">*</span> x_demo <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">+</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">rnorm</span>(<span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">200</span>)</span>
<span id="cb2-16">g_demo <span class="ot" style="color: #003B4F;
background-color: null;
font-style: inherit;">&lt;-</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">disc_q</span>(x_demo, n_class)</span>
<span id="cb2-17">q_demo <span class="ot" style="color: #003B4F;
background-color: null;
font-style: inherit;">&lt;-</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">q_stat</span>(y_demo, g_demo)</span>
<span id="cb2-18"><span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">stopifnot</span>(<span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">abs</span>(q_demo <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">-</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">summary</span>(<span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">lm</span>(y_demo <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">~</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">factor</span>(g_demo)))<span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">$</span>r.squared) <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">&lt;</span> <span class="fl" style="color: #AD0000;
background-color: null;
font-style: inherit;">1e-12</span>)</span>
<span id="cb2-19"></span>
<span id="cb2-20">n_unit <span class="ot" style="color: #003B4F;
background-color: null;
font-style: inherit;">&lt;-</span> <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">1024</span></span>
<span id="cb2-21">n_null <span class="ot" style="color: #003B4F;
background-color: null;
font-style: inherit;">&lt;-</span> <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">2000</span></span>
<span id="cb2-22">null_q <span class="ot" style="color: #003B4F;
background-color: null;
font-style: inherit;">&lt;-</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">replicate</span>(n_null, {</span>
<span id="cb2-23">  y_n <span class="ot" style="color: #003B4F;
background-color: null;
font-style: inherit;">&lt;-</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">rnorm</span>(n_unit)</span>
<span id="cb2-24">  g1 <span class="ot" style="color: #003B4F;
background-color: null;
font-style: inherit;">&lt;-</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">disc_q</span>(<span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">rnorm</span>(n_unit), n_class)</span>
<span id="cb2-25">  g2 <span class="ot" style="color: #003B4F;
background-color: null;
font-style: inherit;">&lt;-</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">disc_q</span>(<span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">rnorm</span>(n_unit), n_class)</span>
<span id="cb2-26">  <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">c</span>(<span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">q1 =</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">q_stat</span>(y_n, g1), <span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">q12 =</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">q_stat</span>(y_n, (g1 <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">-</span> <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">1</span>L) <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">*</span> n_class <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">+</span> g2),</span>
<span id="cb2-27">    <span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">cells =</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">length</span>(<span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">unique</span>((g1 <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">-</span> <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">1</span>L) <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">*</span> n_class <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">+</span> g2)))</span>
<span id="cb2-28">})</span>
<span id="cb2-29">eq_one  <span class="ot" style="color: #003B4F;
background-color: null;
font-style: inherit;">&lt;-</span> (n_class <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">-</span> <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">1</span>) <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">/</span> (n_unit <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">-</span> <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">1</span>)</span>
<span id="cb2-30">eq_two  <span class="ot" style="color: #003B4F;
background-color: null;
font-style: inherit;">&lt;-</span> (n_class<span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">^</span><span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">2</span> <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">-</span> <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">1</span>) <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">/</span> (n_unit <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">-</span> <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">1</span>)</span>
<span id="cb2-31">null_m  <span class="ot" style="color: #003B4F;
background-color: null;
font-style: inherit;">&lt;-</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">rowMeans</span>(null_q)</span>
<span id="cb2-32">null_se <span class="ot" style="color: #003B4F;
background-color: null;
font-style: inherit;">&lt;-</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">apply</span>(null_q, <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">1</span>, sd) <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">/</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">sqrt</span>(n_null)</span>
<span id="cb2-33"><span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">stopifnot</span>(<span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">all</span>(null_q[<span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"cells"</span>, ] <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">==</span> n_class<span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">^</span><span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">2</span>))</span></code></pre></div></div>
</div>
<p>A classification explains some variance even when it is unrelated to the response, and how much has a closed form. With L classes and N units, the expected q of a classification drawn independently of the response is (L - 1) / (N - 1): under normal errors q follows a beta distribution with parameters (L - 1) / 2 and (N - L) / 2, and the same mean holds for any response under random reallocation of units to classes. For five classes and 1024 units that is 0.00391, and over 2000 simulated datasets with an unrelated response the mean q is 0.00396 (Monte Carlo standard error 0.00006). Overlaying two such classifications gives 25 combined classes, and the expected q rises to 24 / (N - 1) = 0.02346; the simulated mean is 0.02357 (standard error 0.00015). This is the size effect the varpart post warns about: more classes, more variance explained, with nothing behind it. Here the combined classification has six times the expected q of either of its parts before any driver has done anything.</p>
</section>
<section id="the-rule-and-the-identity-it-compares-against" class="level2">
<h2 id="the-rule-and-the-identity-it-compares-against-h" class="anchored" data-anchor-id="the-rule-and-the-identity-it-compares-against">The rule and the identity it compares against</h2>
<p>The interaction detector of Wang et al.&nbsp;(2010) computes q1 and q2 for the two classifications and q12 for the classification formed by every combination of their classes, and compares q12 with q1, q2 and q1 + q2. That paper lists seven relations, and they overlap: a q12 above the larger q but below the sum is there both an “enhance, bi-” (larger than each driver alone) and a “weaken” (smaller than the sum). Current software reduces them to five mutually exclusive types. The coding below follows the order of tests in <code>gdinteract()</code> of the GD package, version 10.9 (Song et al.&nbsp;2020), whose source was read for this post: q12 below the smaller of q1 and q2 is a nonlinear weakening; between the two is a univariate weakening; above the larger but below q1 + q2 is a bivariate enhancement; exactly q1 + q2 is independence; above q1 + q2 is a nonlinear enhancement.</p>
<div class="cell">
<div class="code-copy-outer-scaffold"><div class="sourceCode cell-code" id="cb3" style="background: #f1f3f5;"><pre class="sourceCode r code-with-copy"><code class="sourceCode r"><span id="cb3-1">gd_verdict <span class="ot" style="color: #003B4F;
background-color: null;
font-style: inherit;">&lt;-</span> <span class="cf" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">function</span>(q1, q2, q12) {</span>
<span id="cb3-2">  <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">ifelse</span>(q12 <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">&lt;</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">pmin</span>(q1, q2), <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"weaken, nonlinear"</span>,</span>
<span id="cb3-3">  <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">ifelse</span>(q12 <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">&lt;=</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">pmax</span>(q1, q2), <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"weaken, uni-"</span>,</span>
<span id="cb3-4">  <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">ifelse</span>(q12 <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">&lt;</span> q1 <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">+</span> q2, <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"enhance, bi-"</span>,</span>
<span id="cb3-5">  <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">ifelse</span>(q12 <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">==</span> q1 <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">+</span> q2, <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"independent"</span>, <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"enhance, nonlinear"</span>))))</span>
<span id="cb3-6">}</span>
<span id="cb3-7">verdict_levels <span class="ot" style="color: #003B4F;
background-color: null;
font-style: inherit;">&lt;-</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">c</span>(<span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"enhance, nonlinear"</span>, <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"independent"</span>, <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"enhance, bi-"</span>,</span>
<span id="cb3-8">                    <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"weaken, uni-"</span>, <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"weaken, nonlinear"</span>)</span>
<span id="cb3-9"></span>
<span id="cb3-10"><span class="co" style="color: #5E5E5E;
background-color: null;
font-style: inherit;"># population q of one quintile classification of a standard normal driver</span></span>
<span id="cb3-11">cut_pts <span class="ot" style="color: #003B4F;
background-color: null;
font-style: inherit;">&lt;-</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">qnorm</span>(<span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">seq</span>(<span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">0</span>, <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">1</span>, <span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">length.out =</span> n_class <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">+</span> <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">1</span>))</span>
<span id="cb3-12">cls_mean <span class="ot" style="color: #003B4F;
background-color: null;
font-style: inherit;">&lt;-</span> (<span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">dnorm</span>(cut_pts[<span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">-</span>(n_class <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">+</span> <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">1</span>)]) <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">-</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">dnorm</span>(cut_pts[<span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">-</span><span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">1</span>])) <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">*</span> n_class</span>
<span id="cb3-13">v_between <span class="ot" style="color: #003B4F;
background-color: null;
font-style: inherit;">&lt;-</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">mean</span>(cls_mean<span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">^</span><span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">2</span>)</span>
<span id="cb3-14">b_set <span class="ot" style="color: #003B4F;
background-color: null;
font-style: inherit;">&lt;-</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">c</span>(<span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">0</span>, <span class="fl" style="color: #AD0000;
background-color: null;
font-style: inherit;">0.25</span>, <span class="fl" style="color: #AD0000;
background-color: null;
font-style: inherit;">0.5</span>, <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">1</span>)</span>
<span id="cb3-15">q_pop <span class="ot" style="color: #003B4F;
background-color: null;
font-style: inherit;">&lt;-</span> b_set<span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">^</span><span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">2</span> <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">*</span> v_between <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">/</span> (<span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">2</span> <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">*</span> b_set<span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">^</span><span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">2</span> <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">+</span> <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">1</span>)</span>
<span id="cb3-16"></span>
<span id="cb3-17">gd_pieces <span class="ot" style="color: #003B4F;
background-color: null;
font-style: inherit;">&lt;-</span> <span class="cf" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">function</span>(y, g1, g2) {</span>
<span id="cb3-18">  g12 <span class="ot" style="color: #003B4F;
background-color: null;
font-style: inherit;">&lt;-</span> (g1 <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">-</span> <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">1</span>L) <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">*</span> n_class <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">+</span> g2</span>
<span id="cb3-19">  sst <span class="ot" style="color: #003B4F;
background-color: null;
font-style: inherit;">&lt;-</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">sum</span>((y <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">-</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">mean</span>(y))<span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">^</span><span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">2</span>)</span>
<span id="cb3-20">  sse_cell <span class="ot" style="color: #003B4F;
background-color: null;
font-style: inherit;">&lt;-</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">ss_within</span>(y, g12)</span>
<span id="cb3-21">  x_add <span class="ot" style="color: #003B4F;
background-color: null;
font-style: inherit;">&lt;-</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">cbind</span>(<span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">1</span>, <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">outer</span>(g1, <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">2</span><span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">:</span>n_class, <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"=="</span>) <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">+</span> <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">0</span>, <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">outer</span>(g2, <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">2</span><span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">:</span>n_class, <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"=="</span>) <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">+</span> <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">0</span>)</span>
<span id="cb3-22">  sse_add <span class="ot" style="color: #003B4F;
background-color: null;
font-style: inherit;">&lt;-</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">sum</span>(<span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">.lm.fit</span>(x_add, y)<span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">$</span>residuals<span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">^</span><span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">2</span>)</span>
<span id="cb3-23">  n_cell <span class="ot" style="color: #003B4F;
background-color: null;
font-style: inherit;">&lt;-</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">length</span>(<span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">unique</span>(g12))</span>
<span id="cb3-24">  df_ab <span class="ot" style="color: #003B4F;
background-color: null;
font-style: inherit;">&lt;-</span> n_cell <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">-</span> <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">2</span> <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">*</span> n_class <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">+</span> <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">1</span></span>
<span id="cb3-25">  df_e  <span class="ot" style="color: #003B4F;
background-color: null;
font-style: inherit;">&lt;-</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">length</span>(y) <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">-</span> n_cell</span>
<span id="cb3-26">  f_ab  <span class="ot" style="color: #003B4F;
background-color: null;
font-style: inherit;">&lt;-</span> ((sse_add <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">-</span> sse_cell) <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">/</span> df_ab) <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">/</span> (sse_cell <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">/</span> df_e)</span>
<span id="cb3-27">  n_g <span class="ot" style="color: #003B4F;
background-color: null;
font-style: inherit;">&lt;-</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">tabulate</span>(g12)</span>
<span id="cb3-28">  <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">c</span>(<span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">q1 =</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">q_stat</span>(y, g1), <span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">q2 =</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">q_stat</span>(y, g2), <span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">q12 =</span> <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">1</span> <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">-</span> sse_cell <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">/</span> sst,</span>
<span id="cb3-29">    <span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">q_add =</span> <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">1</span> <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">-</span> sse_add <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">/</span> sst, <span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">f_p =</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">pf</span>(f_ab, df_ab, df_e, <span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">lower.tail =</span> <span class="cn" style="color: #8f5902;
background-color: null;
font-style: inherit;">FALSE</span>),</span>
<span id="cb3-30">    <span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">single =</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">sum</span>(n_g <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">==</span> <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">1</span>))</span>
<span id="cb3-31">}</span>
<span id="cb3-32"></span>
<span id="cb3-33"><span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">set.seed</span>(<span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">4302</span>)</span>
<span id="cb3-34">n_big <span class="ot" style="color: #003B4F;
background-color: null;
font-style: inherit;">&lt;-</span> <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">2</span><span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">^</span><span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">20</span></span>
<span id="cb3-35">x1_big <span class="ot" style="color: #003B4F;
background-color: null;
font-style: inherit;">&lt;-</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">rnorm</span>(n_big)</span>
<span id="cb3-36">x2_big <span class="ot" style="color: #003B4F;
background-color: null;
font-style: inherit;">&lt;-</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">rnorm</span>(n_big)</span>
<span id="cb3-37">y_big  <span class="ot" style="color: #003B4F;
background-color: null;
font-style: inherit;">&lt;-</span> <span class="fl" style="color: #AD0000;
background-color: null;
font-style: inherit;">0.5</span> <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">*</span> x1_big <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">+</span> <span class="fl" style="color: #AD0000;
background-color: null;
font-style: inherit;">0.5</span> <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">*</span> x2_big <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">+</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">rnorm</span>(n_big)</span>
<span id="cb3-38">big <span class="ot" style="color: #003B4F;
background-color: null;
font-style: inherit;">&lt;-</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">gd_pieces</span>(y_big, <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">disc_q</span>(x1_big, n_class), <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">disc_q</span>(x2_big, n_class))</span>
<span id="cb3-39">big_gap <span class="ot" style="color: #003B4F;
background-color: null;
font-style: inherit;">&lt;-</span> big[[<span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"q12"</span>]] <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">-</span> big[[<span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"q1"</span>]] <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">-</span> big[[<span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"q2"</span>]]</span>
<span id="cb3-40"><span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">stopifnot</span>(<span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">abs</span>((big[[<span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"q12"</span>]] <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">-</span> big[[<span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"q1"</span>]] <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">-</span> big[[<span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"q2"</span>]]) <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">-</span></span>
<span id="cb3-41">              ((big[[<span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"q12"</span>]] <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">-</span> big[[<span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"q_add"</span>]]) <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">-</span> (big[[<span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"q1"</span>]] <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">+</span> big[[<span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"q2"</span>]] <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">-</span> big[[<span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"q_add"</span>]]))) <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">&lt;</span> <span class="fl" style="color: #AD0000;
background-color: null;
font-style: inherit;">1e-12</span>)</span></code></pre></div></div>
</div>
<p>For two drivers that act additively and independently, the population value of q12 is exactly q1 + q2. Write the response as y = f1(x1) + f2(x2) + e. The between-class variance of the combined classes is the variance of E[y | class of x1, class of x2], which is E[f1 | class of x1] + E[f2 | class of x2] plus a constant, because the class of x2 carries no information about x1. The two terms are independent, so their variances add, and dividing by the variance of y gives q12 = q1 + q2. This is an identity of the population, not a simulation result, and the “independent” verdict is the one the rule reserves for it. An estimate never lands on an equality between continuous quantities, so for additive independent drivers the rule has to pick one of the other four words.</p>
<p>In fact it has only two to choose from. Every combined class lies inside one class of x1 and one class of x2, so splitting the units into combined classes can only lower the within-class sum of squares of either single classification, never raise it. On the same units q12 is therefore at least as large as the larger of q1 and q2, and the two weakening types cannot occur. The GD code drops classes that hold a single unit before computing each q, which changes the units behind q12 and is one route by which a weakening could appear there; missing driver values are another, because GD drops those units from the within-class sum of a single driver but keeps them in its total, and keeps them as classes of their own in the combined one. Here q is computed on all units, as the formula defines it, and every dataset of the replicated runs below that keep q1, q2 and q12 is checked for the inequality.</p>
<p>With y = 0.5 x1 + 0.5 x2 + e and quintile classes of standard normal drivers, the population q of each driver is 0.1495, from the class means of a normal in closed form. One dataset of 1048576 units gives q1 = 0.1505, q2 = 0.1503 and q12 = 0.3005, and q12 - q1 - q2 = -0.00033.</p>
<p>What decides the sign of q12 - q1 - q2 in a finite sample is an exact split into two pieces. Let q_add be the R-squared of the additive two-way model with both classifications as factors and no interaction. Then q12 - q1 - q2 = (q12 - q_add) - (q1 + q2 - q_add). The first piece is the interaction sum of squares of a two-way analysis of variance on the same classes, divided by the total; it can never be negative, because the additive model is nested in the combined-class model. The second piece is the raw shared fraction of variation partitioning, the part of the explained variance that the two classifications claim twice. The rule says “nonlinear enhancement” exactly when the interaction piece beats the shared piece. The <code>stopifnot()</code> in the chunk checks the split on the large dataset.</p>
</section>
<section id="additive-drivers-read-as-enhancing" class="level2">
<h2 id="additive-drivers-read-as-enhancing-h" class="anchored" data-anchor-id="additive-drivers-read-as-enhancing">Additive drivers, read as enhancing</h2>
<p>The design below is fixed before running: two independent standard normal drivers, quintile classes, y = b x1 + b x2 + e with standard normal e, and b of 0, 0.25, 0.5 and 1, so that each driver’s population q runs from zero to 0.299. Every dataset is run through the rule and through the interaction F test of the two-way analysis of variance on the same classes, which is the standard test of the question the rule is trying to answer.</p>
<div class="cell">
<div class="code-copy-outer-scaffold"><div class="sourceCode cell-code" id="cb4" style="background: #f1f3f5;"><pre class="sourceCode r code-with-copy"><code class="sourceCode r"><span id="cb4-1">n_set <span class="ot" style="color: #003B4F;
background-color: null;
font-style: inherit;">&lt;-</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">c</span>(<span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">256</span>, <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">1024</span>, <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">4096</span>, <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">16384</span>)</span>
<span id="cb4-2">n_rep <span class="ot" style="color: #003B4F;
background-color: null;
font-style: inherit;">&lt;-</span> <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">400</span></span>
<span id="cb4-3"><span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">set.seed</span>(<span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">4303</span>)</span>
<span id="cb4-4">rate_raw <span class="ot" style="color: #003B4F;
background-color: null;
font-style: inherit;">&lt;-</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">do.call</span>(rbind, <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">lapply</span>(n_set, <span class="cf" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">function</span>(nn) <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">do.call</span>(rbind, <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">lapply</span>(b_set, <span class="cf" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">function</span>(bb) {</span>
<span id="cb4-5">  out <span class="ot" style="color: #003B4F;
background-color: null;
font-style: inherit;">&lt;-</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">t</span>(<span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">replicate</span>(n_rep, {</span>
<span id="cb4-6">    x1 <span class="ot" style="color: #003B4F;
background-color: null;
font-style: inherit;">&lt;-</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">rnorm</span>(nn)</span>
<span id="cb4-7">    x2 <span class="ot" style="color: #003B4F;
background-color: null;
font-style: inherit;">&lt;-</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">rnorm</span>(nn)</span>
<span id="cb4-8">    <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">gd_pieces</span>(bb <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">*</span> x1 <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">+</span> bb <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">*</span> x2 <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">+</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">rnorm</span>(nn), <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">disc_q</span>(x1, n_class), <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">disc_q</span>(x2, n_class))</span>
<span id="cb4-9">  }))</span>
<span id="cb4-10">  <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">data.frame</span>(<span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">n =</span> nn, <span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">b =</span> bb, out)</span>
<span id="cb4-11">}))))</span>
<span id="cb4-12"><span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">stopifnot</span>(<span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">all</span>(rate_raw<span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">$</span>q12 <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">&gt;=</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">pmax</span>(rate_raw<span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">$</span>q1, rate_raw<span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">$</span>q2) <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">-</span> <span class="fl" style="color: #AD0000;
background-color: null;
font-style: inherit;">1e-12</span>))</span>
<span id="cb4-13">rate_raw<span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">$</span>verdict <span class="ot" style="color: #003B4F;
background-color: null;
font-style: inherit;">&lt;-</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">gd_verdict</span>(rate_raw<span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">$</span>q1, rate_raw<span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">$</span>q2, rate_raw<span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">$</span>q12)</span>
<span id="cb4-14">rate_raw<span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">$</span>enh <span class="ot" style="color: #003B4F;
background-color: null;
font-style: inherit;">&lt;-</span> rate_raw<span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">$</span>verdict <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">==</span> <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"enhance, nonlinear"</span></span>
<span id="cb4-15">rate_raw<span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">$</span>f_rej <span class="ot" style="color: #003B4F;
background-color: null;
font-style: inherit;">&lt;-</span> rate_raw<span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">$</span>f_p <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">&lt;</span> <span class="fl" style="color: #AD0000;
background-color: null;
font-style: inherit;">0.05</span></span>
<span id="cb4-16">rate_tab <span class="ot" style="color: #003B4F;
background-color: null;
font-style: inherit;">&lt;-</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">aggregate</span>(<span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">cbind</span>(enh, f_rej, q1) <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">~</span> n <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">+</span> b, rate_raw, mean)</span>
<span id="cb4-17">rt <span class="ot" style="color: #003B4F;
background-color: null;
font-style: inherit;">&lt;-</span> <span class="cf" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">function</span>(nn, bb, v) rate_tab[rate_tab<span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">$</span>n <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">==</span> nn <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">&amp;</span> rate_tab<span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">$</span>b <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">==</span> bb, v]</span>
<span id="cb4-18">mc_se_max <span class="ot" style="color: #003B4F;
background-color: null;
font-style: inherit;">&lt;-</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">sqrt</span>(<span class="fl" style="color: #AD0000;
background-color: null;
font-style: inherit;">0.25</span> <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">/</span> n_rep)</span>
<span id="cb4-19">n_indep <span class="ot" style="color: #003B4F;
background-color: null;
font-style: inherit;">&lt;-</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">sum</span>(rate_raw<span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">$</span>verdict <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">==</span> <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"independent"</span>)</span>
<span id="cb4-20">f_range <span class="ot" style="color: #003B4F;
background-color: null;
font-style: inherit;">&lt;-</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">range</span>(rate_tab<span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">$</span>f_rej)</span>
<span id="cb4-21">f_se <span class="ot" style="color: #003B4F;
background-color: null;
font-style: inherit;">&lt;-</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">sqrt</span>(<span class="fl" style="color: #AD0000;
background-color: null;
font-style: inherit;">0.05</span> <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">*</span> <span class="fl" style="color: #AD0000;
background-color: null;
font-style: inherit;">0.95</span> <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">/</span> n_rep)</span></code></pre></div></div>
</div>
<p>Each rate below comes from 400 datasets, so its Monte Carlo standard error is at most 0.025. At 1024 units and b = 0.5, where each driver explains about 15 per cent of the variance, the rule reports a nonlinear enhancement in 86.0 per cent of datasets. With no effect at all, b = 0, it does so in 100.0 per cent, and at b = 0.25 in 99.2 per cent. The verdict “independent” came up 0 times in 6400 datasets.</p>
<p>More data does not rescue the rule. At 16384 units the rate is 59.2 per cent for b = 0.5 and 52.0 per cent for b = 1, while for b = 0 it is still 100.0 per cent. The interaction F test on the same datasets rejects at the five per cent level in 3.3 to 5.7 per cent of the datasets across all sixteen combinations of N and b; a single rate of five per cent would have a Monte Carlo standard error of 0.011.</p>
<div class="cell">
<div class="code-copy-outer-scaffold"><div class="sourceCode cell-code" id="cb5" style="background: #f1f3f5;"><pre class="sourceCode r code-with-copy"><code class="sourceCode r"><span id="cb5-1">rate_long <span class="ot" style="color: #003B4F;
background-color: null;
font-style: inherit;">&lt;-</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">rbind</span>(</span>
<span id="cb5-2">  <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">data.frame</span>(rate_tab[, <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">c</span>(<span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"n"</span>, <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"b"</span>)], <span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">panel =</span> <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"rule: nonlinear enhancement"</span>, <span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">rate =</span> rate_tab<span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">$</span>enh),</span>
<span id="cb5-3">  <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">data.frame</span>(rate_tab[, <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">c</span>(<span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"n"</span>, <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"b"</span>)], <span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">panel =</span> <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"interaction F test, p &lt; 0.05"</span>, <span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">rate =</span> rate_tab<span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">$</span>f_rej))</span>
<span id="cb5-4">rate_long<span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">$</span>panel <span class="ot" style="color: #003B4F;
background-color: null;
font-style: inherit;">&lt;-</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">factor</span>(rate_long<span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">$</span>panel, <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">c</span>(<span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"rule: nonlinear enhancement"</span>, <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"interaction F test, p &lt; 0.05"</span>))</span>
<span id="cb5-5">rate_long<span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">$</span>b_lab <span class="ot" style="color: #003B4F;
background-color: null;
font-style: inherit;">&lt;-</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">factor</span>(<span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">sprintf</span>(<span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"b = %.2f, q = %.3f"</span>, rate_long<span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">$</span>b, q_pop[<span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">match</span>(rate_long<span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">$</span>b, b_set)]))</span>
<span id="cb5-6">ref_df <span class="ot" style="color: #003B4F;
background-color: null;
font-style: inherit;">&lt;-</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">data.frame</span>(<span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">panel =</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">factor</span>(<span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">levels</span>(rate_long<span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">$</span>panel), <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">levels</span>(rate_long<span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">$</span>panel)), <span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">y_ref =</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">c</span>(<span class="fl" style="color: #AD0000;
background-color: null;
font-style: inherit;">0.5</span>, <span class="fl" style="color: #AD0000;
background-color: null;
font-style: inherit;">0.05</span>))</span>
<span id="cb5-7">lim_df <span class="ot" style="color: #003B4F;
background-color: null;
font-style: inherit;">&lt;-</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">data.frame</span>(<span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">panel =</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">factor</span>(<span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">rep</span>(<span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">levels</span>(rate_long<span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">$</span>panel), <span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">each =</span> <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">2</span>), <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">levels</span>(rate_long<span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">$</span>panel)),</span>
<span id="cb5-8">                     <span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">n =</span> n_set[<span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">1</span>], <span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">rate =</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">c</span>(<span class="fl" style="color: #AD0000;
background-color: null;
font-style: inherit;">0.4</span>, <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">1</span>, <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">0</span>, <span class="fl" style="color: #AD0000;
background-color: null;
font-style: inherit;">0.1</span>))</span>
<span id="cb5-9"></span>
<span id="cb5-10"><span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">ggplot</span>(rate_long, <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">aes</span>(n, rate, <span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">colour =</span> b_lab)) <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">+</span></span>
<span id="cb5-11">  <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">geom_hline</span>(<span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">data =</span> ref_df, <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">aes</span>(<span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">yintercept =</span> y_ref), <span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">linetype =</span> <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"dashed"</span>,</span>
<span id="cb5-12">             <span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">colour =</span> te_body, <span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">linewidth =</span> <span class="fl" style="color: #AD0000;
background-color: null;
font-style: inherit;">0.5</span>) <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">+</span></span>
<span id="cb5-13">  <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">geom_blank</span>(<span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">data =</span> lim_df, <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">aes</span>(n, rate), <span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">inherit.aes =</span> <span class="cn" style="color: #8f5902;
background-color: null;
font-style: inherit;">FALSE</span>) <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">+</span></span>
<span id="cb5-14">  <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">geom_line</span>(<span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">linewidth =</span> <span class="fl" style="color: #AD0000;
background-color: null;
font-style: inherit;">0.9</span>) <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">+</span></span>
<span id="cb5-15">  <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">geom_point</span>(<span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">size =</span> <span class="fl" style="color: #AD0000;
background-color: null;
font-style: inherit;">2.2</span>) <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">+</span></span>
<span id="cb5-16">  <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">facet_wrap</span>(<span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">~</span> panel, <span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">scales =</span> <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"free_y"</span>) <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">+</span></span>
<span id="cb5-17">  <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">scale_x_log10</span>(<span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">breaks =</span> n_set) <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">+</span></span>
<span id="cb5-18">  <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">scale_colour_manual</span>(<span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">values =</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">c</span>(te_ink, te_forest, te_gold, te_rust), <span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">name =</span> <span class="cn" style="color: #8f5902;
background-color: null;
font-style: inherit;">NULL</span>) <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">+</span></span>
<span id="cb5-19">  <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">labs</span>(<span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">x =</span> <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"units (log scale)"</span>, <span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">y =</span> <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"share of datasets"</span>,</span>
<span id="cb5-20">       <span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">title =</span> <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"Additive drivers, read as a synergy"</span>) <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">+</span></span>
<span id="cb5-21">  <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">theme_datasheet</span>() <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">+</span></span>
<span id="cb5-22">  <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">theme</span>(<span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">legend.position =</span> <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"bottom"</span>) <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">+</span></span>
<span id="cb5-23">  <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">guides</span>(<span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">colour =</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">guide_legend</span>(<span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">nrow =</span> <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">2</span>))</span></code></pre></div></div>
<div class="cell-output-display">
<div id="fig-rate" class="quarto-float quarto-figure quarto-figure-center anchored" alt="Two line panels on warm off-white paper sharing a horizontal axis of units at 256, 1024, 4096 and 16384 on a log scale, with four coloured lines for effect sizes b from 0 to 1, their population q values given in the legend. In the left panel, the share called a nonlinear enhancement, the black line for b = 0 stays at 1 throughout, the dark green line for b = 0.25 falls slowly from 1 to about 0.87, the gold line for b = 0.5 falls from about 0.95 to about 0.59, and the red line for b = 1 falls from about 0.66 to about 0.52, just above a dashed line at 0.5. In the right panel, the interaction F test rejection share, all four lines wander between about 0.03 and 0.06 around a dashed line at 0.05, on a scale running from 0 to 0.1.">
<figure class="quarto-float quarto-float-fig figure">
<div aria-describedby="fig-rate-caption-0ceaefa1-69ba-4598-a22c-09a6ac19f8ca">
<img src="https://tidyecology.com/posts/geodetector-and-the-interaction-rule/index_files/figure-html/fig-rate-1.png" class="img-fluid figure-img" alt="Two line panels on warm off-white paper sharing a horizontal axis of units at 256, 1024, 4096 and 16384 on a log scale, with four coloured lines for effect sizes b from 0 to 1, their population q values given in the legend. In the left panel, the share called a nonlinear enhancement, the black line for b = 0 stays at 1 throughout, the dark green line for b = 0.25 falls slowly from 1 to about 0.87, the gold line for b = 0.5 falls from about 0.95 to about 0.59, and the red line for b = 1 falls from about 0.66 to about 0.52, just above a dashed line at 0.5. In the right panel, the interaction F test rejection share, all four lines wander between about 0.03 and 0.06 around a dashed line at 0.05, on a scale running from 0 to 0.1." width="672">
</div>
<figcaption class="quarto-float-caption-bottom quarto-float-caption quarto-float-fig" id="fig-rate-caption-0ceaefa1-69ba-4598-a22c-09a6ac19f8ca">
Figure&nbsp;1: Share of datasets with two independent, additive drivers that the interaction rule calls a nonlinear enhancement (left) and that the two-way interaction F test rejects at the five per cent level (right), by number of units and effect size b. Each point is 400 datasets.
</figcaption>
</figure>
</div>
</div>
</div>
<p>The split into an interaction piece and a shared piece says why. The interaction piece is never negative and, with no interaction, it is the share of the variance picked up by the (L - 1)^2 = 16 interaction degrees of freedom out of the variance the additive model leaves unexplained, so its expected size is about 16 / (N - 1) times one minus q_add. The shared piece would be exactly zero if the counts in the 25 combined classes were exactly proportional to the class totals, because the two classifications would then be orthogonal factors and their sums of squares would add. With independent drivers the counts are proportional only in expectation, and in any one dataset they wander from it; that makes the shared piece positive in some datasets and negative in others, by an amount that grows with the size of the effects.</p>
<div class="cell">
<div class="code-copy-outer-scaffold"><div class="sourceCode cell-code" id="cb6" style="background: #f1f3f5;"><pre class="sourceCode r code-with-copy"><code class="sourceCode r"><span id="cb6-1">dec <span class="ot" style="color: #003B4F;
background-color: null;
font-style: inherit;">&lt;-</span> rate_raw[rate_raw<span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">$</span>b <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">==</span> <span class="fl" style="color: #AD0000;
background-color: null;
font-style: inherit;">0.5</span> <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">&amp;</span> rate_raw<span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">$</span>n <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">%in%</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">c</span>(<span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">1024</span>, <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">16384</span>), ]</span>
<span id="cb6-2">dec<span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">$</span>inter  <span class="ot" style="color: #003B4F;
background-color: null;
font-style: inherit;">&lt;-</span> dec<span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">$</span>q12 <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">-</span> dec<span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">$</span>q_add</span>
<span id="cb6-3">dec<span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">$</span>shared <span class="ot" style="color: #003B4F;
background-color: null;
font-style: inherit;">&lt;-</span> dec<span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">$</span>q1 <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">+</span> dec<span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">$</span>q2 <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">-</span> dec<span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">$</span>q_add</span>
<span id="cb6-4"><span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">stopifnot</span>(<span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">all</span>(dec<span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">$</span>inter <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">&gt;=</span> <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">0</span>), <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">all</span>(dec<span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">$</span>enh <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">==</span> (dec<span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">$</span>inter <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">&gt;</span> dec<span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">$</span>shared)))</span>
<span id="cb6-5">dec_tab <span class="ot" style="color: #003B4F;
background-color: null;
font-style: inherit;">&lt;-</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">aggregate</span>(<span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">cbind</span>(inter, shared, q_add) <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">~</span> n, dec, mean)</span>
<span id="cb6-6">dec_sd  <span class="ot" style="color: #003B4F;
background-color: null;
font-style: inherit;">&lt;-</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">aggregate</span>(shared <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">~</span> n, dec, sd)</span>
<span id="cb6-7">dec_pos <span class="ot" style="color: #003B4F;
background-color: null;
font-style: inherit;">&lt;-</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">aggregate</span>(shared <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">~</span> n, dec, <span class="cf" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">function</span>(v) <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">mean</span>(v <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">&gt;</span> <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">0</span>))</span>
<span id="cb6-8">dk <span class="ot" style="color: #003B4F;
background-color: null;
font-style: inherit;">&lt;-</span> <span class="cf" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">function</span>(nn, tb, v) tb[tb<span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">$</span>n <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">==</span> nn, v]</span>
<span id="cb6-9">ratio_1k  <span class="ot" style="color: #003B4F;
background-color: null;
font-style: inherit;">&lt;-</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">dk</span>(<span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">1024</span>, dec_tab, <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"inter"</span>) <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">/</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">dk</span>(<span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">1024</span>, dec_sd, <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"shared"</span>)</span>
<span id="cb6-10">ratio_16k <span class="ot" style="color: #003B4F;
background-color: null;
font-style: inherit;">&lt;-</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">dk</span>(<span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">16384</span>, dec_tab, <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"inter"</span>) <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">/</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">dk</span>(<span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">16384</span>, dec_sd, <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"shared"</span>)</span>
<span id="cb6-11">inter_expect <span class="ot" style="color: #003B4F;
background-color: null;
font-style: inherit;">&lt;-</span> (n_class <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">-</span> <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">1</span>)<span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">^</span><span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">2</span> <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">/</span> (<span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">1024</span> <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">-</span> <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">1</span>) <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">*</span> (<span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">1</span> <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">-</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">dk</span>(<span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">1024</span>, dec_tab, <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"q_add"</span>))</span>
<span id="cb6-12">shared_se_1k <span class="ot" style="color: #003B4F;
background-color: null;
font-style: inherit;">&lt;-</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">dk</span>(<span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">1024</span>, dec_sd, <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"shared"</span>) <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">/</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">sqrt</span>(n_rep)</span>
<span id="cb6-13"></span>
<span id="cb6-14">sub_1k <span class="ot" style="color: #003B4F;
background-color: null;
font-style: inherit;">&lt;-</span> rate_raw[rate_raw<span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">$</span>n <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">==</span> <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">1024</span>, ]</span>
<span id="cb6-15">sub_1k<span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">$</span>inter  <span class="ot" style="color: #003B4F;
background-color: null;
font-style: inherit;">&lt;-</span> sub_1k<span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">$</span>q12 <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">-</span> sub_1k<span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">$</span>q_add</span>
<span id="cb6-16">sub_1k<span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">$</span>shared <span class="ot" style="color: #003B4F;
background-color: null;
font-style: inherit;">&lt;-</span> sub_1k<span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">$</span>q1 <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">+</span> sub_1k<span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">$</span>q2 <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">-</span> sub_1k<span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">$</span>q_add</span>
<span id="cb6-17">by_b <span class="ot" style="color: #003B4F;
background-color: null;
font-style: inherit;">&lt;-</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">data.frame</span>(<span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">b =</span> b_set,</span>
<span id="cb6-18">  <span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">inter =</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">tapply</span>(sub_1k<span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">$</span>inter, sub_1k<span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">$</span>b, mean),</span>
<span id="cb6-19">  <span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">shared_sd =</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">tapply</span>(sub_1k<span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">$</span>shared, sub_1k<span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">$</span>b, sd))</span>
<span id="cb6-20"></span>
<span id="cb6-21">g_bal1 <span class="ot" style="color: #003B4F;
background-color: null;
font-style: inherit;">&lt;-</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">rep</span>(<span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">1</span><span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">:</span>n_class, <span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">each =</span> <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">200</span>)</span>
<span id="cb6-22">g_bal2 <span class="ot" style="color: #003B4F;
background-color: null;
font-style: inherit;">&lt;-</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">rep</span>(<span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">rep</span>(<span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">1</span><span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">:</span>n_class, <span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">each =</span> <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">40</span>), n_class)</span>
<span id="cb6-23"><span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">stopifnot</span>(<span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">all</span>(<span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">table</span>(g_bal1, g_bal2) <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">==</span> <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">40</span>))</span>
<span id="cb6-24"><span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">set.seed</span>(<span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">4309</span>)</span>
<span id="cb6-25">y_bal <span class="ot" style="color: #003B4F;
background-color: null;
font-style: inherit;">&lt;-</span> <span class="fl" style="color: #AD0000;
background-color: null;
font-style: inherit;">0.5</span> <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">*</span> g_bal1 <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">+</span> <span class="fl" style="color: #AD0000;
background-color: null;
font-style: inherit;">0.5</span> <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">*</span> g_bal2 <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">+</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">rnorm</span>(<span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">length</span>(g_bal1))</span>
<span id="cb6-26">bal <span class="ot" style="color: #003B4F;
background-color: null;
font-style: inherit;">&lt;-</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">gd_pieces</span>(y_bal, g_bal1, g_bal2)</span>
<span id="cb6-27">bal_shared <span class="ot" style="color: #003B4F;
background-color: null;
font-style: inherit;">&lt;-</span> bal[[<span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"q1"</span>]] <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">+</span> bal[[<span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"q2"</span>]] <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">-</span> bal[[<span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"q_add"</span>]]</span>
<span id="cb6-28"><span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">stopifnot</span>(<span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">abs</span>(bal_shared) <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">&lt;</span> <span class="fl" style="color: #AD0000;
background-color: null;
font-style: inherit;">1e-12</span>)</span></code></pre></div></div>
</div>
<p>On a balanced design with exactly 40 units in every combined class the shared piece is zero to rounding error; the <code>stopifnot()</code> in the chunk requires it to be below one part in a trillion. On the simulated datasets at 1024 units its standard deviation is 0.00021 with no effect, 0.0034 at b = 0.25, 0.0090 at b = 0.5 and 0.0198 at b = 1, while the mean interaction piece is 0.0155, 0.0137, 0.0109 and 0.0062. With no effect the shared piece is far smaller than the interaction piece and the rule says “nonlinear enhancement” every time; as the effect grows the shared piece catches up, and at b = 1 its standard deviation is the larger of the two.</p>
<p>At b = 0.5 the mean interaction piece is 0.0109 at 1024 units, against 0.0109 from 16 / (N - 1) times one minus the mean q_add, and 0.00067 at 16384, falling roughly as 1 / N. The shared piece has a mean of -0.00008 (Monte Carlo standard error 0.00045) and a standard deviation of 0.0090 at 1024 units, and +0.00004 and 0.00240 at 16384; it is positive in 48.2 and 51.5 per cent of datasets. The ratio of the mean interaction piece to that standard deviation drops from 1.21 to 0.28: the interaction piece shrinks like 1 / N and the shared piece like one over the square root of N, so with enough units the verdict turns on the sign of the shared piece, and that sign is set by chance. The rate of “nonlinear enhancement” heads for one half, not for zero.</p>
<div class="cell">
<div class="code-copy-outer-scaffold"><div class="sourceCode cell-code" id="cb7" style="background: #f1f3f5;"><pre class="sourceCode r code-with-copy"><code class="sourceCode r"><span id="cb7-1">dec<span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">$</span>n_lab <span class="ot" style="color: #003B4F;
background-color: null;
font-style: inherit;">&lt;-</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">factor</span>(<span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">sprintf</span>(<span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"%d units"</span>, dec<span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">$</span>n), <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">sprintf</span>(<span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"%d units"</span>, <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">c</span>(<span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">1024</span>, <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">16384</span>)))</span>
<span id="cb7-2">dec<span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">$</span>verdict <span class="ot" style="color: #003B4F;
background-color: null;
font-style: inherit;">&lt;-</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">factor</span>(dec<span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">$</span>verdict, verdict_levels)</span>
<span id="cb7-3"><span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">ggplot</span>(dec, <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">aes</span>(shared, inter, <span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">colour =</span> verdict)) <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">+</span></span>
<span id="cb7-4">  <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">geom_abline</span>(<span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">slope =</span> <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">1</span>, <span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">intercept =</span> <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">0</span>, <span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">colour =</span> te_body, <span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">linewidth =</span> <span class="fl" style="color: #AD0000;
background-color: null;
font-style: inherit;">0.5</span>) <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">+</span></span>
<span id="cb7-5">  <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">geom_vline</span>(<span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">xintercept =</span> <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">0</span>, <span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">colour =</span> te_line, <span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">linewidth =</span> <span class="fl" style="color: #AD0000;
background-color: null;
font-style: inherit;">0.6</span>) <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">+</span></span>
<span id="cb7-6">  <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">geom_point</span>(<span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">size =</span> <span class="fl" style="color: #AD0000;
background-color: null;
font-style: inherit;">1.4</span>, <span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">alpha =</span> <span class="fl" style="color: #AD0000;
background-color: null;
font-style: inherit;">0.7</span>) <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">+</span></span>
<span id="cb7-7">  <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">facet_wrap</span>(<span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">~</span> n_lab, <span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">scales =</span> <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"free"</span>) <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">+</span></span>
<span id="cb7-8">  <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">scale_colour_manual</span>(<span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">values =</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">c</span>(<span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"enhance, nonlinear"</span> <span class="ot" style="color: #003B4F;
background-color: null;
font-style: inherit;">=</span> te_rust, <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"enhance, bi-"</span> <span class="ot" style="color: #003B4F;
background-color: null;
font-style: inherit;">=</span> te_gold),</span>
<span id="cb7-9">                      <span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">drop =</span> <span class="cn" style="color: #8f5902;
background-color: null;
font-style: inherit;">TRUE</span>, <span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">name =</span> <span class="cn" style="color: #8f5902;
background-color: null;
font-style: inherit;">NULL</span>) <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">+</span></span>
<span id="cb7-10">  <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">labs</span>(<span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">x =</span> <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"shared piece, q1 + q2 - q_add"</span>, <span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">y =</span> <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"interaction piece, q12 - q_add"</span>,</span>
<span id="cb7-11">       <span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">title =</span> <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"A positive term against a coin flip"</span>) <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">+</span></span>
<span id="cb7-12">  <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">theme_datasheet</span>() <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">+</span></span>
<span id="cb7-13">  <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">theme</span>(<span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">legend.position =</span> <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"bottom"</span>, <span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">plot.margin =</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">margin</span>(<span class="fl" style="color: #AD0000;
background-color: null;
font-style: inherit;">5.5</span>, <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">18</span>, <span class="fl" style="color: #AD0000;
background-color: null;
font-style: inherit;">5.5</span>, <span class="fl" style="color: #AD0000;
background-color: null;
font-style: inherit;">5.5</span>))</span></code></pre></div></div>
<div class="cell-output-display">
<div id="fig-decomp" class="quarto-float quarto-figure quarto-figure-center anchored" alt="Two scatter panels on warm off-white paper, for 1024 units on the left and 16384 units on the right, each plotting the interaction piece on the vertical axis against the shared piece on the horizontal axis for 400 datasets, with a diagonal line through the origin and a pale vertical line at zero. Red points, called a nonlinear enhancement, lie to the left of the diagonal and gold points, called a bivariate enhancement, to the right. In the left panel the interaction piece runs from about 0.004 to 0.023 while the shared piece spreads from about minus 0.02 to plus 0.035, and most points are red. In the right panel the interaction piece runs from about 0.0002 to 0.0016 and the shared piece from about minus 0.006 to plus 0.008; the diagonal is nearly vertical and the cloud is split roughly in half between red on the left and gold on the right.">
<figure class="quarto-float quarto-float-fig figure">
<div aria-describedby="fig-decomp-caption-0ceaefa1-69ba-4598-a22c-09a6ac19f8ca">
<img src="https://tidyecology.com/posts/geodetector-and-the-interaction-rule/index_files/figure-html/fig-decomp-1.png" class="img-fluid figure-img" alt="Two scatter panels on warm off-white paper, for 1024 units on the left and 16384 units on the right, each plotting the interaction piece on the vertical axis against the shared piece on the horizontal axis for 400 datasets, with a diagonal line through the origin and a pale vertical line at zero. Red points, called a nonlinear enhancement, lie to the left of the diagonal and gold points, called a bivariate enhancement, to the right. In the left panel the interaction piece runs from about 0.004 to 0.023 while the shared piece spreads from about minus 0.02 to plus 0.035, and most points are red. In the right panel the interaction piece runs from about 0.0002 to 0.0016 and the shared piece from about minus 0.006 to plus 0.008; the diagonal is nearly vertical and the cloud is split roughly in half between red on the left and gold on the right." width="672">
</div>
<figcaption class="quarto-float-caption-bottom quarto-float-caption quarto-float-fig" id="fig-decomp-caption-0ceaefa1-69ba-4598-a22c-09a6ac19f8ca">
Figure&nbsp;2: The interaction piece against the shared piece for each dataset at b = 0.5. Points above the diagonal are called a nonlinear enhancement, points below it a bivariate enhancement. The panels have different scales.
</figcaption>
</figure>
</div>
</div>
</div>
</section>
<section id="correlated-drivers-the-sign-decides" class="level2">
<h2 id="correlated-drivers-the-sign-decides-h" class="anchored" data-anchor-id="correlated-drivers-the-sign-decides">Correlated drivers: the sign decides</h2>
<p>Real drivers are rarely independent. Roads follow valleys, so elevation and distance to roads tend to be correlated, and temperature and elevation strongly so. Correlation between the drivers feeds the shared piece directly. When the two contributions to the response are positively correlated, the two classifications explain overlapping variance, so q1 + q2 exceeds q_add and the shared piece moves above zero. When the contributions are negatively correlated, each classification hides part of what the other explains, and the shared piece goes below zero. The run below keeps the additive model, b = 0.5 and 1024 units, and correlates the two normal drivers at r from 0 to 0.5, and at r = -0.5. With both effects positive, r = -0.5 is the case of elevation raising NDVI while distance to roads, positively correlated with elevation, lowers it: reversing the sign of one driver only reverses the order of its classes, which changes no q, and the chunk checks this on one dataset.</p>
<div class="cell">
<div class="code-copy-outer-scaffold"><div class="sourceCode cell-code" id="cb8" style="background: #f1f3f5;"><pre class="sourceCode r code-with-copy"><code class="sourceCode r"><span id="cb8-1">rho_set <span class="ot" style="color: #003B4F;
background-color: null;
font-style: inherit;">&lt;-</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">c</span>(<span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">0</span>, <span class="fl" style="color: #AD0000;
background-color: null;
font-style: inherit;">0.1</span>, <span class="fl" style="color: #AD0000;
background-color: null;
font-style: inherit;">0.2</span>, <span class="fl" style="color: #AD0000;
background-color: null;
font-style: inherit;">0.3</span>, <span class="fl" style="color: #AD0000;
background-color: null;
font-style: inherit;">0.5</span>, <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">-</span><span class="fl" style="color: #AD0000;
background-color: null;
font-style: inherit;">0.5</span>)</span>
<span id="cb8-2"><span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">set.seed</span>(<span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">4304</span>)</span>
<span id="cb8-3">cor_raw <span class="ot" style="color: #003B4F;
background-color: null;
font-style: inherit;">&lt;-</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">do.call</span>(rbind, <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">lapply</span>(rho_set, <span class="cf" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">function</span>(rho) {</span>
<span id="cb8-4">  out <span class="ot" style="color: #003B4F;
background-color: null;
font-style: inherit;">&lt;-</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">t</span>(<span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">replicate</span>(n_rep, {</span>
<span id="cb8-5">    x1 <span class="ot" style="color: #003B4F;
background-color: null;
font-style: inherit;">&lt;-</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">rnorm</span>(n_unit)</span>
<span id="cb8-6">    x2 <span class="ot" style="color: #003B4F;
background-color: null;
font-style: inherit;">&lt;-</span> rho <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">*</span> x1 <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">+</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">sqrt</span>(<span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">1</span> <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">-</span> rho<span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">^</span><span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">2</span>) <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">*</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">rnorm</span>(n_unit)</span>
<span id="cb8-7">    <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">gd_pieces</span>(<span class="fl" style="color: #AD0000;
background-color: null;
font-style: inherit;">0.5</span> <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">*</span> x1 <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">+</span> <span class="fl" style="color: #AD0000;
background-color: null;
font-style: inherit;">0.5</span> <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">*</span> x2 <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">+</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">rnorm</span>(n_unit), <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">disc_q</span>(x1, n_class), <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">disc_q</span>(x2, n_class))</span>
<span id="cb8-8">  }))</span>
<span id="cb8-9">  <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">data.frame</span>(<span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">rho =</span> rho, out)</span>
<span id="cb8-10">}))</span>
<span id="cb8-11">cor_raw<span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">$</span>verdict <span class="ot" style="color: #003B4F;
background-color: null;
font-style: inherit;">&lt;-</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">gd_verdict</span>(cor_raw<span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">$</span>q1, cor_raw<span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">$</span>q2, cor_raw<span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">$</span>q12)</span>
<span id="cb8-12">cor_raw<span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">$</span>enh <span class="ot" style="color: #003B4F;
background-color: null;
font-style: inherit;">&lt;-</span> cor_raw<span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">$</span>verdict <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">==</span> <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"enhance, nonlinear"</span></span>
<span id="cb8-13">cor_raw<span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">$</span>bi  <span class="ot" style="color: #003B4F;
background-color: null;
font-style: inherit;">&lt;-</span> cor_raw<span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">$</span>verdict <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">==</span> <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"enhance, bi-"</span></span>
<span id="cb8-14">cor_raw<span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">$</span>shared <span class="ot" style="color: #003B4F;
background-color: null;
font-style: inherit;">&lt;-</span> cor_raw<span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">$</span>q1 <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">+</span> cor_raw<span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">$</span>q2 <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">-</span> cor_raw<span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">$</span>q_add</span>
<span id="cb8-15">cor_raw<span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">$</span>f_rej <span class="ot" style="color: #003B4F;
background-color: null;
font-style: inherit;">&lt;-</span> cor_raw<span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">$</span>f_p <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">&lt;</span> <span class="fl" style="color: #AD0000;
background-color: null;
font-style: inherit;">0.05</span></span>
<span id="cb8-16">cor_raw<span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">$</span>shared_pos <span class="ot" style="color: #003B4F;
background-color: null;
font-style: inherit;">&lt;-</span> cor_raw<span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">$</span>shared <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">&gt;</span> <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">0</span></span>
<span id="cb8-17">cor_tab <span class="ot" style="color: #003B4F;
background-color: null;
font-style: inherit;">&lt;-</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">aggregate</span>(<span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">cbind</span>(enh, bi, shared, shared_pos, f_rej) <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">~</span> rho, cor_raw, mean)</span>
<span id="cb8-18"><span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">stopifnot</span>(<span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">all</span>(cor_raw<span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">$</span>bi[cor_raw<span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">$</span>rho <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">&gt;=</span> <span class="fl" style="color: #AD0000;
background-color: null;
font-style: inherit;">0.2</span>]), <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">all</span>(cor_raw<span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">$</span>shared_pos[cor_raw<span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">$</span>rho <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">&gt;=</span> <span class="fl" style="color: #AD0000;
background-color: null;
font-style: inherit;">0.2</span>]))</span>
<span id="cb8-19">ct <span class="ot" style="color: #003B4F;
background-color: null;
font-style: inherit;">&lt;-</span> <span class="cf" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">function</span>(rr, v) cor_tab[cor_tab<span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">$</span>rho <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">==</span> rr, v]</span>
<span id="cb8-20"><span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">stopifnot</span>(<span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">all</span>(cor_raw<span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">$</span>enh[cor_raw<span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">$</span>rho <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">==</span> <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">-</span><span class="fl" style="color: #AD0000;
background-color: null;
font-style: inherit;">0.5</span>]), <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">all</span>(cor_raw<span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">$</span>shared[cor_raw<span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">$</span>rho <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">==</span> <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">-</span><span class="fl" style="color: #AD0000;
background-color: null;
font-style: inherit;">0.5</span>] <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">&lt;</span> <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">0</span>))</span>
<span id="cb8-21"></span>
<span id="cb8-22"><span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">set.seed</span>(<span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">4313</span>)</span>
<span id="cb8-23">x1_flip <span class="ot" style="color: #003B4F;
background-color: null;
font-style: inherit;">&lt;-</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">rnorm</span>(n_unit)</span>
<span id="cb8-24">x2_flip <span class="ot" style="color: #003B4F;
background-color: null;
font-style: inherit;">&lt;-</span> <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">-</span><span class="fl" style="color: #AD0000;
background-color: null;
font-style: inherit;">0.5</span> <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">*</span> x1_flip <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">+</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">sqrt</span>(<span class="fl" style="color: #AD0000;
background-color: null;
font-style: inherit;">0.75</span>) <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">*</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">rnorm</span>(n_unit)</span>
<span id="cb8-25">y_flip  <span class="ot" style="color: #003B4F;
background-color: null;
font-style: inherit;">&lt;-</span> <span class="fl" style="color: #AD0000;
background-color: null;
font-style: inherit;">0.5</span> <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">*</span> x1_flip <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">+</span> <span class="fl" style="color: #AD0000;
background-color: null;
font-style: inherit;">0.5</span> <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">*</span> x2_flip <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">+</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">rnorm</span>(n_unit)</span>
<span id="cb8-26">flip_a <span class="ot" style="color: #003B4F;
background-color: null;
font-style: inherit;">&lt;-</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">gd_pieces</span>(y_flip, <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">disc_q</span>(x1_flip, n_class), <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">disc_q</span>(x2_flip, n_class))</span>
<span id="cb8-27">flip_b <span class="ot" style="color: #003B4F;
background-color: null;
font-style: inherit;">&lt;-</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">gd_pieces</span>(y_flip, <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">disc_q</span>(x1_flip, n_class), <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">disc_q</span>(<span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">-</span>x2_flip, n_class))</span>
<span id="cb8-28"><span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">stopifnot</span>(<span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">max</span>(<span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">abs</span>(flip_a[<span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">1</span><span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">:</span><span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">4</span>] <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">-</span> flip_b[<span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">1</span><span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">:</span><span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">4</span>])) <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">&lt;</span> <span class="fl" style="color: #AD0000;
background-color: null;
font-style: inherit;">1e-12</span>)</span>
<span id="cb8-29"></span>
<span id="cb8-30">spline_f <span class="ot" style="color: #003B4F;
background-color: null;
font-style: inherit;">&lt;-</span> <span class="cf" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">function</span>(y, x1, x2) {</span>
<span id="cb8-31">  b1 <span class="ot" style="color: #003B4F;
background-color: null;
font-style: inherit;">&lt;-</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">ns</span>(x1, <span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">df =</span> <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">4</span>)</span>
<span id="cb8-32">  b2 <span class="ot" style="color: #003B4F;
background-color: null;
font-style: inherit;">&lt;-</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">ns</span>(x2, <span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">df =</span> <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">4</span>)</span>
<span id="cb8-33">  x_a <span class="ot" style="color: #003B4F;
background-color: null;
font-style: inherit;">&lt;-</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">cbind</span>(<span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">1</span>, b1, b2)</span>
<span id="cb8-34">  x_i <span class="ot" style="color: #003B4F;
background-color: null;
font-style: inherit;">&lt;-</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">cbind</span>(x_a, <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">do.call</span>(cbind, <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">lapply</span>(<span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">1</span><span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">:</span><span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">4</span>, <span class="cf" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">function</span>(j) b1[, j] <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">*</span> b2)))</span>
<span id="cb8-35">  rss_a <span class="ot" style="color: #003B4F;
background-color: null;
font-style: inherit;">&lt;-</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">sum</span>(<span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">.lm.fit</span>(x_a, y)<span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">$</span>residuals<span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">^</span><span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">2</span>)</span>
<span id="cb8-36">  rss_i <span class="ot" style="color: #003B4F;
background-color: null;
font-style: inherit;">&lt;-</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">sum</span>(<span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">.lm.fit</span>(x_i, y)<span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">$</span>residuals<span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">^</span><span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">2</span>)</span>
<span id="cb8-37">  df_i <span class="ot" style="color: #003B4F;
background-color: null;
font-style: inherit;">&lt;-</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">ncol</span>(x_i) <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">-</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">ncol</span>(x_a)</span>
<span id="cb8-38">  <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">pf</span>(((rss_a <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">-</span> rss_i) <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">/</span> df_i) <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">/</span> (rss_i <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">/</span> (<span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">length</span>(y) <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">-</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">ncol</span>(x_i))), df_i,</span>
<span id="cb8-39">     <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">length</span>(y) <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">-</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">ncol</span>(x_i), <span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">lower.tail =</span> <span class="cn" style="color: #8f5902;
background-color: null;
font-style: inherit;">FALSE</span>)</span>
<span id="cb8-40">}</span>
<span id="cb8-41"><span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">set.seed</span>(<span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">4305</span>)</span>
<span id="cb8-42">cls_vs_spline <span class="ot" style="color: #003B4F;
background-color: null;
font-style: inherit;">&lt;-</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">do.call</span>(rbind, <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">lapply</span>(<span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">c</span>(<span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">1024</span>, <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">4096</span>), <span class="cf" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">function</span>(nn) {</span>
<span id="cb8-43">  out <span class="ot" style="color: #003B4F;
background-color: null;
font-style: inherit;">&lt;-</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">t</span>(<span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">replicate</span>(n_rep, {</span>
<span id="cb8-44">    x1 <span class="ot" style="color: #003B4F;
background-color: null;
font-style: inherit;">&lt;-</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">rnorm</span>(nn)</span>
<span id="cb8-45">    x2 <span class="ot" style="color: #003B4F;
background-color: null;
font-style: inherit;">&lt;-</span> <span class="fl" style="color: #AD0000;
background-color: null;
font-style: inherit;">0.5</span> <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">*</span> x1 <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">+</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">sqrt</span>(<span class="fl" style="color: #AD0000;
background-color: null;
font-style: inherit;">0.75</span>) <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">*</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">rnorm</span>(nn)</span>
<span id="cb8-46">    y <span class="ot" style="color: #003B4F;
background-color: null;
font-style: inherit;">&lt;-</span> <span class="fl" style="color: #AD0000;
background-color: null;
font-style: inherit;">0.5</span> <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">*</span> x1 <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">+</span> <span class="fl" style="color: #AD0000;
background-color: null;
font-style: inherit;">0.5</span> <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">*</span> x2 <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">+</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">rnorm</span>(nn)</span>
<span id="cb8-47">    <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">c</span>(<span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">cls =</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">gd_pieces</span>(y, <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">disc_q</span>(x1, n_class), <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">disc_q</span>(x2, n_class))[[<span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"f_p"</span>]] <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">&lt;</span> <span class="fl" style="color: #AD0000;
background-color: null;
font-style: inherit;">0.05</span>,</span>
<span id="cb8-48">      <span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">spl =</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">spline_f</span>(y, x1, x2) <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">&lt;</span> <span class="fl" style="color: #AD0000;
background-color: null;
font-style: inherit;">0.05</span>)</span>
<span id="cb8-49">  }))</span>
<span id="cb8-50">  <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">data.frame</span>(<span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">n =</span> nn, <span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">cls =</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">mean</span>(out[, <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"cls"</span>]), <span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">spl =</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">mean</span>(out[, <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"spl"</span>]))</span>
<span id="cb8-51">}))</span>
<span id="cb8-52"></span>
<span id="cb8-53"><span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">set.seed</span>(<span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">4312</span>)</span>
<span id="cb8-54">cls_big <span class="ot" style="color: #003B4F;
background-color: null;
font-style: inherit;">&lt;-</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">do.call</span>(rbind, <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">lapply</span>(<span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">c</span>(<span class="fl" style="color: #AD0000;
background-color: null;
font-style: inherit;">0.1</span>, <span class="fl" style="color: #AD0000;
background-color: null;
font-style: inherit;">0.2</span>), <span class="cf" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">function</span>(rho) {</span>
<span id="cb8-55">  rej <span class="ot" style="color: #003B4F;
background-color: null;
font-style: inherit;">&lt;-</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">replicate</span>(n_rep, {</span>
<span id="cb8-56">    x1 <span class="ot" style="color: #003B4F;
background-color: null;
font-style: inherit;">&lt;-</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">rnorm</span>(<span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">16384</span>)</span>
<span id="cb8-57">    x2 <span class="ot" style="color: #003B4F;
background-color: null;
font-style: inherit;">&lt;-</span> rho <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">*</span> x1 <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">+</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">sqrt</span>(<span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">1</span> <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">-</span> rho<span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">^</span><span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">2</span>) <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">*</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">rnorm</span>(<span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">16384</span>)</span>
<span id="cb8-58">    <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">gd_pieces</span>(<span class="fl" style="color: #AD0000;
background-color: null;
font-style: inherit;">0.5</span> <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">*</span> x1 <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">+</span> <span class="fl" style="color: #AD0000;
background-color: null;
font-style: inherit;">0.5</span> <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">*</span> x2 <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">+</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">rnorm</span>(<span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">16384</span>), <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">disc_q</span>(x1, n_class), <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">disc_q</span>(x2, n_class))[[<span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"f_p"</span>]] <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">&lt;</span> <span class="fl" style="color: #AD0000;
background-color: null;
font-style: inherit;">0.05</span></span>
<span id="cb8-59">  })</span>
<span id="cb8-60">  <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">data.frame</span>(<span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">rho =</span> rho, <span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">f_rej =</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">mean</span>(rej))</span>
<span id="cb8-61">}))</span></code></pre></div></div>
</div>
<p>At r = 0.1 the rule already calls 5.7 per cent of datasets a nonlinear enhancement and 94.3 per cent a bivariate one, against 82.8 and 17.2 per cent at r = 0 on this run’s own draws; the mean shared piece has grown from +0.0012 to 0.0290. The shared piece is positive in 52.5 per cent of datasets at r = 0 and in 100.0 per cent at r = 0.1. From r = 0.2 upwards every dataset is a bivariate enhancement, and at r = 0.5 the shared piece averages 0.182. At r = -0.5 it averages -0.074 and is negative in every dataset, and the rule calls 100.0 per cent of them a nonlinear enhancement. Same process, same absence of interaction: the verdict follows the sign of the correlation between the two contributions, not any interaction.</p>
<p>The interaction F test on classes has a problem of its own here. When the drivers are correlated, the mean of x1 inside a class of x1 depends on which class of x2 the unit is in, so the class means of an additive response are no longer additive in the two classifications. The classes carry a real interaction that the process does not have. It is a property of the class means, not of the sample, so the F test finds it more often as N grows: with r = 0.5, in the draws used for the spline comparison below, it rejects in 9.0 per cent of datasets at 1024 units and 31.0 per cent at 4096. At 1024 units and r from 0 to 0.5 its rejection rates in the main run are 5.2, 5.2, 5.7, 6.2 and 8.3 per cent. At 16384 units a correlation of 0.1 gives 6.0 per cent and a correlation of 0.2 gives 12.8 per cent, each from 400 datasets. A test on the continuous drivers does not have this problem. Comparing an additive model with a natural spline of four degrees of freedom in each driver against the same model plus their tensor-product terms, the interaction F test rejects in 3.5 and 4.0 per cent of the same kind of datasets. Once the drivers are correlated, cutting them into classes costs the interaction question its meaning, and the model should use the drivers as measured.</p>
</section>
<section id="on-a-raster-the-units-are-not-independent" class="level2">
<h2 id="on-a-raster-the-units-are-not-independent-h" class="anchored" data-anchor-id="on-a-raster-the-units-are-not-independent">On a raster, the units are not independent</h2>
<p>Everything so far treated the units as independent draws. A raster is not that: neighbouring cells share their elevation, their NDVI and their distance to a road. The grids below are 32 by 32 cells, 1024 units as before, and each layer (the two drivers and the error) is Gaussian noise smoothed with a Gaussian kernel whose standard deviation is r cells, then standardised. The fields are generated on a larger wrapped grid and a 32 by 32 window is cut out, so the window does not wrap at its edges, as a real map does not. Two ranges are used: a kernel standard deviation of 2 cells and of 5 cells.</p>
<div class="cell">
<div class="code-copy-outer-scaffold"><div class="sourceCode cell-code" id="cb9" style="background: #f1f3f5;"><pre class="sourceCode r code-with-copy"><code class="sourceCode r"><span id="cb9-1">n_side <span class="ot" style="color: #003B4F;
background-color: null;
font-style: inherit;">&lt;-</span> <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">32</span></span>
<span id="cb9-2">r_set  <span class="ot" style="color: #003B4F;
background-color: null;
font-style: inherit;">&lt;-</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">c</span>(<span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">2</span>, <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">5</span>)</span>
<span id="cb9-3">smooth_layer <span class="ot" style="color: #003B4F;
background-color: null;
font-style: inherit;">&lt;-</span> <span class="cf" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">function</span>(n, r, <span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">wrap =</span> <span class="cn" style="color: #8f5902;
background-color: null;
font-style: inherit;">FALSE</span>) {</span>
<span id="cb9-4">  m <span class="ot" style="color: #003B4F;
background-color: null;
font-style: inherit;">&lt;-</span> <span class="cf" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">if</span> (wrap) n <span class="cf" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">else</span> n <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">+</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">ceiling</span>(<span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">4</span> <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">*</span> r)</span>
<span id="cb9-5">  w <span class="ot" style="color: #003B4F;
background-color: null;
font-style: inherit;">&lt;-</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">matrix</span>(<span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">rnorm</span>(m <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">*</span> m), m, m)</span>
<span id="cb9-6">  d_wrap <span class="ot" style="color: #003B4F;
background-color: null;
font-style: inherit;">&lt;-</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">pmin</span>(<span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">0</span><span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">:</span>(m <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">-</span> <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">1</span>), m <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">-</span> <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">0</span><span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">:</span>(m <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">-</span> <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">1</span>))</span>
<span id="cb9-7">  k_one <span class="ot" style="color: #003B4F;
background-color: null;
font-style: inherit;">&lt;-</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">exp</span>(<span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">-</span>d_wrap<span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">^</span><span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">2</span> <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">/</span> (<span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">2</span> <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">*</span> r<span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">^</span><span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">2</span>))</span>
<span id="cb9-8">  z <span class="ot" style="color: #003B4F;
background-color: null;
font-style: inherit;">&lt;-</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">Re</span>(<span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">fft</span>(<span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">fft</span>(w) <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">*</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">fft</span>(<span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">outer</span>(k_one, k_one)), <span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">inverse =</span> <span class="cn" style="color: #8f5902;
background-color: null;
font-style: inherit;">TRUE</span>))[<span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">1</span><span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">:</span>n, <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">1</span><span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">:</span>n]</span>
<span id="cb9-9">  <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">as.vector</span>((z <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">-</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">mean</span>(z)) <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">/</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">sd</span>(<span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">as.vector</span>(z)))</span>
<span id="cb9-10">}</span>
<span id="cb9-11">moran_rook <span class="ot" style="color: #003B4F;
background-color: null;
font-style: inherit;">&lt;-</span> <span class="cf" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">function</span>(v, n) {</span>
<span id="cb9-12">  z <span class="ot" style="color: #003B4F;
background-color: null;
font-style: inherit;">&lt;-</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">matrix</span>(v <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">-</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">mean</span>(v), n, n)</span>
<span id="cb9-13">  cross <span class="ot" style="color: #003B4F;
background-color: null;
font-style: inherit;">&lt;-</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">sum</span>(z[<span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">-</span><span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">1</span>, ] <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">*</span> z[<span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">-</span>n, ]) <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">+</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">sum</span>(z[, <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">-</span><span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">1</span>] <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">*</span> z[, <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">-</span>n])</span>
<span id="cb9-14">  (n <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">*</span> n <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">/</span> (<span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">4</span> <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">*</span> n <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">*</span> (n <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">-</span> <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">1</span>))) <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">*</span> <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">2</span> <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">*</span> cross <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">/</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">sum</span>(z<span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">^</span><span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">2</span>)</span>
<span id="cb9-15">}</span>
<span id="cb9-16"><span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">set.seed</span>(<span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">4306</span>)</span>
<span id="cb9-17">map_df <span class="ot" style="color: #003B4F;
background-color: null;
font-style: inherit;">&lt;-</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">do.call</span>(rbind, <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">lapply</span>(r_set, <span class="cf" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">function</span>(r) {</span>
<span id="cb9-18">  x1 <span class="ot" style="color: #003B4F;
background-color: null;
font-style: inherit;">&lt;-</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">smooth_layer</span>(n_side, r)</span>
<span id="cb9-19">  x2 <span class="ot" style="color: #003B4F;
background-color: null;
font-style: inherit;">&lt;-</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">smooth_layer</span>(n_side, r)</span>
<span id="cb9-20">  e  <span class="ot" style="color: #003B4F;
background-color: null;
font-style: inherit;">&lt;-</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">smooth_layer</span>(n_side, r)</span>
<span id="cb9-21">  y  <span class="ot" style="color: #003B4F;
background-color: null;
font-style: inherit;">&lt;-</span> <span class="fl" style="color: #AD0000;
background-color: null;
font-style: inherit;">0.5</span> <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">*</span> x1 <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">+</span> <span class="fl" style="color: #AD0000;
background-color: null;
font-style: inherit;">0.5</span> <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">*</span> x2 <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">+</span> e</span>
<span id="cb9-22">  <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">data.frame</span>(<span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">r =</span> r, <span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">row_i =</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">rep</span>(<span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">seq_len</span>(n_side), n_side), <span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">col_i =</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">rep</span>(<span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">seq_len</span>(n_side), <span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">each =</span> n_side),</span>
<span id="cb9-23">             <span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">layer =</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">rep</span>(<span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">c</span>(<span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"driver x1"</span>, <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"driver x2"</span>, <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"response y"</span>), <span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">each =</span> n_side<span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">^</span><span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">2</span>),</span>
<span id="cb9-24">             <span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">value =</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">c</span>(x1, x2, <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">as.vector</span>(<span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">scale</span>(y))))</span>
<span id="cb9-25">}))</span></code></pre></div></div>
</div>
<div class="cell">
<div class="code-copy-outer-scaffold"><div class="sourceCode cell-code" id="cb10" style="background: #f1f3f5;"><pre class="sourceCode r code-with-copy"><code class="sourceCode r"><span id="cb10-1">map_df<span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">$</span>r_lab <span class="ot" style="color: #003B4F;
background-color: null;
font-style: inherit;">&lt;-</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">factor</span>(<span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">sprintf</span>(<span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"kernel SD %d cells"</span>, map_df<span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">$</span>r), <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">sprintf</span>(<span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"kernel SD %d cells"</span>, r_set))</span>
<span id="cb10-2"><span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">ggplot</span>(map_df, <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">aes</span>(col_i, row_i, <span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">fill =</span> value)) <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">+</span></span>
<span id="cb10-3">  <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">geom_raster</span>() <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">+</span></span>
<span id="cb10-4">  <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">facet_grid</span>(r_lab <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">~</span> layer) <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">+</span></span>
<span id="cb10-5">  <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">scale_fill_gradient2</span>(<span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">low =</span> te_forest, <span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">mid =</span> te_paper, <span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">high =</span> te_rust, <span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">midpoint =</span> <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">0</span>,</span>
<span id="cb10-6">                       <span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">name =</span> <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"standardised value"</span>) <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">+</span></span>
<span id="cb10-7">  <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">coord_equal</span>(<span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">expand =</span> <span class="cn" style="color: #8f5902;
background-color: null;
font-style: inherit;">FALSE</span>) <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">+</span></span>
<span id="cb10-8">  <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">labs</span>(<span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">x =</span> <span class="cn" style="color: #8f5902;
background-color: null;
font-style: inherit;">NULL</span>, <span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">y =</span> <span class="cn" style="color: #8f5902;
background-color: null;
font-style: inherit;">NULL</span>, <span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">title =</span> <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"Two ranges of spatial structure"</span>) <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">+</span></span>
<span id="cb10-9">  <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">theme_datasheet</span>() <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">+</span></span>
<span id="cb10-10">  <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">theme</span>(<span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">axis.text =</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">element_blank</span>(), <span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">panel.grid.major =</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">element_blank</span>(),</span>
<span id="cb10-11">        <span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">legend.position =</span> <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"bottom"</span>)</span></code></pre></div></div>
<div class="cell-output-display">
<div id="fig-grid" class="quarto-float quarto-figure quarto-figure-center anchored" alt="A grid of six square raster maps on warm off-white paper, three columns for driver x1, driver x2 and response y, and two rows for a smoothing kernel standard deviation of 2 cells (top) and 5 cells (bottom). Each map is shaded from dark green for low standardised values through pale off-white near zero to red for high values, with a colour bar labelled from minus 2 to 2 at the bottom. The top row shows many small blobs of a few cells across; the bottom row shows a few broad patches that span a large part of each map, such as a green band across the lower middle of x1 and of y.">
<figure class="quarto-float quarto-float-fig figure">
<div aria-describedby="fig-grid-caption-0ceaefa1-69ba-4598-a22c-09a6ac19f8ca">
<img src="https://tidyecology.com/posts/geodetector-and-the-interaction-rule/index_files/figure-html/fig-grid-1.png" class="img-fluid figure-img" alt="A grid of six square raster maps on warm off-white paper, three columns for driver x1, driver x2 and response y, and two rows for a smoothing kernel standard deviation of 2 cells (top) and 5 cells (bottom). Each map is shaded from dark green for low standardised values through pale off-white near zero to red for high values, with a colour bar labelled from minus 2 to 2 at the bottom. The top row shows many small blobs of a few cells across; the bottom row shows a few broad patches that span a large part of each map, such as a green band across the lower middle of x1 and of y." width="672">
</div>
<figcaption class="quarto-float-caption-bottom quarto-float-caption quarto-float-fig" id="fig-grid-caption-0ceaefa1-69ba-4598-a22c-09a6ac19f8ca">
Figure&nbsp;3: One simulated raster at each range: two independent drivers and an additive response, each standardised. Top row kernel standard deviation 2 cells, bottom row 5 cells.
</figcaption>
</figure>
</div>
</div>
</div>
<p>Three scenarios run on these grids. In the null scenario the response is the error layer alone and has nothing to do with either driver. In the additive scenario it is 0.5 x1 + 0.5 x2 + e, as before. In the product scenario a real interaction, 0.5 x1 x2, is added, so that there is something for a test to find.</p>
<p>Two spatial versions of the interaction test are tried, both built on the toroidal shift that Lotwick and Silverman (1982) introduced for point patterns and that the point-pattern post uses. The observed statistic is the interaction F of the two-way analysis of variance on the classes; only its reference distribution changes. The driver shift slides the x2 layer, with its classes, over the grid by a random offset, wrapping at the edges, and recomputes F against the unmoved y and x1; this keeps each layer’s own spatial structure and breaks their alignment. The residual shift fits the additive two-way model, slides the map of its residuals instead, adds the shifted residuals back to the fitted values and recomputes F. Both use 99 shifts and reject when the observed F is among the five largest of the 100 values. Neither was run before this post was planned, and neither was adjusted after the results came in.</p>
<div class="cell">
<div class="code-copy-outer-scaffold"><div class="sourceCode cell-code" id="cb11" style="background: #f1f3f5;"><pre class="sourceCode r code-with-copy"><code class="sourceCode r"><span id="cb11-1">f_inter <span class="ot" style="color: #003B4F;
background-color: null;
font-style: inherit;">&lt;-</span> <span class="cf" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">function</span>(ymat, g1, g2) {</span>
<span id="cb11-2">  g12 <span class="ot" style="color: #003B4F;
background-color: null;
font-style: inherit;">&lt;-</span> (g1 <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">-</span> <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">1</span>L) <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">*</span> n_class <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">+</span> g2</span>
<span id="cb11-3">  x_add <span class="ot" style="color: #003B4F;
background-color: null;
font-style: inherit;">&lt;-</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">cbind</span>(<span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">1</span>, <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">outer</span>(g1, <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">2</span><span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">:</span>n_class, <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"=="</span>) <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">+</span> <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">0</span>, <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">outer</span>(g2, <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">2</span><span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">:</span>n_class, <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"=="</span>) <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">+</span> <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">0</span>)</span>
<span id="cb11-4">  sse_add <span class="ot" style="color: #003B4F;
background-color: null;
font-style: inherit;">&lt;-</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">colSums</span>(<span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">qr.resid</span>(<span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">qr</span>(x_add), ymat)<span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">^</span><span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">2</span>)</span>
<span id="cb11-5">  n_g <span class="ot" style="color: #003B4F;
background-color: null;
font-style: inherit;">&lt;-</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">tabulate</span>(g12)</span>
<span id="cb11-6">  n_g <span class="ot" style="color: #003B4F;
background-color: null;
font-style: inherit;">&lt;-</span> n_g[n_g <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">&gt;</span> <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">0</span>]</span>
<span id="cb11-7">  sse_cell <span class="ot" style="color: #003B4F;
background-color: null;
font-style: inherit;">&lt;-</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">colSums</span>(ymat<span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">^</span><span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">2</span>) <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">-</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">colSums</span>(<span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">rowsum</span>(ymat, g12, <span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">reorder =</span> <span class="cn" style="color: #8f5902;
background-color: null;
font-style: inherit;">TRUE</span>)<span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">^</span><span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">2</span> <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">/</span> n_g)</span>
<span id="cb11-8">  df_ab <span class="ot" style="color: #003B4F;
background-color: null;
font-style: inherit;">&lt;-</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">length</span>(n_g) <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">-</span> <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">2</span> <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">*</span> n_class <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">+</span> <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">1</span></span>
<span id="cb11-9">  df_e  <span class="ot" style="color: #003B4F;
background-color: null;
font-style: inherit;">&lt;-</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">nrow</span>(ymat) <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">-</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">length</span>(n_g)</span>
<span id="cb11-10">  ((sse_add <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">-</span> sse_cell) <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">/</span> df_ab) <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">/</span> (sse_cell <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">/</span> df_e)</span>
<span id="cb11-11">}</span>
<span id="cb11-12">shift_index <span class="ot" style="color: #003B4F;
background-color: null;
font-style: inherit;">&lt;-</span> <span class="cf" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">function</span>(n, dx, dy) {</span>
<span id="cb11-13">  rr <span class="ot" style="color: #003B4F;
background-color: null;
font-style: inherit;">&lt;-</span> ((<span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">0</span><span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">:</span>(n <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">-</span> <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">1</span>) <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">+</span> dx) <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">%%</span> n) <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">+</span> <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">1</span></span>
<span id="cb11-14">  cc <span class="ot" style="color: #003B4F;
background-color: null;
font-style: inherit;">&lt;-</span> ((<span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">0</span><span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">:</span>(n <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">-</span> <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">1</span>) <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">+</span> dy) <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">%%</span> n) <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">+</span> <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">1</span></span>
<span id="cb11-15">  <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">as.vector</span>(<span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">outer</span>(rr, (cc <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">-</span> <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">1</span>) <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">*</span> n, <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"+"</span>))</span>
<span id="cb11-16">}</span>
<span id="cb11-17">n_shift <span class="ot" style="color: #003B4F;
background-color: null;
font-style: inherit;">&lt;-</span> <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">99</span></span>
<span id="cb11-18">one_grid <span class="ot" style="color: #003B4F;
background-color: null;
font-style: inherit;">&lt;-</span> <span class="cf" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">function</span>(scn, r, <span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">wrap =</span> <span class="cn" style="color: #8f5902;
background-color: null;
font-style: inherit;">FALSE</span>) {</span>
<span id="cb11-19">  x1 <span class="ot" style="color: #003B4F;
background-color: null;
font-style: inherit;">&lt;-</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">smooth_layer</span>(n_side, r, wrap)</span>
<span id="cb11-20">  x2 <span class="ot" style="color: #003B4F;
background-color: null;
font-style: inherit;">&lt;-</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">smooth_layer</span>(n_side, r, wrap)</span>
<span id="cb11-21">  e  <span class="ot" style="color: #003B4F;
background-color: null;
font-style: inherit;">&lt;-</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">smooth_layer</span>(n_side, r, wrap)</span>
<span id="cb11-22">  y <span class="ot" style="color: #003B4F;
background-color: null;
font-style: inherit;">&lt;-</span> <span class="cf" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">switch</span>(scn, <span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">null =</span> e, <span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">additive =</span> <span class="fl" style="color: #AD0000;
background-color: null;
font-style: inherit;">0.5</span> <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">*</span> x1 <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">+</span> <span class="fl" style="color: #AD0000;
background-color: null;
font-style: inherit;">0.5</span> <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">*</span> x2 <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">+</span> e,</span>
<span id="cb11-23">              <span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">product =</span> <span class="fl" style="color: #AD0000;
background-color: null;
font-style: inherit;">0.5</span> <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">*</span> x1 <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">+</span> <span class="fl" style="color: #AD0000;
background-color: null;
font-style: inherit;">0.5</span> <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">*</span> x2 <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">+</span> <span class="fl" style="color: #AD0000;
background-color: null;
font-style: inherit;">0.5</span> <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">*</span> x1 <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">*</span> x2 <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">+</span> e)</span>
<span id="cb11-24">  g1 <span class="ot" style="color: #003B4F;
background-color: null;
font-style: inherit;">&lt;-</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">disc_q</span>(x1, n_class)</span>
<span id="cb11-25">  g2 <span class="ot" style="color: #003B4F;
background-color: null;
font-style: inherit;">&lt;-</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">disc_q</span>(x2, n_class)</span>
<span id="cb11-26">  pc <span class="ot" style="color: #003B4F;
background-color: null;
font-style: inherit;">&lt;-</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">gd_pieces</span>(y, g1, g2)</span>
<span id="cb11-27">  f_obs <span class="ot" style="color: #003B4F;
background-color: null;
font-style: inherit;">&lt;-</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">f_inter</span>(<span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">matrix</span>(y), g1, g2)</span>
<span id="cb11-28">  s_id <span class="ot" style="color: #003B4F;
background-color: null;
font-style: inherit;">&lt;-</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">sample.int</span>(n_side<span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">^</span><span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">2</span> <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">-</span> <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">1</span>, n_shift)</span>
<span id="cb11-29">  dx <span class="ot" style="color: #003B4F;
background-color: null;
font-style: inherit;">&lt;-</span> s_id <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">%/%</span> n_side</span>
<span id="cb11-30">  dy <span class="ot" style="color: #003B4F;
background-color: null;
font-style: inherit;">&lt;-</span> s_id <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">%%</span> n_side</span>
<span id="cb11-31">  f_drv <span class="ot" style="color: #003B4F;
background-color: null;
font-style: inherit;">&lt;-</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">vapply</span>(<span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">seq_len</span>(n_shift), <span class="cf" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">function</span>(i)</span>
<span id="cb11-32">    <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">f_inter</span>(<span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">matrix</span>(y), g1, g2[<span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">shift_index</span>(n_side, dx[i], dy[i])]), <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">0</span>)</span>
<span id="cb11-33">  x_add <span class="ot" style="color: #003B4F;
background-color: null;
font-style: inherit;">&lt;-</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">cbind</span>(<span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">1</span>, <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">outer</span>(g1, <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">2</span><span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">:</span>n_class, <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"=="</span>) <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">+</span> <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">0</span>, <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">outer</span>(g2, <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">2</span><span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">:</span>n_class, <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"=="</span>) <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">+</span> <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">0</span>)</span>
<span id="cb11-34">  fit_add <span class="ot" style="color: #003B4F;
background-color: null;
font-style: inherit;">&lt;-</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">qr.fitted</span>(<span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">qr</span>(x_add), y)</span>
<span id="cb11-35">  res_add <span class="ot" style="color: #003B4F;
background-color: null;
font-style: inherit;">&lt;-</span> y <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">-</span> fit_add</span>
<span id="cb11-36">  y_star <span class="ot" style="color: #003B4F;
background-color: null;
font-style: inherit;">&lt;-</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">vapply</span>(<span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">seq_len</span>(n_shift), <span class="cf" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">function</span>(i)</span>
<span id="cb11-37">    fit_add <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">+</span> res_add[<span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">shift_index</span>(n_side, dx[i], dy[i])], <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">numeric</span>(n_side<span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">^</span><span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">2</span>))</span>
<span id="cb11-38">  f_res <span class="ot" style="color: #003B4F;
background-color: null;
font-style: inherit;">&lt;-</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">f_inter</span>(y_star, g1, g2)</span>
<span id="cb11-39">  p_one <span class="ot" style="color: #003B4F;
background-color: null;
font-style: inherit;">&lt;-</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">pf</span>((pc[[<span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"q1"</span>]] <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">/</span> (n_class <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">-</span> <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">1</span>)) <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">/</span> ((<span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">1</span> <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">-</span> pc[[<span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"q1"</span>]]) <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">/</span> (n_side<span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">^</span><span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">2</span> <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">-</span> n_class)),</span>
<span id="cb11-40">              n_class <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">-</span> <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">1</span>, n_side<span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">^</span><span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">2</span> <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">-</span> n_class, <span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">lower.tail =</span> <span class="cn" style="color: #8f5902;
background-color: null;
font-style: inherit;">FALSE</span>)</span>
<span id="cb11-41">  <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">c</span>(pc, <span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">moran =</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">moran_rook</span>(y, n_side), <span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">q1_rej =</span> p_one <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">&lt;</span> <span class="fl" style="color: #AD0000;
background-color: null;
font-style: inherit;">0.05</span>,</span>
<span id="cb11-42">    <span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">drv_rej =</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">sum</span>(f_drv <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">&gt;=</span> f_obs) <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">+</span> <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">1</span> <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">&lt;=</span> <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">5</span>, <span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">res_rej =</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">sum</span>(f_res <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">&gt;=</span> f_obs) <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">+</span> <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">1</span> <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">&lt;=</span> <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">5</span>)</span>
<span id="cb11-43">}</span>
<span id="cb11-44">n_grid_rep <span class="ot" style="color: #003B4F;
background-color: null;
font-style: inherit;">&lt;-</span> <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">200</span></span>
<span id="cb11-45">scn_set <span class="ot" style="color: #003B4F;
background-color: null;
font-style: inherit;">&lt;-</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">c</span>(<span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"null"</span>, <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"additive"</span>, <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"product"</span>)</span>
<span id="cb11-46"><span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">set.seed</span>(<span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">4307</span>)</span>
<span id="cb11-47">grid_raw <span class="ot" style="color: #003B4F;
background-color: null;
font-style: inherit;">&lt;-</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">do.call</span>(rbind, <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">lapply</span>(r_set, <span class="cf" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">function</span>(r) <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">do.call</span>(rbind, <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">lapply</span>(scn_set, <span class="cf" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">function</span>(scn)</span>
<span id="cb11-48">  <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">data.frame</span>(<span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">r =</span> r, <span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">scn =</span> scn, <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">t</span>(<span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">replicate</span>(n_grid_rep, <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">one_grid</span>(scn, r))))))))</span>
<span id="cb11-49">grid_raw<span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">$</span>verdict <span class="ot" style="color: #003B4F;
background-color: null;
font-style: inherit;">&lt;-</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">gd_verdict</span>(grid_raw<span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">$</span>q1, grid_raw<span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">$</span>q2, grid_raw<span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">$</span>q12)</span>
<span id="cb11-50">grid_raw<span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">$</span>enh <span class="ot" style="color: #003B4F;
background-color: null;
font-style: inherit;">&lt;-</span> grid_raw<span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">$</span>verdict <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">==</span> <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"enhance, nonlinear"</span></span>
<span id="cb11-51">grid_raw<span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">$</span>f_rej <span class="ot" style="color: #003B4F;
background-color: null;
font-style: inherit;">&lt;-</span> grid_raw<span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">$</span>f_p <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">&lt;</span> <span class="fl" style="color: #AD0000;
background-color: null;
font-style: inherit;">0.05</span></span>
<span id="cb11-52">grid_tab <span class="ot" style="color: #003B4F;
background-color: null;
font-style: inherit;">&lt;-</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">aggregate</span>(<span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">cbind</span>(enh, f_rej, drv_rej, res_rej, q1_rej, q1, moran) <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">~</span> r <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">+</span> scn, grid_raw, mean)</span>
<span id="cb11-53">gt <span class="ot" style="color: #003B4F;
background-color: null;
font-style: inherit;">&lt;-</span> <span class="cf" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">function</span>(r, scn, v) grid_tab[grid_tab<span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">$</span>r <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">==</span> r <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">&amp;</span> grid_tab<span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">$</span>scn <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">==</span> scn, v]</span>
<span id="cb11-54">grid_se <span class="ot" style="color: #003B4F;
background-color: null;
font-style: inherit;">&lt;-</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">sqrt</span>(<span class="fl" style="color: #AD0000;
background-color: null;
font-style: inherit;">0.05</span> <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">*</span> <span class="fl" style="color: #AD0000;
background-color: null;
font-style: inherit;">0.95</span> <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">/</span> n_grid_rep)</span>
<span id="cb11-55"><span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">stopifnot</span>(<span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">all</span>(grid_raw<span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">$</span>q12 <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">&gt;=</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">pmax</span>(grid_raw<span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">$</span>q1, grid_raw<span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">$</span>q2) <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">-</span> <span class="fl" style="color: #AD0000;
background-color: null;
font-style: inherit;">1e-12</span>))</span></code></pre></div></div>
</div>
<div class="cell">
<div class="code-copy-outer-scaffold"><div class="sourceCode cell-code" id="cb12" style="background: #f1f3f5;"><pre class="sourceCode r code-with-copy"><code class="sourceCode r"><span id="cb12-1"><span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">set.seed</span>(<span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">4310</span>)</span>
<span id="cb12-2">wrap_raw <span class="ot" style="color: #003B4F;
background-color: null;
font-style: inherit;">&lt;-</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">do.call</span>(rbind, <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">lapply</span>(<span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">c</span>(<span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"null"</span>, <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"additive"</span>), <span class="cf" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">function</span>(scn)</span>
<span id="cb12-3">  <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">data.frame</span>(<span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">scn =</span> scn, <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">t</span>(<span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">replicate</span>(n_grid_rep, <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">one_grid</span>(scn, <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">5</span>, <span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">wrap =</span> <span class="cn" style="color: #8f5902;
background-color: null;
font-style: inherit;">TRUE</span>))))))</span>
<span id="cb12-4">wrap_tab <span class="ot" style="color: #003B4F;
background-color: null;
font-style: inherit;">&lt;-</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">aggregate</span>(<span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">cbind</span>(drv_rej, res_rej, moran) <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">~</span> scn, wrap_raw, mean)</span>
<span id="cb12-5">wt <span class="ot" style="color: #003B4F;
background-color: null;
font-style: inherit;">&lt;-</span> <span class="cf" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">function</span>(scn, v) wrap_tab[wrap_tab<span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">$</span>scn <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">==</span> scn, v]</span>
<span id="cb12-6">se_diff <span class="ot" style="color: #003B4F;
background-color: null;
font-style: inherit;">&lt;-</span> <span class="cf" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">function</span>(p1, p2) <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">sqrt</span>(p1 <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">*</span> (<span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">1</span> <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">-</span> p1) <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">/</span> n_grid_rep <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">+</span> p2 <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">*</span> (<span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">1</span> <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">-</span> p2) <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">/</span> n_grid_rep)</span>
<span id="cb12-7">res_drop_z <span class="ot" style="color: #003B4F;
background-color: null;
font-style: inherit;">&lt;-</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">sapply</span>(<span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">c</span>(<span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"null"</span>, <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"additive"</span>), <span class="cf" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">function</span>(scn)</span>
<span id="cb12-8">  (<span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">gt</span>(<span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">5</span>, scn, <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"res_rej"</span>) <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">-</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">wt</span>(scn, <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"res_rej"</span>)) <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">/</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">se_diff</span>(<span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">gt</span>(<span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">5</span>, scn, <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"res_rej"</span>), <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">wt</span>(scn, <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"res_rej"</span>)))</span>
<span id="cb12-9">drv_drop_z <span class="ot" style="color: #003B4F;
background-color: null;
font-style: inherit;">&lt;-</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">sapply</span>(<span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">c</span>(<span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"null"</span>, <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"additive"</span>), <span class="cf" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">function</span>(scn)</span>
<span id="cb12-10">  (<span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">gt</span>(<span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">5</span>, scn, <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"drv_rej"</span>) <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">-</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">wt</span>(scn, <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"drv_rej"</span>)) <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">/</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">se_diff</span>(<span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">gt</span>(<span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">5</span>, scn, <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"drv_rej"</span>), <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">wt</span>(scn, <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"drv_rej"</span>)))</span></code></pre></div></div>
</div>
<p>Moran’s I of the response, with rook neighbours, averages 0.93 in the null scenario at a kernel standard deviation of 2 cells and 0.98 at 5 cells, against an expectation near zero for independent cells. The factor detector feels this first. In the null scenario the mean q of a driver that has nothing to do with the response is 0.0400 at the short range and 0.1310 at the long one, 10 and 34 times the independence value of 0.0039, and the one-way F test of that q rejects at the five per cent level in 86.5 and 98.5 per cent of grids. Two smooth maps that are unrelated still share large patches, and a classification of one explains the other’s patches.</p>
<p>The interaction rule does no better. In the null scenario it reports a nonlinear enhancement in 99.5 per cent of grids at the short range and 90.5 per cent at the long one; in the additive scenario in 76.0 and 65.0 per cent. The ordinary interaction F test, which held its level on independent units, now rejects in 89.5 and 100.0 per cent of null grids and 92.0 and 100.0 per cent of additive ones. It is the right question with the wrong reference distribution.</p>
<div class="cell">
<div class="code-copy-outer-scaffold"><div class="sourceCode cell-code" id="cb13" style="background: #f1f3f5;"><pre class="sourceCode r code-with-copy"><code class="sourceCode r"><span id="cb13-1">test_cols <span class="ot" style="color: #003B4F;
background-color: null;
font-style: inherit;">&lt;-</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">c</span>(<span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">enh =</span> <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"rule: nonlinear enhancement"</span>, <span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">f_rej =</span> <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"interaction F test"</span>,</span>
<span id="cb13-2">               <span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">drv_rej =</span> <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"driver shift"</span>, <span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">res_rej =</span> <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"residual shift"</span>)</span>
<span id="cb13-3">sp_long <span class="ot" style="color: #003B4F;
background-color: null;
font-style: inherit;">&lt;-</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">do.call</span>(rbind, <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">lapply</span>(<span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">names</span>(test_cols), <span class="cf" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">function</span>(tc)</span>
<span id="cb13-4">  <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">data.frame</span>(grid_tab[, <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">c</span>(<span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"r"</span>, <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"scn"</span>)], <span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">test =</span> test_cols[[tc]], <span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">rate =</span> grid_tab[[tc]])))</span>
<span id="cb13-5">sp_long<span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">$</span>se <span class="ot" style="color: #003B4F;
background-color: null;
font-style: inherit;">&lt;-</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">sqrt</span>(sp_long<span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">$</span>rate <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">*</span> (<span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">1</span> <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">-</span> sp_long<span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">$</span>rate) <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">/</span> n_grid_rep)</span>
<span id="cb13-6">sp_long<span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">$</span>test <span class="ot" style="color: #003B4F;
background-color: null;
font-style: inherit;">&lt;-</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">factor</span>(sp_long<span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">$</span>test, <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">rev</span>(test_cols))</span>
<span id="cb13-7">sp_long<span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">$</span>scn  <span class="ot" style="color: #003B4F;
background-color: null;
font-style: inherit;">&lt;-</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">factor</span>(sp_long<span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">$</span>scn, scn_set, <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">c</span>(<span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"null: y unrelated"</span>, <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"additive"</span>, <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"product: real interaction"</span>))</span>
<span id="cb13-8">sp_long<span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">$</span>r_lab <span class="ot" style="color: #003B4F;
background-color: null;
font-style: inherit;">&lt;-</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">factor</span>(<span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">sprintf</span>(<span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"kernel SD %d cells"</span>, sp_long<span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">$</span>r), <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">sprintf</span>(<span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"kernel SD %d cells"</span>, r_set))</span>
<span id="cb13-9"></span>
<span id="cb13-10"><span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">ggplot</span>(sp_long, <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">aes</span>(rate, test, <span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">colour =</span> r_lab)) <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">+</span></span>
<span id="cb13-11">  <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">geom_vline</span>(<span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">xintercept =</span> <span class="fl" style="color: #AD0000;
background-color: null;
font-style: inherit;">0.05</span>, <span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">linetype =</span> <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"dashed"</span>, <span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">colour =</span> te_body, <span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">linewidth =</span> <span class="fl" style="color: #AD0000;
background-color: null;
font-style: inherit;">0.5</span>) <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">+</span></span>
<span id="cb13-12">  <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">geom_errorbar</span>(<span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">aes</span>(<span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">xmin =</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">pmax</span>(rate <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">-</span> <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">2</span> <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">*</span> se, <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">0</span>), <span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">xmax =</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">pmin</span>(rate <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">+</span> <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">2</span> <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">*</span> se, <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">1</span>)),</span>
<span id="cb13-13">                <span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">orientation =</span> <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"y"</span>, <span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">width =</span> <span class="fl" style="color: #AD0000;
background-color: null;
font-style: inherit;">0.25</span>, <span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">linewidth =</span> <span class="fl" style="color: #AD0000;
background-color: null;
font-style: inherit;">0.6</span>,</span>
<span id="cb13-14">                <span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">position =</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">position_dodge</span>(<span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">width =</span> <span class="fl" style="color: #AD0000;
background-color: null;
font-style: inherit;">0.55</span>)) <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">+</span></span>
<span id="cb13-15">  <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">geom_point</span>(<span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">size =</span> <span class="fl" style="color: #AD0000;
background-color: null;
font-style: inherit;">2.4</span>, <span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">position =</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">position_dodge</span>(<span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">width =</span> <span class="fl" style="color: #AD0000;
background-color: null;
font-style: inherit;">0.55</span>)) <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">+</span></span>
<span id="cb13-16">  <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">facet_wrap</span>(<span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">~</span> scn, <span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">ncol =</span> <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">3</span>) <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">+</span></span>
<span id="cb13-17">  <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">scale_colour_manual</span>(<span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">values =</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">c</span>(te_forest, te_rust), <span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">name =</span> <span class="cn" style="color: #8f5902;
background-color: null;
font-style: inherit;">NULL</span>) <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">+</span></span>
<span id="cb13-18">  <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">scale_x_continuous</span>(<span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">limits =</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">c</span>(<span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">0</span>, <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">1</span>), <span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">breaks =</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">c</span>(<span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">0</span>, <span class="fl" style="color: #AD0000;
background-color: null;
font-style: inherit;">0.5</span>, <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">1</span>), <span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">labels =</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">c</span>(<span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"0"</span>, <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"0.5"</span>, <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"1"</span>)) <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">+</span></span>
<span id="cb13-19">  <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">labs</span>(<span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">x =</span> <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"share of rasters reporting an interaction"</span>, <span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">y =</span> <span class="cn" style="color: #8f5902;
background-color: null;
font-style: inherit;">NULL</span>,</span>
<span id="cb13-20">       <span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">title =</span> <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"Only the shift tests come near 5%, at short range"</span>) <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">+</span></span>
<span id="cb13-21">  <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">theme_datasheet</span>() <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">+</span></span>
<span id="cb13-22">  <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">theme</span>(<span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">legend.position =</span> <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"bottom"</span>, <span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">panel.spacing.x =</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">unit</span>(<span class="fl" style="color: #AD0000;
background-color: null;
font-style: inherit;">1.2</span>, <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"lines"</span>))</span></code></pre></div></div>
<div class="cell-output-display">
<div id="fig-spatial" class="quarto-float quarto-figure quarto-figure-center anchored" alt="Three panels of dot-and-whisker points on warm off-white paper, for the null scenario with y unrelated, the additive scenario and the product scenario with a real interaction. Each panel has four rows: rule nonlinear enhancement, interaction F test, driver shift and residual shift, with a dark green point for a kernel standard deviation of 2 cells and a red point for 5 cells, and a dashed vertical line at 0.05 on an axis from 0 to 1. In the null and additive panels the rule and the F test points sit between about 0.65 and 1, far from the dashed line, while the driver shift points sit near the line, the green ones on it and the red ones at about 0.1; the residual shift green points are near the line and the red ones at about 0.17 and 0.2. In the product panel the green points are above 0.9 for every row, while the red driver shift point is at about 0.38 and the red residual shift point at about 0.6.">
<figure class="quarto-float quarto-float-fig figure">
<div aria-describedby="fig-spatial-caption-0ceaefa1-69ba-4598-a22c-09a6ac19f8ca">
<img src="https://tidyecology.com/posts/geodetector-and-the-interaction-rule/index_files/figure-html/fig-spatial-1.png" class="img-fluid figure-img" alt="Three panels of dot-and-whisker points on warm off-white paper, for the null scenario with y unrelated, the additive scenario and the product scenario with a real interaction. Each panel has four rows: rule nonlinear enhancement, interaction F test, driver shift and residual shift, with a dark green point for a kernel standard deviation of 2 cells and a red point for 5 cells, and a dashed vertical line at 0.05 on an axis from 0 to 1. In the null and additive panels the rule and the F test points sit between about 0.65 and 1, far from the dashed line, while the driver shift points sit near the line, the green ones on it and the red ones at about 0.1; the residual shift green points are near the line and the red ones at about 0.17 and 0.2. In the product panel the green points are above 0.9 for every row, while the red driver shift point is at about 0.38 and the red residual shift point at about 0.6." width="672">
</div>
<figcaption class="quarto-float-caption-bottom quarto-float-caption quarto-float-fig" id="fig-spatial-caption-0ceaefa1-69ba-4598-a22c-09a6ac19f8ca">
Figure&nbsp;4: Share of 200 simulated rasters in which each procedure reports an interaction, by scenario and range. The dashed line marks five per cent; bars show plus and minus two Monte Carlo standard errors. Only the product scenario contains a real interaction.
</figcaption>
</figure>
</div>
</div>
</div>
<p>In this design, with b = 0.5 and one range for all three layers, the two shift tests are the only procedures that come near the nominal level, and only at the short range. At a kernel standard deviation of 2 cells the driver shift rejects in 4.5 per cent of null grids and 6.0 per cent of additive ones, and the residual shift in 7.5 and 7.0 per cent; a rate of five per cent has a Monte Carlo standard error of 0.015 here. At 5 cells the driver shift rejects in 9.0 and 10.0 per cent and the residual shift in 17.0 and 20.5 per cent. With the real interaction present, the driver shift finds it in 91.0 per cent of grids at the short range and 37.5 per cent at the long one, and the residual shift in 94.5 and 61.5 per cent.</p>
<p>Part of what goes wrong at the long range is the edge of the map. A toroidal shift wraps the layer round, so the cells that leave one edge come back in at the opposite one, and on a map that does not wrap this puts unrelated values side by side along a seam. When the three layers are generated to wrap exactly at the window’s edges, which no real map does, the driver shift at a kernel standard deviation of 5 cells rejects in 6.0 per cent of null grids and 6.0 per cent of additive ones, and the residual shift in 8.0 and 8.5 per cent. The drop for the residual shift is 2.7 and 3.5 times the standard error of the difference, so on these estimates the seam accounts for most of its excess over five per cent at this range; the drop for the driver shift is 1.1 and 1.5 standard errors, within Monte Carlo error. A real map cannot be made to wrap, so on a real map the long-range rates in the figure are the relevant ones.</p>
<p>The driver shift also rests on a condition that an additive response breaks. Its reference distribution is right only when the shifted layer is independent of the response and of the other driver, and looks the same after the shift as before. In the null scenario that holds apart from the seam. An additive response that depends on x2 breaks it whenever b is not zero: what the shift tests is independence of the x2 layer from the other two, not absence of interaction. Nothing then guarantees its size, and the design above is one case, so two more designs were run, fixed before running, each with 400 additive grids, drivers at a kernel standard deviation of 2 cells and b = 1: the error at the same range, and the error at 5 cells.</p>
<div class="cell">
<div class="code-copy-outer-scaffold"><div class="sourceCode cell-code" id="cb14" style="background: #f1f3f5;"><pre class="sourceCode r code-with-copy"><code class="sourceCode r"><span id="cb14-1">mix_grid <span class="ot" style="color: #003B4F;
background-color: null;
font-style: inherit;">&lt;-</span> <span class="cf" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">function</span>(r_x, r_e, b) {</span>
<span id="cb14-2">  x1 <span class="ot" style="color: #003B4F;
background-color: null;
font-style: inherit;">&lt;-</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">smooth_layer</span>(n_side, r_x)</span>
<span id="cb14-3">  x2 <span class="ot" style="color: #003B4F;
background-color: null;
font-style: inherit;">&lt;-</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">smooth_layer</span>(n_side, r_x)</span>
<span id="cb14-4">  e  <span class="ot" style="color: #003B4F;
background-color: null;
font-style: inherit;">&lt;-</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">smooth_layer</span>(n_side, r_e)</span>
<span id="cb14-5">  y  <span class="ot" style="color: #003B4F;
background-color: null;
font-style: inherit;">&lt;-</span> b <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">*</span> x1 <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">+</span> b <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">*</span> x2 <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">+</span> e</span>
<span id="cb14-6">  g1 <span class="ot" style="color: #003B4F;
background-color: null;
font-style: inherit;">&lt;-</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">disc_q</span>(x1, n_class)</span>
<span id="cb14-7">  g2 <span class="ot" style="color: #003B4F;
background-color: null;
font-style: inherit;">&lt;-</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">disc_q</span>(x2, n_class)</span>
<span id="cb14-8">  f_obs <span class="ot" style="color: #003B4F;
background-color: null;
font-style: inherit;">&lt;-</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">f_inter</span>(<span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">matrix</span>(y), g1, g2)</span>
<span id="cb14-9">  s_id <span class="ot" style="color: #003B4F;
background-color: null;
font-style: inherit;">&lt;-</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">sample.int</span>(n_side<span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">^</span><span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">2</span> <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">-</span> <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">1</span>, n_shift)</span>
<span id="cb14-10">  dx <span class="ot" style="color: #003B4F;
background-color: null;
font-style: inherit;">&lt;-</span> s_id <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">%/%</span> n_side</span>
<span id="cb14-11">  dy <span class="ot" style="color: #003B4F;
background-color: null;
font-style: inherit;">&lt;-</span> s_id <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">%%</span> n_side</span>
<span id="cb14-12">  f_drv <span class="ot" style="color: #003B4F;
background-color: null;
font-style: inherit;">&lt;-</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">vapply</span>(<span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">seq_len</span>(n_shift), <span class="cf" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">function</span>(i)</span>
<span id="cb14-13">    <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">f_inter</span>(<span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">matrix</span>(y), g1, g2[<span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">shift_index</span>(n_side, dx[i], dy[i])]), <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">0</span>)</span>
<span id="cb14-14">  x_add <span class="ot" style="color: #003B4F;
background-color: null;
font-style: inherit;">&lt;-</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">cbind</span>(<span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">1</span>, <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">outer</span>(g1, <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">2</span><span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">:</span>n_class, <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"=="</span>) <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">+</span> <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">0</span>, <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">outer</span>(g2, <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">2</span><span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">:</span>n_class, <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"=="</span>) <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">+</span> <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">0</span>)</span>
<span id="cb14-15">  fit_add <span class="ot" style="color: #003B4F;
background-color: null;
font-style: inherit;">&lt;-</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">qr.fitted</span>(<span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">qr</span>(x_add), y)</span>
<span id="cb14-16">  res_add <span class="ot" style="color: #003B4F;
background-color: null;
font-style: inherit;">&lt;-</span> y <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">-</span> fit_add</span>
<span id="cb14-17">  y_star <span class="ot" style="color: #003B4F;
background-color: null;
font-style: inherit;">&lt;-</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">vapply</span>(<span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">seq_len</span>(n_shift), <span class="cf" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">function</span>(i)</span>
<span id="cb14-18">    fit_add <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">+</span> res_add[<span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">shift_index</span>(n_side, dx[i], dy[i])], <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">numeric</span>(n_side<span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">^</span><span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">2</span>))</span>
<span id="cb14-19">  <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">c</span>(<span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">drv_rej =</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">sum</span>(f_drv <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">&gt;=</span> f_obs) <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">+</span> <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">1</span> <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">&lt;=</span> <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">5</span>,</span>
<span id="cb14-20">    <span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">res_rej =</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">sum</span>(<span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">f_inter</span>(y_star, g1, g2) <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">&gt;=</span> f_obs) <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">+</span> <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">1</span> <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">&lt;=</span> <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">5</span>)</span>
<span id="cb14-21">}</span>
<span id="cb14-22">mix_set <span class="ot" style="color: #003B4F;
background-color: null;
font-style: inherit;">&lt;-</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">data.frame</span>(<span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">r_x =</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">c</span>(<span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">2</span>, <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">2</span>), <span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">r_e =</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">c</span>(<span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">2</span>, <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">5</span>), <span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">b =</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">c</span>(<span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">1</span>, <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">1</span>))</span>
<span id="cb14-23">n_mix <span class="ot" style="color: #003B4F;
background-color: null;
font-style: inherit;">&lt;-</span> <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">400</span></span>
<span id="cb14-24"><span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">set.seed</span>(<span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">4311</span>)</span>
<span id="cb14-25">mix_tab <span class="ot" style="color: #003B4F;
background-color: null;
font-style: inherit;">&lt;-</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">do.call</span>(rbind, <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">lapply</span>(<span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">seq_len</span>(<span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">nrow</span>(mix_set)), <span class="cf" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">function</span>(k) {</span>
<span id="cb14-26">  out <span class="ot" style="color: #003B4F;
background-color: null;
font-style: inherit;">&lt;-</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">t</span>(<span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">replicate</span>(n_mix, <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">mix_grid</span>(mix_set<span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">$</span>r_x[k], mix_set<span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">$</span>r_e[k], mix_set<span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">$</span>b[k])))</span>
<span id="cb14-27">  <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">data.frame</span>(mix_set[k, ], <span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">drv_rej =</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">mean</span>(out[, <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"drv_rej"</span>]), <span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">res_rej =</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">mean</span>(out[, <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"res_rej"</span>]))</span>
<span id="cb14-28">}))</span>
<span id="cb14-29">mt <span class="ot" style="color: #003B4F;
background-color: null;
font-style: inherit;">&lt;-</span> <span class="cf" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">function</span>(r_e, v) mix_tab[mix_tab<span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">$</span>r_e <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">==</span> r_e, v]</span>
<span id="cb14-30">mix_se <span class="ot" style="color: #003B4F;
background-color: null;
font-style: inherit;">&lt;-</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">sqrt</span>(<span class="fl" style="color: #AD0000;
background-color: null;
font-style: inherit;">0.05</span> <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">*</span> <span class="fl" style="color: #AD0000;
background-color: null;
font-style: inherit;">0.95</span> <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">/</span> n_mix)</span>
<span id="cb14-31">mix_z <span class="ot" style="color: #003B4F;
background-color: null;
font-style: inherit;">&lt;-</span> <span class="cf" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">function</span>(r_e, v) (<span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">mt</span>(r_e, v) <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">-</span> <span class="fl" style="color: #AD0000;
background-color: null;
font-style: inherit;">0.05</span>) <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">/</span> mix_se</span>
<span id="cb14-32">long_drv <span class="ot" style="color: #003B4F;
background-color: null;
font-style: inherit;">&lt;-</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">mean</span>(<span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">c</span>(<span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">gt</span>(<span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">5</span>, <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"null"</span>, <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"drv_rej"</span>), <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">gt</span>(<span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">5</span>, <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"additive"</span>, <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"drv_rej"</span>)))</span>
<span id="cb14-33">long_drv_z <span class="ot" style="color: #003B4F;
background-color: null;
font-style: inherit;">&lt;-</span> (long_drv <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">-</span> <span class="fl" style="color: #AD0000;
background-color: null;
font-style: inherit;">0.05</span>) <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">/</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">sqrt</span>(<span class="fl" style="color: #AD0000;
background-color: null;
font-style: inherit;">0.05</span> <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">*</span> <span class="fl" style="color: #AD0000;
background-color: null;
font-style: inherit;">0.95</span> <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">/</span> (<span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">2</span> <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">*</span> n_grid_rep))</span></code></pre></div></div>
</div>
<p>With the error at the same range as the drivers, the driver shift rejects in 4.8 per cent of grids and the residual shift in 9.0 per cent; with the error at 5 cells, in 7.8 and 12.0 per cent. A rate of five per cent has a Monte Carlo standard error of 0.011 here. The residual shift is too liberal in both designs, by 3.7 and 6.4 standard errors. The driver shift holds with the error at the drivers’ range and sits 2.5 standard errors above five per cent with the longer-range error. On one run that is not decisive; it is also not the guarantee a test needs, since nothing in the method keeps its size near five per cent once the response depends on the shifted layer.</p>
</section>
<section id="the-five-verdicts-side-by-side" class="level2">
<h2 id="the-five-verdicts-side-by-side-h" class="anchored" data-anchor-id="the-five-verdicts-side-by-side">The five verdicts, side by side</h2>
<div class="cell">
<div class="code-copy-outer-scaffold"><div class="sourceCode cell-code" id="cb15" style="background: #f1f3f5;"><pre class="sourceCode r code-with-copy"><code class="sourceCode r"><span id="cb15-1"><span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">set.seed</span>(<span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">4308</span>)</span>
<span id="cb15-2">prod_raw <span class="ot" style="color: #003B4F;
background-color: null;
font-style: inherit;">&lt;-</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">data.frame</span>(<span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">t</span>(<span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">replicate</span>(n_rep, {</span>
<span id="cb15-3">  x1 <span class="ot" style="color: #003B4F;
background-color: null;
font-style: inherit;">&lt;-</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">rnorm</span>(n_unit)</span>
<span id="cb15-4">  x2 <span class="ot" style="color: #003B4F;
background-color: null;
font-style: inherit;">&lt;-</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">rnorm</span>(n_unit)</span>
<span id="cb15-5">  <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">gd_pieces</span>(<span class="fl" style="color: #AD0000;
background-color: null;
font-style: inherit;">0.5</span> <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">*</span> x1 <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">+</span> <span class="fl" style="color: #AD0000;
background-color: null;
font-style: inherit;">0.5</span> <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">*</span> x2 <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">+</span> <span class="fl" style="color: #AD0000;
background-color: null;
font-style: inherit;">0.5</span> <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">*</span> x1 <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">*</span> x2 <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">+</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">rnorm</span>(n_unit),</span>
<span id="cb15-6">            <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">disc_q</span>(x1, n_class), <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">disc_q</span>(x2, n_class))</span>
<span id="cb15-7">})))</span>
<span id="cb15-8">prod_raw<span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">$</span>verdict <span class="ot" style="color: #003B4F;
background-color: null;
font-style: inherit;">&lt;-</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">gd_verdict</span>(prod_raw<span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">$</span>q1, prod_raw<span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">$</span>q2, prod_raw<span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">$</span>q12)</span>
<span id="cb15-9">prod_enh <span class="ot" style="color: #003B4F;
background-color: null;
font-style: inherit;">&lt;-</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">mean</span>(prod_raw<span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">$</span>verdict <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">==</span> <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"enhance, nonlinear"</span>)</span>
<span id="cb15-10">prod_f   <span class="ot" style="color: #003B4F;
background-color: null;
font-style: inherit;">&lt;-</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">mean</span>(prod_raw<span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">$</span>f_p <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">&lt;</span> <span class="fl" style="color: #AD0000;
background-color: null;
font-style: inherit;">0.05</span>)</span>
<span id="cb15-11"></span>
<span id="cb15-12">pick <span class="ot" style="color: #003B4F;
background-color: null;
font-style: inherit;">&lt;-</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">list</span>(</span>
<span id="cb15-13">  <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"independent units, additive, N 1024"</span> <span class="ot" style="color: #003B4F;
background-color: null;
font-style: inherit;">=</span> rate_raw<span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">$</span>verdict[rate_raw<span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">$</span>n <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">==</span> <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">1024</span> <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">&amp;</span> rate_raw<span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">$</span>b <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">==</span> <span class="fl" style="color: #AD0000;
background-color: null;
font-style: inherit;">0.5</span>],</span>
<span id="cb15-14">  <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"independent units, additive, N 16384"</span> <span class="ot" style="color: #003B4F;
background-color: null;
font-style: inherit;">=</span> rate_raw<span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">$</span>verdict[rate_raw<span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">$</span>n <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">==</span> <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">16384</span> <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">&amp;</span> rate_raw<span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">$</span>b <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">==</span> <span class="fl" style="color: #AD0000;
background-color: null;
font-style: inherit;">0.5</span>],</span>
<span id="cb15-15">  <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"correlated drivers r 0.5, additive"</span> <span class="ot" style="color: #003B4F;
background-color: null;
font-style: inherit;">=</span> cor_raw<span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">$</span>verdict[cor_raw<span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">$</span>rho <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">==</span> <span class="fl" style="color: #AD0000;
background-color: null;
font-style: inherit;">0.5</span>],</span>
<span id="cb15-16">  <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"correlated drivers r -0.5, additive"</span> <span class="ot" style="color: #003B4F;
background-color: null;
font-style: inherit;">=</span> cor_raw<span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">$</span>verdict[cor_raw<span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">$</span>rho <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">==</span> <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">-</span><span class="fl" style="color: #AD0000;
background-color: null;
font-style: inherit;">0.5</span>],</span>
<span id="cb15-17">  <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"raster, SD 2 cells, y unrelated"</span> <span class="ot" style="color: #003B4F;
background-color: null;
font-style: inherit;">=</span> grid_raw<span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">$</span>verdict[grid_raw<span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">$</span>r <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">==</span> <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">2</span> <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">&amp;</span> grid_raw<span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">$</span>scn <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">==</span> <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"null"</span>],</span>
<span id="cb15-18">  <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"raster, SD 5 cells, additive"</span> <span class="ot" style="color: #003B4F;
background-color: null;
font-style: inherit;">=</span> grid_raw<span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">$</span>verdict[grid_raw<span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">$</span>r <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">==</span> <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">5</span> <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">&amp;</span> grid_raw<span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">$</span>scn <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">==</span> <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"additive"</span>],</span>
<span id="cb15-19">  <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"independent units, real interaction"</span> <span class="ot" style="color: #003B4F;
background-color: null;
font-style: inherit;">=</span> prod_raw<span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">$</span>verdict)</span>
<span id="cb15-20">vd_df <span class="ot" style="color: #003B4F;
background-color: null;
font-style: inherit;">&lt;-</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">do.call</span>(rbind, <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">lapply</span>(<span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">names</span>(pick), <span class="cf" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">function</span>(nm) {</span>
<span id="cb15-21">  tb <span class="ot" style="color: #003B4F;
background-color: null;
font-style: inherit;">&lt;-</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">table</span>(<span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">factor</span>(pick[[nm]], verdict_levels))</span>
<span id="cb15-22">  <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">data.frame</span>(<span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">scenario =</span> nm, <span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">verdict =</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">factor</span>(<span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">names</span>(tb), verdict_levels), <span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">share =</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">as.numeric</span>(tb) <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">/</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">length</span>(pick[[nm]]))</span>
<span id="cb15-23">}))</span>
<span id="cb15-24">vd_df<span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">$</span>scenario <span class="ot" style="color: #003B4F;
background-color: null;
font-style: inherit;">&lt;-</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">factor</span>(vd_df<span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">$</span>scenario, <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">rev</span>(<span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">names</span>(pick)))</span>
<span id="cb15-25">all_q <span class="ot" style="color: #003B4F;
background-color: null;
font-style: inherit;">&lt;-</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">rbind</span>(rate_raw[, <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">c</span>(<span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"q1"</span>, <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"q2"</span>, <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"q12"</span>, <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"single"</span>)], cor_raw[, <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">c</span>(<span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"q1"</span>, <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"q2"</span>, <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"q12"</span>, <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"single"</span>)],</span>
<span id="cb15-26">               grid_raw[, <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">c</span>(<span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"q1"</span>, <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"q2"</span>, <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"q12"</span>, <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"single"</span>)], wrap_raw[, <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">c</span>(<span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"q1"</span>, <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"q2"</span>, <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"q12"</span>, <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"single"</span>)],</span>
<span id="cb15-27">               prod_raw[, <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">c</span>(<span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"q1"</span>, <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"q2"</span>, <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"q12"</span>, <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"single"</span>)])</span>
<span id="cb15-28"><span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">stopifnot</span>(<span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">all</span>(all_q<span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">$</span>q12 <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">&gt;=</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">pmax</span>(all_q<span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">$</span>q1, all_q<span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">$</span>q2) <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">-</span> <span class="fl" style="color: #AD0000;
background-color: null;
font-style: inherit;">1e-12</span>))</span>
<span id="cb15-29">n_all    <span class="ot" style="color: #003B4F;
background-color: null;
font-style: inherit;">&lt;-</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">nrow</span>(all_q)</span>
<span id="cb15-30">n_single <span class="ot" style="color: #003B4F;
background-color: null;
font-style: inherit;">&lt;-</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">sum</span>(all_q<span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">$</span>single <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">&gt;</span> <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">0</span>)</span>
<span id="cb15-31"><span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">stopifnot</span>(<span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">all</span>(vd_df<span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">$</span>share[vd_df<span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">$</span>verdict <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">%in%</span> verdict_levels[<span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">c</span>(<span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">2</span>, <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">4</span>, <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">5</span>)]] <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">==</span> <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">0</span>))</span></code></pre></div></div>
</div>
<p>With the real interaction, on independent units, the rule reports a nonlinear enhancement in 100.0 per cent of datasets and the F test rejects in 100.0 per cent. That is the case the verdict is meant for, and the figure puts it next to six cases without any interaction. Across the 10800 datasets of the replicated runs that keep all three q values (independent units with additive drivers, correlated drivers, the main and wrapped raster runs and the real interaction), q12 was never below the larger of q1 and q2, so none of them received either weakening verdict; 85 of them had a combined class holding a single unit, the case in which the GD code would have dropped units.</p>
<div class="cell">
<div class="code-copy-outer-scaffold"><div class="sourceCode cell-code" id="cb16" style="background: #f1f3f5;"><pre class="sourceCode r code-with-copy"><code class="sourceCode r"><span id="cb16-1"><span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">ggplot</span>(vd_df, <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">aes</span>(share, scenario, <span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">fill =</span> verdict)) <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">+</span></span>
<span id="cb16-2">  <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">geom_col</span>(<span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">width =</span> <span class="fl" style="color: #AD0000;
background-color: null;
font-style: inherit;">0.7</span>, <span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">colour =</span> te_paper, <span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">linewidth =</span> <span class="fl" style="color: #AD0000;
background-color: null;
font-style: inherit;">0.3</span>) <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">+</span></span>
<span id="cb16-3">  <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">scale_fill_manual</span>(<span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">values =</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">c</span>(<span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"enhance, nonlinear"</span> <span class="ot" style="color: #003B4F;
background-color: null;
font-style: inherit;">=</span> te_rust, <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"independent"</span> <span class="ot" style="color: #003B4F;
background-color: null;
font-style: inherit;">=</span> te_line,</span>
<span id="cb16-4">                               <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"enhance, bi-"</span> <span class="ot" style="color: #003B4F;
background-color: null;
font-style: inherit;">=</span> te_gold, <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"weaken, uni-"</span> <span class="ot" style="color: #003B4F;
background-color: null;
font-style: inherit;">=</span> te_forest,</span>
<span id="cb16-5">                               <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"weaken, nonlinear"</span> <span class="ot" style="color: #003B4F;
background-color: null;
font-style: inherit;">=</span> te_ink), <span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">drop =</span> <span class="cn" style="color: #8f5902;
background-color: null;
font-style: inherit;">FALSE</span>, <span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">name =</span> <span class="cn" style="color: #8f5902;
background-color: null;
font-style: inherit;">NULL</span>) <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">+</span></span>
<span id="cb16-6">  <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">scale_x_continuous</span>(<span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">breaks =</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">c</span>(<span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">0</span>, <span class="fl" style="color: #AD0000;
background-color: null;
font-style: inherit;">0.25</span>, <span class="fl" style="color: #AD0000;
background-color: null;
font-style: inherit;">0.5</span>, <span class="fl" style="color: #AD0000;
background-color: null;
font-style: inherit;">0.75</span>, <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">1</span>), <span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">labels =</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">c</span>(<span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"0"</span>, <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"0.25"</span>, <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"0.5"</span>, <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"0.75"</span>, <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"1"</span>),</span>
<span id="cb16-7">                     <span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">expand =</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">expansion</span>(<span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">mult =</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">c</span>(<span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">0</span>, <span class="fl" style="color: #AD0000;
background-color: null;
font-style: inherit;">0.03</span>))) <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">+</span></span>
<span id="cb16-8">  <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">labs</span>(<span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">x =</span> <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"share of datasets"</span>, <span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">y =</span> <span class="cn" style="color: #8f5902;
background-color: null;
font-style: inherit;">NULL</span>,</span>
<span id="cb16-9">       <span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">title =</span> <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"The verdict follows N, correlation and space"</span>) <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">+</span></span>
<span id="cb16-10">  <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">theme_datasheet</span>() <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">+</span></span>
<span id="cb16-11">  <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">theme</span>(<span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">legend.position =</span> <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"bottom"</span>, <span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">panel.grid.major.y =</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">element_blank</span>()) <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">+</span></span>
<span id="cb16-12">  <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">guides</span>(<span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">fill =</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">guide_legend</span>(<span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">nrow =</span> <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">2</span>))</span></code></pre></div></div>
<div class="cell-output-display">
<div id="fig-verdicts" class="quarto-float quarto-figure quarto-figure-center anchored" alt="Seven horizontal stacked bars on warm off-white paper, each showing the share of datasets given each interaction type, from 0 to 1. Red marks nonlinear enhancement and gold bivariate enhancement; the legend also lists independent, univariate weakening and nonlinear weakening, which appear in no bar. Independent units with additive drivers at N 1024 are about 0.14 gold and 0.86 red; at N 16384 about 0.41 gold and 0.59 red. Correlated drivers at r 0.5 are entirely gold, and at r minus 0.5 entirely red. A raster with a kernel standard deviation of 2 cells and y unrelated is almost entirely red. A raster with a kernel standard deviation of 5 cells and additive drivers is about 0.35 gold and 0.65 red. Independent units with a real interaction, the bottom bar, are entirely red.">
<figure class="quarto-float quarto-float-fig figure">
<div aria-describedby="fig-verdicts-caption-0ceaefa1-69ba-4598-a22c-09a6ac19f8ca">
<img src="https://tidyecology.com/posts/geodetector-and-the-interaction-rule/index_files/figure-html/fig-verdicts-1.png" class="img-fluid figure-img" alt="Seven horizontal stacked bars on warm off-white paper, each showing the share of datasets given each interaction type, from 0 to 1. Red marks nonlinear enhancement and gold bivariate enhancement; the legend also lists independent, univariate weakening and nonlinear weakening, which appear in no bar. Independent units with additive drivers at N 1024 are about 0.14 gold and 0.86 red; at N 16384 about 0.41 gold and 0.59 red. Correlated drivers at r 0.5 are entirely gold, and at r minus 0.5 entirely red. A raster with a kernel standard deviation of 2 cells and y unrelated is almost entirely red. A raster with a kernel standard deviation of 5 cells and additive drivers is about 0.35 gold and 0.65 red. Independent units with a real interaction, the bottom bar, are entirely red." width="672">
</div>
<figcaption class="quarto-float-caption-bottom quarto-float-caption quarto-float-fig" id="fig-verdicts-caption-0ceaefa1-69ba-4598-a22c-09a6ac19f8ca">
Figure&nbsp;5: Share of datasets given each of the five interaction types by the rule, for six scenarios with no interaction and one with a real interaction (bottom row). The independent and the two weakening types do not occur.
</figcaption>
</figure>
</div>
</div>
</div>
</section>
<section id="what-to-report" class="level2">
<h2 id="what-to-report-h" class="anchored" data-anchor-id="what-to-report">What to report</h2>
<p>Report q for each driver with its number of classes, the number of units, and the expected q of an unrelated classification, (L - 1) / (N - 1). The q of a single driver is a legitimate description of how much of the variance lines up with its classes, and it is the same number as the R-squared of a one-way analysis of variance. Report the q of the combined classes against (L1 L2 - 1) / (N - 1), not against q1 + q2.</p>
<p>Do not use the five interaction types as evidence of interaction. On independent units and additive drivers the verdict was decided by the number of units and the effect size, with correlated drivers by the sign of the correlation between their contributions, and on a raster by the spatial structure. When the question is whether two drivers interact and the units are independent, fit a model on the continuous drivers with an interaction term and test it, as in the spline comparison above. The F test on the classes is safe only while the drivers are close to uncorrelated: the interaction it picks up from correlated drivers belongs to the class means, so its rejection rate grows with the number of units, and at 16384 units a correlation of 0.1 gave 6.0 per cent and one of 0.2 gave 12.8 per cent. Report the correlation between the drivers and the shared fraction q1 + q2 - q_add next to any interaction result.</p>
<p>On a raster or any other spatial layer, report Moran’s I of the response and of the model residuals, and do not trust any F or q test that assumes independent units. Neither spatial test tried here can be recommended. With b = 0.5 and one range for every layer, the toroidal shift of one driver layer came nearest the nominal level: at the short range it rejected in 4.5 and 6.0 per cent of grids without an interaction and found the real one in 91.0 per cent. With b = 1 and an error field of longer range than the drivers it rejected in 7.8 per cent of additive grids. With every layer at the long range it rejected in 9.5 per cent of the null and additive grids taken together, 4.1 standard errors above five per cent, and found the real interaction in only 37.5 per cent. Shifting the residual map instead failed at the long range, 17.0 and 20.5 per cent, and at the short range with b = 1, 9.0 per cent. What a driver shift tests is independence of the shifted layer from the others, not absence of interaction. Any shift test on a real map needs its size checked by simulating layers with the ranges and effect sizes fitted to that map; that step was not tried here, and without it the p value of a shift test is not evidence of interaction.</p>
</section>
<section id="honest-limits" class="level2">
<h2 id="honest-limits-h" class="anchored" data-anchor-id="honest-limits">Honest limits</h2>
<p>The simulation uses quantile classes with five classes per driver, and one grid of 32 by 32 cells. The geographical detector literature also uses natural breaks, equal intervals and optimised discretisation, which searches over class counts and break methods for the largest q (Song et al.&nbsp;2020). A search of that kind raises q1, q2 and q12 by selection and was not simulated. The split into a nonnegative interaction piece and a shared piece holds for any choice of breaks, but the rates here are for quantile classes only.</p>
<p>The drivers are Gaussian and stationary, and the spatial fields are isotropic with a Gaussian kernel. The point-pattern post shows toroidal shift going wrong when both layers follow a shared trend across the plot, and a real elevation layer usually has one; that case was not simulated here, and the shift tests should not be assumed to hold under it. Moran spectral randomisation, the null measured in the map-keeping post, was not tried on the interaction statistic.</p>
<p>Only two ranges and one map size were tried, so how the error rate of the shift tests changes with the ratio of range to map extent is known at two points only. The main spatial run also fixed b = 0.5 and gave the drivers and the error one range; the two extra designs with b = 1 add two points, and four designs do not map out where either test holds. The wrapped-map check shows the seam is part of the long-range problem; it does not say how much of the rest comes from the small number of broad patches a 32 by 32 window holds at that range.</p>
<p>The F test on classes answers a question about class means. With correlated drivers the class means carry a real interaction that the process does not, which is why the spline comparison was run; that comparison assumes the spline basis is flexible enough for the main effects, which holds for the straight lines simulated here and has to be checked for real drivers.</p>
</section>
<section id="references" class="level2">
<h2 id="references-h" class="anchored" data-anchor-id="references">References</h2>
<p>Wang JF, Li XH, Christakos G, Liao YL, Zhang T, Gu X, Zheng XY 2010 International Journal of Geographical Information Science 24(1):107-127 (<a href="https://doi.org/10.1080/13658810802443457">10.1080/13658810802443457</a>)</p>
<p>Wang JF, Zhang TL, Fu BJ 2016 Ecological Indicators 67:250-256 (<a href="https://doi.org/10.1016/j.ecolind.2016.02.052">10.1016/j.ecolind.2016.02.052</a>)</p>
<p>Song Y, Wang J, Ge Y, Xu C 2020 GIScience and Remote Sensing 57(5):593-610 (<a href="https://doi.org/10.1080/15481603.2020.1760434">10.1080/15481603.2020.1760434</a>)</p>
<p>Lotwick HW, Silverman BW 1982 Journal of the Royal Statistical Society Series B 44(3):406-413 (<a href="https://doi.org/10.1111/j.2517-6161.1982.tb01221.x">10.1111/j.2517-6161.1982.tb01221.x</a>)</p>
</section>
<section id="related-tutorials" class="level2">
<h2 id="related-tutorials-h" class="anchored" data-anchor-id="related-tutorials">Related tutorials</h2>
<ul>
<li><a href="https://tidyecology.com/posts/variance-partitioning-varpart/">Variation partitioning in R: environment vs space</a></li>
<li><a href="https://tidyecology.com/posts/interaction-terms-glm/">Interaction terms in ecological GLMs</a></li>
<li><a href="https://tidyecology.com/posts/two-species-point-patterns/">Two-species point patterns: testing for interaction</a></li>
<li><a href="https://tidyecology.com/posts/permutation-nulls-that-keep-the-map/">Permutation nulls that keep the map</a></li>
</ul>
<details class="te-repro" data-pagefind-ignore="">
<summary>Reproducibility</summary>
<ul>
<li>Code last run: 2026-10-15</li>
<li>R version 4.5.3 (2026-03-11), aarch64-apple-darwin20</li>
<li>Packages: ggplot2 4.0.3</li>
</ul>
</details>


<!-- -->

</section>

 ]]></description>
  <category>R</category>
  <category>spatial</category>
  <category>GIS</category>
  <category>interactions</category>
  <category>variance partitioning</category>
  <category>simulation</category>
  <category>ecology tutorial</category>
  <guid isPermaLink="false">https://tidyecology.com/posts/geodetector-and-the-interaction-rule/</guid>
  <pubDate>Sat, 26 Sep 2026 09:00:00 GMT</pubDate>
  <media:content url="https://tidyecology.com/posts/geodetector-and-the-interaction-rule/thumbnail.png" medium="image" type="image/png" height="104" width="144"/>
</item>
<item>
  <title>Snapped coordinates and a clustering verdict</title>
  <dc:creator>Tidy Ecology</dc:creator>
  <link>https://tidyecology.com/posts/snapped-coordinates-and-clustering/</link>
  <description><![CDATA[ 





<p>An orchid atlas has three hundred records from a square block of hill country, all entered as grid references, so each record carries the centre of its grid square rather than the spot where the plant grew. The first analysis anyone runs on such a set is a test of whether the plants are aggregated, and the first test in most courses is the Clark-Evans index: the mean distance from each record to its nearest neighbour, divided by what that mean would be if the records were scattered at random. The index comes back well below one, the simulation envelope agrees, and the report says the orchid is clustered.</p>
<p>A reviewer points out that many records sit on exactly the same coordinates and asks for duplicates to be removed, which is standard advice in occurrence-cleaning workflows. One record per grid cell is kept, the index is rerun, and it now comes back well above one: the orchid is regular. Nothing about the orchid changed between the two runs. What changed is how its coordinates were stored and then tidied.</p>
<p>This post measures both steps on patterns whose truth is known. <a href="https://tidyecology.com/posts/nearest-neighbour-clark-evans/">Nearest-neighbour analysis and Clark-Evans in R</a> builds the index on clean simulated points, and its closing section on what nearest neighbours miss is about scale, not about ties. <a href="https://tidyecology.com/posts/checking-a-point-pattern-analysis/">Checking a point pattern analysis</a> shows random maps being called non random, but there the cause is how the envelope is read, on coordinates that are exact; its honest limits name inhomogeneity, not coordinate storage, as the remaining threat. <a href="https://tidyecology.com/posts/cleaning-gbif-occurrence-data/">Cleaning GBIF and iNaturalist records in R</a> runs the duplicate step and filters on stated coordinate precision, and reports how many rows each step removes, without asking what either does to an analysis further down.</p>
<p>The closest measurement already on this site is in <a href="https://tidyecology.com/posts/sampling-bias-in-presence-only-models/">Sampling bias in presence-only models</a>. Its section on spatial thinning shows one record per cell pulling a species distribution slope well below the truth, at a correlation where the unthinned fit was already right. This post is the same clean-up step read by a distance statistic instead of a regression slope, and the damage is of a different kind: there it changes the environmental make-up of the retained sample, here it changes the geometry, and it pushes the statistic in the opposite direction from the one the raw records pushed it. <a href="https://tidyecology.com/posts/coordinate-error-and-habitat-assignment/">Coordinate error and habitat assignment</a> is the other near relative, and the difference is worth stating once. Coordinate error moves a record; a coordinate grid puts many records in the same place, and a nearest-neighbour statistic cannot tell an aggregation from a shared cell.</p>
<p>The index is Clark and Evans (1954). The cleaning steps being measured are the ones automated by CoordinateCleaner (Zizka and colleagues 2019) and argued for by Maldonado and colleagues (2015), and the envelopes follow Baddeley, Rubak and Turner (2015). None of those sources claims the reversal measured below; it is the measured piece here, not a published result.</p>
<div class="cell">
<div class="code-copy-outer-scaffold"><div class="sourceCode cell-code" id="cb1" style="background: #f1f3f5;"><pre class="sourceCode r code-with-copy"><code class="sourceCode r"><span id="cb1-1"><span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">library</span>(ggplot2)</span>
<span id="cb1-2"><span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">library</span>(patchwork)</span>
<span id="cb1-3"></span>
<span id="cb1-4">te_paper  <span class="ot" style="color: #003B4F;
background-color: null;
font-style: inherit;">&lt;-</span> <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"#f5f4ee"</span></span>
<span id="cb1-5">te_ink    <span class="ot" style="color: #003B4F;
background-color: null;
font-style: inherit;">&lt;-</span> <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"#16241d"</span></span>
<span id="cb1-6">te_body   <span class="ot" style="color: #003B4F;
background-color: null;
font-style: inherit;">&lt;-</span> <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"#2c3a31"</span></span>
<span id="cb1-7">te_forest <span class="ot" style="color: #003B4F;
background-color: null;
font-style: inherit;">&lt;-</span> <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"#275139"</span></span>
<span id="cb1-8">te_rust   <span class="ot" style="color: #003B4F;
background-color: null;
font-style: inherit;">&lt;-</span> <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"#b5534e"</span></span>
<span id="cb1-9">te_gold   <span class="ot" style="color: #003B4F;
background-color: null;
font-style: inherit;">&lt;-</span> <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"#c9b458"</span></span>
<span id="cb1-10">te_line   <span class="ot" style="color: #003B4F;
background-color: null;
font-style: inherit;">&lt;-</span> <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"#dad9ca"</span></span>
<span id="cb1-11"></span>
<span id="cb1-12">theme_datasheet <span class="ot" style="color: #003B4F;
background-color: null;
font-style: inherit;">&lt;-</span> <span class="cf" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">function</span>() {</span>
<span id="cb1-13">  <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">theme_minimal</span>(<span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">base_size =</span> <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">12</span>) <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">+</span></span>
<span id="cb1-14">    <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">theme</span>(<span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">plot.background  =</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">element_rect</span>(<span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">fill =</span> te_paper, <span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">colour =</span> <span class="cn" style="color: #8f5902;
background-color: null;
font-style: inherit;">NA</span>),</span>
<span id="cb1-15">          <span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">panel.background =</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">element_rect</span>(<span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">fill =</span> te_paper, <span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">colour =</span> <span class="cn" style="color: #8f5902;
background-color: null;
font-style: inherit;">NA</span>),</span>
<span id="cb1-16">          <span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">panel.grid.major =</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">element_line</span>(<span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">colour =</span> te_line, <span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">linewidth =</span> <span class="fl" style="color: #AD0000;
background-color: null;
font-style: inherit;">0.3</span>),</span>
<span id="cb1-17">          <span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">panel.grid.minor =</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">element_blank</span>(),</span>
<span id="cb1-18">          <span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">text             =</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">element_text</span>(<span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">colour =</span> te_body),</span>
<span id="cb1-19">          <span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">plot.title       =</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">element_text</span>(<span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">colour =</span> te_ink, <span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">face =</span> <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"bold"</span>),</span>
<span id="cb1-20">          <span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">plot.subtitle    =</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">element_text</span>(<span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">colour =</span> te_body),</span>
<span id="cb1-21">          <span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">axis.text        =</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">element_text</span>(<span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">colour =</span> te_body))</span>
<span id="cb1-22">}</span></code></pre></div></div>
</div>
<section id="the-index-the-envelope-and-the-storage-grid" class="level2">
<h2 id="the-index-the-envelope-and-the-storage-grid-h" class="anchored" data-anchor-id="the-index-the-envelope-and-the-storage-grid">The index, the envelope and the storage grid</h2>
<p>The window is a square of side 100 units holding 300 records, so a unit can be read as a tenth of a kilometre and the square as a ten kilometre atlas block. Storage on a grid of cell size h replaces every coordinate by the centre of the cell it falls in, which is what a grid reference, a rounded decimal degree or a site centroid does. Cell sizes of 1, 2, 5 and 10 units divide the side exactly, so every cell is whole. The clean-up keeps the first record at each distinct stored location.</p>
<p>The Clark-Evans index here is the naive one: observed mean nearest-neighbour distance over the complete spatial randomness expectation of one over twice the square root of the density, with no edge correction. That choice is deliberate, because it is what most scripts compute, and it has a consequence that has to be handled before anything else. Without an edge correction the index on random points sits above one, so a verdict read against the nominal value of one would be biased before the coordinates were touched. Every verdict below is read against a simulation envelope built with the same statistic: the 2.5 and 97.5 per cent quantiles of the index over 199 random patterns of the same size, with exact coordinates, which is the envelope an analyst would actually build.</p>
<div class="cell">
<div class="code-copy-outer-scaffold"><div class="sourceCode cell-code" id="cb2" style="background: #f1f3f5;"><pre class="sourceCode r code-with-copy"><code class="sourceCode r"><span id="cb2-1">side    <span class="ot" style="color: #003B4F;
background-color: null;
font-style: inherit;">&lt;-</span> <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">100</span></span>
<span id="cb2-2">area    <span class="ot" style="color: #003B4F;
background-color: null;
font-style: inherit;">&lt;-</span> side<span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">^</span><span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">2</span></span>
<span id="cb2-3">n_rec   <span class="ot" style="color: #003B4F;
background-color: null;
font-style: inherit;">&lt;-</span> <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">300</span></span>
<span id="cb2-4">n_env   <span class="ot" style="color: #003B4F;
background-color: null;
font-style: inherit;">&lt;-</span> <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">199</span></span>
<span id="cb2-5">cells_h <span class="ot" style="color: #003B4F;
background-color: null;
font-style: inherit;">&lt;-</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">c</span>(<span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">0</span>, <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">1</span>, <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">2</span>, <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">5</span>, <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">10</span>)</span>
<span id="cb2-6"></span>
<span id="cb2-7">nn_dist <span class="ot" style="color: #003B4F;
background-color: null;
font-style: inherit;">&lt;-</span> <span class="cf" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">function</span>(x, y) {</span>
<span id="cb2-8">  d2 <span class="ot" style="color: #003B4F;
background-color: null;
font-style: inherit;">&lt;-</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">outer</span>(x, x, <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"-"</span>)<span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">^</span><span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">2</span> <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">+</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">outer</span>(y, y, <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"-"</span>)<span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">^</span><span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">2</span></span>
<span id="cb2-9">  <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">diag</span>(d2) <span class="ot" style="color: #003B4F;
background-color: null;
font-style: inherit;">&lt;-</span> <span class="cn" style="color: #8f5902;
background-color: null;
font-style: inherit;">Inf</span></span>
<span id="cb2-10">  <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">sqrt</span>(d2[<span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">cbind</span>(<span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">seq_along</span>(x), <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">max.col</span>(<span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">-</span>d2, <span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">ties.method =</span> <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"first"</span>))])</span>
<span id="cb2-11">}</span>
<span id="cb2-12">ce_expect <span class="ot" style="color: #003B4F;
background-color: null;
font-style: inherit;">&lt;-</span> <span class="cf" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">function</span>(n_pts) <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">1</span> <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">/</span> (<span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">2</span> <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">*</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">sqrt</span>(n_pts <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">/</span> area))</span>
<span id="cb2-13">ce_index  <span class="ot" style="color: #003B4F;
background-color: null;
font-style: inherit;">&lt;-</span> <span class="cf" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">function</span>(x, y) <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">mean</span>(<span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">nn_dist</span>(x, y)) <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">/</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">ce_expect</span>(<span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">length</span>(x))</span>
<span id="cb2-14"></span>
<span id="cb2-15">csr_pts  <span class="ot" style="color: #003B4F;
background-color: null;
font-style: inherit;">&lt;-</span> <span class="cf" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">function</span>(n_pts) <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">list</span>(<span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">x =</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">runif</span>(n_pts, <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">0</span>, side), <span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">y =</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">runif</span>(n_pts, <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">0</span>, side))</span>
<span id="cb2-16">snap_pts <span class="ot" style="color: #003B4F;
background-color: null;
font-style: inherit;">&lt;-</span> <span class="cf" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">function</span>(pts, h) {</span>
<span id="cb2-17">  <span class="cf" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">if</span> (h <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">==</span> <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">0</span>) <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">return</span>(pts)</span>
<span id="cb2-18">  <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">list</span>(<span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">x =</span> (<span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">floor</span>(pts<span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">$</span>x <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">/</span> h) <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">+</span> <span class="fl" style="color: #AD0000;
background-color: null;
font-style: inherit;">0.5</span>) <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">*</span> h, <span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">y =</span> (<span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">floor</span>(pts<span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">$</span>y <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">/</span> h) <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">+</span> <span class="fl" style="color: #AD0000;
background-color: null;
font-style: inherit;">0.5</span>) <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">*</span> h)</span>
<span id="cb2-19">}</span>
<span id="cb2-20">one_per_cell <span class="ot" style="color: #003B4F;
background-color: null;
font-style: inherit;">&lt;-</span> <span class="cf" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">function</span>(pts) {</span>
<span id="cb2-21">  keep <span class="ot" style="color: #003B4F;
background-color: null;
font-style: inherit;">&lt;-</span> <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">!</span><span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">duplicated</span>(<span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">paste</span>(pts<span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">$</span>x, pts<span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">$</span>y))</span>
<span id="cb2-22">  <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">list</span>(<span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">x =</span> pts<span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">$</span>x[keep], <span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">y =</span> pts<span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">$</span>y[keep])</span>
<span id="cb2-23">}</span>
<span id="cb2-24"></span>
<span id="cb2-25">env_store <span class="ot" style="color: #003B4F;
background-color: null;
font-style: inherit;">&lt;-</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">new.env</span>()</span>
<span id="cb2-26">env_exact <span class="ot" style="color: #003B4F;
background-color: null;
font-style: inherit;">&lt;-</span> <span class="cf" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">function</span>(n_pts) {</span>
<span id="cb2-27">  key <span class="ot" style="color: #003B4F;
background-color: null;
font-style: inherit;">&lt;-</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">as.character</span>(n_pts)</span>
<span id="cb2-28">  <span class="cf" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">if</span> (<span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">is.null</span>(env_store[[key]])) {</span>
<span id="cb2-29">    sims <span class="ot" style="color: #003B4F;
background-color: null;
font-style: inherit;">&lt;-</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">replicate</span>(n_env, { q <span class="ot" style="color: #003B4F;
background-color: null;
font-style: inherit;">&lt;-</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">csr_pts</span>(n_pts); <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">ce_index</span>(q<span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">$</span>x, q<span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">$</span>y) })</span>
<span id="cb2-30">    env_store[[key]] <span class="ot" style="color: #003B4F;
background-color: null;
font-style: inherit;">&lt;-</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">quantile</span>(sims, <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">c</span>(<span class="fl" style="color: #AD0000;
background-color: null;
font-style: inherit;">0.025</span>, <span class="fl" style="color: #AD0000;
background-color: null;
font-style: inherit;">0.975</span>), <span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">names =</span> <span class="cn" style="color: #8f5902;
background-color: null;
font-style: inherit;">FALSE</span>)</span>
<span id="cb2-31">  }</span>
<span id="cb2-32">  env_store[[key]]</span>
<span id="cb2-33">}</span>
<span id="cb2-34">call_it <span class="ot" style="color: #003B4F;
background-color: null;
font-style: inherit;">&lt;-</span> <span class="cf" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">function</span>(r_val, band) {</span>
<span id="cb2-35">  <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">ifelse</span>(r_val <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">&lt;</span> band[<span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">1</span>], <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"clustered"</span>, <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">ifelse</span>(r_val <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">&gt;</span> band[<span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">2</span>], <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"regular"</span>, <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"random"</span>))</span>
<span id="cb2-36">}</span>
<span id="cb2-37"></span>
<span id="cb2-38"><span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">set.seed</span>(<span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">2501</span>)</span>
<span id="cb2-39">env_300  <span class="ot" style="color: #003B4F;
background-color: null;
font-style: inherit;">&lt;-</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">env_exact</span>(n_rec)</span>
<span id="cb2-40">mean_nn0 <span class="ot" style="color: #003B4F;
background-color: null;
font-style: inherit;">&lt;-</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">ce_expect</span>(n_rec)</span></code></pre></div></div>
</div>
<p>At this density the random expectation of the nearest-neighbour distance is 2.89 units, so a cell of 5 units is 1.7 times the typical spacing between records and a cell of 2 units is 0.69 times it. The envelope for 300 exact random points runs from 0.966 to 1.081. It is not centred on one, and that is the edge effect: a record near the boundary has its true nearest neighbour outside the window, unobserved, so its measured distance is too long.</p>
</section>
<section id="a-random-map-stored-on-a-grid-is-called-clustered" class="level2">
<h2 id="a-random-map-stored-on-a-grid-is-called-clustered-h" class="anchored" data-anchor-id="a-random-map-stored-on-a-grid-is-called-clustered">A random map, stored on a grid, is called clustered</h2>
<p>Each of 100 fresh random patterns is stored at every cell size, including a cell size of zero, which is the unrounded control. The index and the share of records whose nearest neighbour sits at distance exactly zero are recorded, and the verdict is read against the envelope above. The same stored pattern is then cleaned to one record per cell, the index is recomputed at the reduced number of records, and its verdict is read against a fresh envelope built at that reduced number.</p>
<div class="cell">
<div class="code-copy-outer-scaffold"><div class="sourceCode cell-code" id="cb3" style="background: #f1f3f5;"><pre class="sourceCode r code-with-copy"><code class="sourceCode r"><span id="cb3-1">n_draw <span class="ot" style="color: #003B4F;
background-color: null;
font-style: inherit;">&lt;-</span> <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">100</span></span>
<span id="cb3-2"><span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">set.seed</span>(<span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">3251</span>)</span>
<span id="cb3-3">sim_rows <span class="ot" style="color: #003B4F;
background-color: null;
font-style: inherit;">&lt;-</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">vector</span>(<span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"list"</span>, n_draw <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">*</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">length</span>(cells_h))</span>
<span id="cb3-4">row_i <span class="ot" style="color: #003B4F;
background-color: null;
font-style: inherit;">&lt;-</span> <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">0</span></span>
<span id="cb3-5"><span class="cf" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">for</span> (d_i <span class="cf" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">in</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">seq_len</span>(n_draw)) {</span>
<span id="cb3-6">  pts0 <span class="ot" style="color: #003B4F;
background-color: null;
font-style: inherit;">&lt;-</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">csr_pts</span>(n_rec)</span>
<span id="cb3-7">  <span class="cf" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">for</span> (h <span class="cf" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">in</span> cells_h) {</span>
<span id="cb3-8">    stored  <span class="ot" style="color: #003B4F;
background-color: null;
font-style: inherit;">&lt;-</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">snap_pts</span>(pts0, h)</span>
<span id="cb3-9">    nn_st   <span class="ot" style="color: #003B4F;
background-color: null;
font-style: inherit;">&lt;-</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">nn_dist</span>(stored<span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">$</span>x, stored<span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">$</span>y)</span>
<span id="cb3-10">    r_raw   <span class="ot" style="color: #003B4F;
background-color: null;
font-style: inherit;">&lt;-</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">mean</span>(nn_st) <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">/</span> mean_nn0</span>
<span id="cb3-11">    cleaned <span class="ot" style="color: #003B4F;
background-color: null;
font-style: inherit;">&lt;-</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">one_per_cell</span>(stored)</span>
<span id="cb3-12">    n_kept  <span class="ot" style="color: #003B4F;
background-color: null;
font-style: inherit;">&lt;-</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">length</span>(cleaned<span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">$</span>x)</span>
<span id="cb3-13">    nn_cl   <span class="ot" style="color: #003B4F;
background-color: null;
font-style: inherit;">&lt;-</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">nn_dist</span>(cleaned<span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">$</span>x, cleaned<span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">$</span>y)</span>
<span id="cb3-14">    r_clean <span class="ot" style="color: #003B4F;
background-color: null;
font-style: inherit;">&lt;-</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">mean</span>(nn_cl) <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">/</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">ce_expect</span>(n_kept)</span>
<span id="cb3-15">    row_i <span class="ot" style="color: #003B4F;
background-color: null;
font-style: inherit;">&lt;-</span> row_i <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">+</span> <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">1</span></span>
<span id="cb3-16">    sim_rows[[row_i]] <span class="ot" style="color: #003B4F;
background-color: null;
font-style: inherit;">&lt;-</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">data.frame</span>(</span>
<span id="cb3-17">      <span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">draw =</span> d_i, <span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">h =</span> h, <span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">r_raw =</span> r_raw, <span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">zero_share =</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">mean</span>(nn_st <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">==</span> <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">0</span>),</span>
<span id="cb3-18">      <span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">raw_call =</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">call_it</span>(r_raw, env_300), <span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">n_kept =</span> n_kept, <span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">r_clean =</span> r_clean,</span>
<span id="cb3-19">      <span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">min_nn_clean =</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">min</span>(nn_cl), <span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">clean_call =</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">call_it</span>(r_clean, <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">env_exact</span>(n_kept)),</span>
<span id="cb3-20">      <span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">clean_call_300 =</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">call_it</span>(r_clean, env_300))</span>
<span id="cb3-21">  }</span>
<span id="cb3-22">}</span>
<span id="cb3-23">sim_res <span class="ot" style="color: #003B4F;
background-color: null;
font-style: inherit;">&lt;-</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">do.call</span>(rbind, sim_rows)</span>
<span id="cb3-24"></span>
<span id="cb3-25">zero_theory <span class="ot" style="color: #003B4F;
background-color: null;
font-style: inherit;">&lt;-</span> <span class="cf" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">function</span>(h) <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">ifelse</span>(h <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">==</span> <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">0</span>, <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">0</span>, <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">1</span> <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">-</span> (<span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">1</span> <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">-</span> h<span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">^</span><span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">2</span> <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">/</span> area)<span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">^</span>(n_rec <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">-</span> <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">1</span>))</span>
<span id="cb3-26">kept_theory <span class="ot" style="color: #003B4F;
background-color: null;
font-style: inherit;">&lt;-</span> <span class="cf" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">function</span>(h) <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">ifelse</span>(h <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">==</span> <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">0</span>, n_rec, (area <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">/</span> h<span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">^</span><span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">2</span>) <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">*</span> (<span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">1</span> <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">-</span> (<span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">1</span> <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">-</span> h<span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">^</span><span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">2</span> <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">/</span> area)<span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">^</span>n_rec))</span>
<span id="cb3-27"></span>
<span id="cb3-28">share_se <span class="ot" style="color: #003B4F;
background-color: null;
font-style: inherit;">&lt;-</span> <span class="cf" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">function</span>(p) <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">sqrt</span>(p <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">*</span> (<span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">1</span> <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">-</span> p) <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">/</span> n_draw)</span>
<span id="cb3-29">by_h <span class="ot" style="color: #003B4F;
background-color: null;
font-style: inherit;">&lt;-</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">do.call</span>(rbind, <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">lapply</span>(cells_h, <span class="cf" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">function</span>(h) {</span>
<span id="cb3-30">  s <span class="ot" style="color: #003B4F;
background-color: null;
font-style: inherit;">&lt;-</span> sim_res[sim_res<span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">$</span>h <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">==</span> h, ]</span>
<span id="cb3-31">  <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">data.frame</span>(</span>
<span id="cb3-32">    <span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">h =</span> h, <span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">r_raw =</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">median</span>(s<span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">$</span>r_raw), <span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">r_raw_lo =</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">min</span>(s<span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">$</span>r_raw), <span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">r_raw_hi =</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">max</span>(s<span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">$</span>r_raw),</span>
<span id="cb3-33">    <span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">zero_share =</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">mean</span>(s<span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">$</span>zero_share), <span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">zero_pred =</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">zero_theory</span>(h),</span>
<span id="cb3-34">    <span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">raw_clustered =</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">mean</span>(s<span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">$</span>raw_call <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">==</span> <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"clustered"</span>), <span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">raw_regular =</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">mean</span>(s<span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">$</span>raw_call <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">==</span> <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"regular"</span>),</span>
<span id="cb3-35">    <span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">n_kept =</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">mean</span>(s<span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">$</span>n_kept), <span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">kept_pred =</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">kept_theory</span>(h),</span>
<span id="cb3-36">    <span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">r_clean =</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">median</span>(s<span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">$</span>r_clean), <span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">r_clean_lo =</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">min</span>(s<span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">$</span>r_clean), <span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">r_clean_hi =</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">max</span>(s<span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">$</span>r_clean),</span>
<span id="cb3-37">    <span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">clean_regular =</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">mean</span>(s<span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">$</span>clean_call <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">==</span> <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"regular"</span>),</span>
<span id="cb3-38">    <span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">clean_clustered =</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">mean</span>(s<span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">$</span>clean_call <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">==</span> <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"clustered"</span>),</span>
<span id="cb3-39">    <span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">clean_regular_300 =</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">mean</span>(s<span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">$</span>clean_call_300 <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">==</span> <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"regular"</span>))</span>
<span id="cb3-40">}))</span>
<span id="cb3-41">row_of <span class="ot" style="color: #003B4F;
background-color: null;
font-style: inherit;">&lt;-</span> <span class="cf" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">function</span>(h) by_h[by_h<span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">$</span>h <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">==</span> h, ]</span>
<span id="cb3-42">ctl <span class="ot" style="color: #003B4F;
background-color: null;
font-style: inherit;">&lt;-</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">row_of</span>(<span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">0</span>); h1 <span class="ot" style="color: #003B4F;
background-color: null;
font-style: inherit;">&lt;-</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">row_of</span>(<span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">1</span>); h2 <span class="ot" style="color: #003B4F;
background-color: null;
font-style: inherit;">&lt;-</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">row_of</span>(<span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">2</span>); h5 <span class="ot" style="color: #003B4F;
background-color: null;
font-style: inherit;">&lt;-</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">row_of</span>(<span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">5</span>); h10 <span class="ot" style="color: #003B4F;
background-color: null;
font-style: inherit;">&lt;-</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">row_of</span>(<span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">10</span>)</span>
<span id="cb3-43">ctl_out <span class="ot" style="color: #003B4F;
background-color: null;
font-style: inherit;">&lt;-</span> ctl<span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">$</span>raw_clustered <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">+</span> ctl<span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">$</span>raw_regular</span>
<span id="cb3-44">of_n <span class="ot" style="color: #003B4F;
background-color: null;
font-style: inherit;">&lt;-</span> <span class="cf" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">function</span>(p) <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">sprintf</span>(<span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"%d of %d"</span>, <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">round</span>(p <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">*</span> n_draw), n_draw)</span></code></pre></div></div>
</div>
<div class="cell">
<div class="code-copy-outer-scaffold"><div class="sourceCode cell-code" id="cb4" style="background: #f1f3f5;"><pre class="sourceCode r code-with-copy"><code class="sourceCode r"><span id="cb4-1">tab_show <span class="ot" style="color: #003B4F;
background-color: null;
font-style: inherit;">&lt;-</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">data.frame</span>(</span>
<span id="cb4-2">  <span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">cell =</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">ifelse</span>(by_h<span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">$</span>h <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">==</span> <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">0</span>, <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"0 (unrounded control)"</span>, <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">sprintf</span>(<span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"%d"</span>, by_h<span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">$</span>h)),</span>
<span id="cb4-3">  <span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">R_stored =</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">sprintf</span>(<span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"%.3f (%.3f to %.3f)"</span>, by_h<span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">$</span>r_raw, by_h<span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">$</span>r_raw_lo, by_h<span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">$</span>r_raw_hi),</span>
<span id="cb4-4">  <span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">zero_nn =</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">sprintf</span>(<span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"%.3f"</span>, by_h<span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">$</span>zero_share),</span>
<span id="cb4-5">  <span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">called_clustered =</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">sprintf</span>(<span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"%.2f"</span>, by_h<span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">$</span>raw_clustered),</span>
<span id="cb4-6">  <span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">kept =</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">sprintf</span>(<span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"%.1f"</span>, by_h<span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">$</span>n_kept),</span>
<span id="cb4-7">  <span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">R_one_per_cell =</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">sprintf</span>(<span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"%.3f (%.3f to %.3f)"</span>, by_h<span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">$</span>r_clean, by_h<span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">$</span>r_clean_lo, by_h<span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">$</span>r_clean_hi),</span>
<span id="cb4-8">  <span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">called_regular =</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">sprintf</span>(<span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"%.2f"</span>, by_h<span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">$</span>clean_regular))</span>
<span id="cb4-9">knitr<span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">::</span><span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">kable</span>(tab_show, <span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">align =</span> <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"lllrrlr"</span>,</span>
<span id="cb4-10">             <span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">col.names =</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">c</span>(<span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"cell size"</span>, <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"R as stored, median (range)"</span>, <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"share of zero NN distances"</span>,</span>
<span id="cb4-11">                           <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"share called clustered"</span>, <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"records kept"</span>, <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"R one per cell, median (range)"</span>,</span>
<span id="cb4-12">                           <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"share called regular"</span>))</span></code></pre></div></div>
<div class="cell-output-display">
<table class="caption-top table table-sm table-striped small">
<colgroup>
<col style="width: 13%">
<col style="width: 16%">
<col style="width: 16%">
<col style="width: 13%">
<col style="width: 7%">
<col style="width: 18%">
<col style="width: 12%">
</colgroup>
<thead>
<tr class="header">
<th style="text-align: left;">cell size</th>
<th style="text-align: left;">R as stored, median (range)</th>
<th style="text-align: left;">share of zero NN distances</th>
<th style="text-align: right;">share called clustered</th>
<th style="text-align: right;">records kept</th>
<th style="text-align: left;">R one per cell, median (range)</th>
<th style="text-align: right;">share called regular</th>
</tr>
</thead>
<tbody>
<tr class="odd">
<td style="text-align: left;">0 (unrounded control)</td>
<td style="text-align: left;">1.029 (0.959 to 1.098)</td>
<td style="text-align: left;">0.000</td>
<td style="text-align: right;">0.02</td>
<td style="text-align: right;">300.0</td>
<td style="text-align: left;">1.029 (0.959 to 1.098)</td>
<td style="text-align: right;">0.05</td>
</tr>
<tr class="even">
<td style="text-align: left;">1</td>
<td style="text-align: left;">1.026 (0.962 to 1.096)</td>
<td style="text-align: left;">0.027</td>
<td style="text-align: right;">0.05</td>
<td style="text-align: right;">295.9</td>
<td style="text-align: left;">1.048 (0.985 to 1.120)</td>
<td style="text-align: right;">0.11</td>
</tr>
<tr class="odd">
<td style="text-align: left;">2</td>
<td style="text-align: left;">1.019 (0.931 to 1.085)</td>
<td style="text-align: left;">0.113</td>
<td style="text-align: right;">0.07</td>
<td style="text-align: right;">282.8</td>
<td style="text-align: left;">1.115 (1.051 to 1.187)</td>
<td style="text-align: right;">0.81</td>
</tr>
<tr class="even">
<td style="text-align: left;">5</td>
<td style="text-align: left;">0.853 (0.719 to 0.989)</td>
<td style="text-align: left;">0.521</td>
<td style="text-align: right;">0.99</td>
<td style="text-align: right;">212.2</td>
<td style="text-align: left;">1.500 (1.441 to 1.538)</td>
<td style="text-align: right;">1.00</td>
</tr>
<tr class="odd">
<td style="text-align: left;">10</td>
<td style="text-align: left;">0.162 (0.092 to 0.277)</td>
<td style="text-align: left;">0.952</td>
<td style="text-align: right;">1.00</td>
<td style="text-align: right;">94.9</td>
<td style="text-align: left;">1.949 (1.887 to 1.990)</td>
<td style="text-align: right;">1.00</td>
</tr>
</tbody>
</table>
</div>
</div>
<div class="cell">
<div class="code-copy-outer-scaffold"><div class="sourceCode cell-code" id="cb5" style="background: #f1f3f5;"><pre class="sourceCode r code-with-copy"><code class="sourceCode r"><span id="cb5-1"><span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">set.seed</span>(<span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">9090</span>)</span>
<span id="cb5-2">env_check    <span class="ot" style="color: #003B4F;
background-color: null;
font-style: inherit;">&lt;-</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">replicate</span>(<span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">2000</span>, { q <span class="ot" style="color: #003B4F;
background-color: null;
font-style: inherit;">&lt;-</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">csr_pts</span>(n_rec); <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">ce_index</span>(q<span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">$</span>x, q<span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">$</span>y) })</span>
<span id="cb5-3">env_true_out <span class="ot" style="color: #003B4F;
background-color: null;
font-style: inherit;">&lt;-</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">mean</span>(env_check <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">&lt;</span> env_300[<span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">1</span>] <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">|</span> env_check <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">&gt;</span> env_300[<span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">2</span>])</span></code></pre></div></div>
</div>
<p>The control row behaves as it should. Unrounded random patterns give a median index of 1.029, inside their own envelope, and 7 of 100 draws fall outside it, against a nominal five in a hundred (Monte Carlo standard error 0.022 on the share). The excess is the envelope itself: against 2000 further random patterns of 300 records, this 199-pattern band excludes a share of 0.070, not 0.05, because a quantile taken from 199 patterns is itself noisy and this one came out slightly narrow. The stored-record verdicts at every cell size are read against the same band and carry the same small excess. With that allowed for, the statistic and the envelope agree with each other before any storage grid is applied.</p>
<p>At a cell of 5 units the median index of the stored records is 0.853 and 99 of 100 draws are called clustered. The reason is in the next column: 0.521 of the records have a nearest neighbour at distance exactly zero, because they share a cell with at least one other record. At a cell of 10 units the zero share is 0.952, the median index collapses to 0.162 and 100 of 100 draws are called clustered. At 1 and 2 units the stored records are still read almost correctly: 5 of 100 and 7 of 100 draws are called clustered, against 2 of 100 for the control and a nominal 2.5 in a hundred on that side, so a small excess at most (standard error 0.026 at 2 units), and nothing like the cell of 5, although 0.113 of records already have a zero distance at 2 units.</p>
<p>The zero share is the one quantity here that follows from a formula. A record has a zero nearest-neighbour distance exactly when at least one of the other 299 records falls in its cell, so its expected share is one minus (1 minus h squared over the area) to the power 299. That gives 0.113, 0.527 and 0.950 at 2, 5 and 10 units, against simulated shares of 0.113, 0.521 and 0.952. The formula calibrates the snap; it does not give the index, and it does not give the verdict, which also depends on how the non-zero distances shift and on the envelope.</p>
<div class="cell">
<div class="code-copy-outer-scaffold"><div class="sourceCode cell-code" id="cb6" style="background: #f1f3f5;"><pre class="sourceCode r code-with-copy"><code class="sourceCode r"><span id="cb6-1">h_curve <span class="ot" style="color: #003B4F;
background-color: null;
font-style: inherit;">&lt;-</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">data.frame</span>(<span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">h =</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">seq</span>(<span class="fl" style="color: #AD0000;
background-color: null;
font-style: inherit;">0.25</span>, <span class="fl" style="color: #AD0000;
background-color: null;
font-style: inherit;">10.5</span>, <span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">by =</span> <span class="fl" style="color: #AD0000;
background-color: null;
font-style: inherit;">0.05</span>))</span>
<span id="cb6-2">h_curve<span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">$</span>zero <span class="ot" style="color: #003B4F;
background-color: null;
font-style: inherit;">&lt;-</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">zero_theory</span>(h_curve<span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">$</span>h)</span>
<span id="cb6-3">h_curve<span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">$</span>kept <span class="ot" style="color: #003B4F;
background-color: null;
font-style: inherit;">&lt;-</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">kept_theory</span>(h_curve<span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">$</span>h)</span>
<span id="cb6-4">pts_cal <span class="ot" style="color: #003B4F;
background-color: null;
font-style: inherit;">&lt;-</span> by_h[by_h<span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">$</span>h <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">&gt;</span> <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">0</span>, ]</span>
<span id="cb6-5">cal_zero <span class="ot" style="color: #003B4F;
background-color: null;
font-style: inherit;">&lt;-</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">ggplot</span>(h_curve, <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">aes</span>(h, zero)) <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">+</span></span>
<span id="cb6-6">  <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">geom_line</span>(<span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">colour =</span> te_gold, <span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">linewidth =</span> <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">1</span>) <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">+</span></span>
<span id="cb6-7">  <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">geom_point</span>(<span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">data =</span> pts_cal, <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">aes</span>(h, zero_share), <span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">colour =</span> te_forest, <span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">size =</span> <span class="fl" style="color: #AD0000;
background-color: null;
font-style: inherit;">2.8</span>) <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">+</span></span>
<span id="cb6-8">  <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">labs</span>(<span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">x =</span> <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"cell size (units)"</span>, <span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">y =</span> <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"share of zero NN distances"</span>,</span>
<span id="cb6-9">       <span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">title =</span> <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"Records sharing a cell"</span>) <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">+</span></span>
<span id="cb6-10">  <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">theme_datasheet</span>()</span>
<span id="cb6-11">cal_kept <span class="ot" style="color: #003B4F;
background-color: null;
font-style: inherit;">&lt;-</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">ggplot</span>(h_curve, <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">aes</span>(h, kept)) <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">+</span></span>
<span id="cb6-12">  <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">geom_line</span>(<span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">colour =</span> te_gold, <span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">linewidth =</span> <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">1</span>) <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">+</span></span>
<span id="cb6-13">  <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">geom_point</span>(<span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">data =</span> pts_cal, <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">aes</span>(h, n_kept), <span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">colour =</span> te_rust, <span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">size =</span> <span class="fl" style="color: #AD0000;
background-color: null;
font-style: inherit;">2.8</span>) <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">+</span></span>
<span id="cb6-14">  <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">labs</span>(<span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">x =</span> <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"cell size (units)"</span>, <span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">y =</span> <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"records kept after cleaning"</span>,</span>
<span id="cb6-15">       <span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">title =</span> <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"Records left by one per cell"</span>) <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">+</span></span>
<span id="cb6-16">  <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">theme_datasheet</span>()</span>
<span id="cb6-17">(cal_zero <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">|</span> cal_kept) <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">+</span></span>
<span id="cb6-18">  <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">plot_annotation</span>(<span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">subtitle =</span> <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"gold line: occupancy formula; points: mean of 100 simulated patterns"</span>,</span>
<span id="cb6-19">                  <span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">theme =</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">theme_datasheet</span>())</span></code></pre></div></div>
<div class="cell-output-display">
<div id="fig-zero" class="quarto-float quarto-figure quarto-figure-center anchored" alt="Two side-by-side panels on warm off-white paper. The left panel, titled Records sharing a cell, plots the share of zero nearest-neighbour distances against cell size from zero to ten units: a gold S-shaped curve rises from zero through about one half at five units to about ninety-five hundredths at ten, and four dark green points at cell sizes one, two, five and ten sit on the curve. The right panel, titled Records left by one per cell, plots records kept after cleaning: a gold curve falls from three hundred at the left to under one hundred at ten units, and four red points at the same cell sizes, near two hundred and ninety-six, two hundred and eighty-three, two hundred and twelve and ninety-five, sit on it.">
<figure class="quarto-float quarto-float-fig figure">
<div aria-describedby="fig-zero-caption-0ceaefa1-69ba-4598-a22c-09a6ac19f8ca">
<img src="https://tidyecology.com/posts/snapped-coordinates-and-clustering/index_files/figure-html/fig-zero-1.png" class="img-fluid figure-img" alt="Two side-by-side panels on warm off-white paper. The left panel, titled Records sharing a cell, plots the share of zero nearest-neighbour distances against cell size from zero to ten units: a gold S-shaped curve rises from zero through about one half at five units to about ninety-five hundredths at ten, and four dark green points at cell sizes one, two, five and ten sit on the curve. The right panel, titled Records left by one per cell, plots records kept after cleaning: a gold curve falls from three hundred at the left to under one hundred at ten units, and four red points at the same cell sizes, near two hundred and ninety-six, two hundred and eighty-three, two hundred and twelve and ninety-five, sit on it." width="672">
</div>
<figcaption class="quarto-float-caption-bottom quarto-float-caption quarto-float-fig" id="fig-zero-caption-0ceaefa1-69ba-4598-a22c-09a6ac19f8ca">
Figure&nbsp;1: Calibration of the snap: the share of records with a zero nearest-neighbour distance and the number of records left after cleaning, simulated against the occupancy formula.
</figcaption>
</figure>
</div>
</div>
</div>
<div class="cell">
<div class="code-copy-outer-scaffold"><div class="sourceCode cell-code" id="cb7" style="background: #f1f3f5;"><pre class="sourceCode r code-with-copy"><code class="sourceCode r"><span id="cb7-1"><span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">set.seed</span>(<span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">77</span>)</span>
<span id="cb7-2">ex_csr   <span class="ot" style="color: #003B4F;
background-color: null;
font-style: inherit;">&lt;-</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">csr_pts</span>(n_rec)</span>
<span id="cb7-3">thomas_pts <span class="ot" style="color: #003B4F;
background-color: null;
font-style: inherit;">&lt;-</span> <span class="cf" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">function</span>(<span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">n_parent =</span> <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">30</span>, <span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">per_parent =</span> <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">10</span>, <span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">spread =</span> <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">3</span>) {</span>
<span id="cb7-4">  px <span class="ot" style="color: #003B4F;
background-color: null;
font-style: inherit;">&lt;-</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">runif</span>(n_parent, <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">0</span>, side); py <span class="ot" style="color: #003B4F;
background-color: null;
font-style: inherit;">&lt;-</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">runif</span>(n_parent, <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">0</span>, side)</span>
<span id="cb7-5">  x <span class="ot" style="color: #003B4F;
background-color: null;
font-style: inherit;">&lt;-</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">rep</span>(px, <span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">each =</span> per_parent) <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">+</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">rnorm</span>(n_parent <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">*</span> per_parent, <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">0</span>, spread)</span>
<span id="cb7-6">  y <span class="ot" style="color: #003B4F;
background-color: null;
font-style: inherit;">&lt;-</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">rep</span>(py, <span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">each =</span> per_parent) <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">+</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">rnorm</span>(n_parent <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">*</span> per_parent, <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">0</span>, spread)</span>
<span id="cb7-7">  inside <span class="ot" style="color: #003B4F;
background-color: null;
font-style: inherit;">&lt;-</span> x <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">&gt;</span> <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">0</span> <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">&amp;</span> x <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">&lt;</span> side <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">&amp;</span> y <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">&gt;</span> <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">0</span> <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">&amp;</span> y <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">&lt;</span> side</span>
<span id="cb7-8">  <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">list</span>(<span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">x =</span> x[inside], <span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">y =</span> y[inside])</span>
<span id="cb7-9">}</span>
<span id="cb7-10">ex_thomas <span class="ot" style="color: #003B4F;
background-color: null;
font-style: inherit;">&lt;-</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">thomas_pts</span>()</span>
<span id="cb7-11"></span>
<span id="cb7-12">stage_frame <span class="ot" style="color: #003B4F;
background-color: null;
font-style: inherit;">&lt;-</span> <span class="cf" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">function</span>(pts, lab_pattern) {</span>
<span id="cb7-13">  stored  <span class="ot" style="color: #003B4F;
background-color: null;
font-style: inherit;">&lt;-</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">snap_pts</span>(pts, <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">5</span>)</span>
<span id="cb7-14">  key     <span class="ot" style="color: #003B4F;
background-color: null;
font-style: inherit;">&lt;-</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">paste</span>(stored<span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">$</span>x, stored<span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">$</span>y)</span>
<span id="cb7-15">  counts  <span class="ot" style="color: #003B4F;
background-color: null;
font-style: inherit;">&lt;-</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">as.vector</span>(<span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">table</span>(key)[key])</span>
<span id="cb7-16">  cleaned <span class="ot" style="color: #003B4F;
background-color: null;
font-style: inherit;">&lt;-</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">one_per_cell</span>(stored)</span>
<span id="cb7-17">  <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">rbind</span>(</span>
<span id="cb7-18">    <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">data.frame</span>(<span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">x =</span> pts<span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">$</span>x, <span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">y =</span> pts<span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">$</span>y, <span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">n_here =</span> <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">1</span>, <span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">stage =</span> <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"exact coordinates"</span>),</span>
<span id="cb7-19">    <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">data.frame</span>(<span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">x =</span> stored<span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">$</span>x, <span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">y =</span> stored<span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">$</span>y, <span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">n_here =</span> counts, <span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">stage =</span> <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"stored on a 5 unit grid"</span>)[<span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">!</span><span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">duplicated</span>(key), ],</span>
<span id="cb7-20">    <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">data.frame</span>(<span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">x =</span> cleaned<span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">$</span>x, <span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">y =</span> cleaned<span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">$</span>y, <span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">n_here =</span> <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">1</span>, <span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">stage =</span> <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"one record per cell"</span>)) <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">|&gt;</span></span>
<span id="cb7-21">    <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">transform</span>(<span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">pattern =</span> lab_pattern)</span>
<span id="cb7-22">}</span>
<span id="cb7-23">map_df <span class="ot" style="color: #003B4F;
background-color: null;
font-style: inherit;">&lt;-</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">rbind</span>(<span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">stage_frame</span>(ex_csr, <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"random"</span>), <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">stage_frame</span>(ex_thomas, <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"clustered (Thomas)"</span>))</span>
<span id="cb7-24">map_df<span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">$</span>stage   <span class="ot" style="color: #003B4F;
background-color: null;
font-style: inherit;">&lt;-</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">factor</span>(map_df<span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">$</span>stage, <span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">levels =</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">c</span>(<span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"exact coordinates"</span>, <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"stored on a 5 unit grid"</span>,</span>
<span id="cb7-25">                                                  <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"one record per cell"</span>))</span>
<span id="cb7-26">map_df<span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">$</span>pattern <span class="ot" style="color: #003B4F;
background-color: null;
font-style: inherit;">&lt;-</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">factor</span>(map_df<span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">$</span>pattern, <span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">levels =</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">c</span>(<span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"random"</span>, <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"clustered (Thomas)"</span>))</span></code></pre></div></div>
</div>
<div class="cell">
<div class="code-copy-outer-scaffold"><div class="sourceCode cell-code" id="cb8" style="background: #f1f3f5;"><pre class="sourceCode r code-with-copy"><code class="sourceCode r"><span id="cb8-1"><span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">ggplot</span>(map_df, <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">aes</span>(x, y)) <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">+</span></span>
<span id="cb8-2">  <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">geom_point</span>(<span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">aes</span>(<span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">size =</span> n_here), <span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">colour =</span> te_forest, <span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">alpha =</span> <span class="fl" style="color: #AD0000;
background-color: null;
font-style: inherit;">0.75</span>, <span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">stroke =</span> <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">0</span>) <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">+</span></span>
<span id="cb8-3">  <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">scale_size_area</span>(<span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">max_size =</span> <span class="fl" style="color: #AD0000;
background-color: null;
font-style: inherit;">3.2</span>, <span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">breaks =</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">c</span>(<span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">1</span>, <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">3</span>, <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">6</span>), <span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">name =</span> <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"records at the point"</span>) <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">+</span></span>
<span id="cb8-4">  <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">facet_grid</span>(pattern <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">~</span> stage) <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">+</span></span>
<span id="cb8-5">  <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">coord_equal</span>(<span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">xlim =</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">c</span>(<span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">0</span>, side), <span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">ylim =</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">c</span>(<span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">0</span>, side), <span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">expand =</span> <span class="cn" style="color: #8f5902;
background-color: null;
font-style: inherit;">FALSE</span>) <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">+</span></span>
<span id="cb8-6">  <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">labs</span>(<span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">x =</span> <span class="cn" style="color: #8f5902;
background-color: null;
font-style: inherit;">NULL</span>, <span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">y =</span> <span class="cn" style="color: #8f5902;
background-color: null;
font-style: inherit;">NULL</span>, <span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">title =</span> <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"What the storage grid does to the map"</span>) <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">+</span></span>
<span id="cb8-7">  <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">theme_datasheet</span>() <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">+</span></span>
<span id="cb8-8">  <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">theme</span>(<span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">axis.text =</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">element_blank</span>(), <span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">legend.position =</span> <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"bottom"</span>,</span>
<span id="cb8-9">        <span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">panel.border =</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">element_rect</span>(<span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">colour =</span> te_line, <span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">fill =</span> <span class="cn" style="color: #8f5902;
background-color: null;
font-style: inherit;">NA</span>),</span>
<span id="cb8-10">        <span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">strip.text =</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">element_text</span>(<span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">colour =</span> te_ink))</span></code></pre></div></div>
<div class="cell-output-display">
<div id="fig-maps" class="quarto-float quarto-figure quarto-figure-center anchored" alt="Six square map panels on warm off-white paper in two rows and three columns. The top row is a random pattern and the bottom row a clustered Thomas pattern; the columns are exact coordinates, the same records stored on a 5 unit grid, and one record per cell. In the exact column the random points are scattered evenly and the clustered points form about thirty tight groups. In the stored column every point sits on a regular grid of positions and larger dots mark positions shared by several records, with the largest dots in the clustered row. In the one record per cell column all dots are the same small size on the grid; the random row fills the grid thinly and evenly, while the clustered row shows blocks of adjacent occupied cells separated by empty areas.">
<figure class="quarto-float quarto-float-fig figure">
<div aria-describedby="fig-maps-caption-0ceaefa1-69ba-4598-a22c-09a6ac19f8ca">
<img src="https://tidyecology.com/posts/snapped-coordinates-and-clustering/index_files/figure-html/fig-maps-1.png" class="img-fluid figure-img" alt="Six square map panels on warm off-white paper in two rows and three columns. The top row is a random pattern and the bottom row a clustered Thomas pattern; the columns are exact coordinates, the same records stored on a 5 unit grid, and one record per cell. In the exact column the random points are scattered evenly and the clustered points form about thirty tight groups. In the stored column every point sits on a regular grid of positions and larger dots mark positions shared by several records, with the largest dots in the clustered row. In the one record per cell column all dots are the same small size on the grid; the random row fills the grid thinly and evenly, while the clustered row shows blocks of adjacent occupied cells separated by empty areas." width="672">
</div>
<figcaption class="quarto-float-caption-bottom quarto-float-caption quarto-float-fig" id="fig-maps-caption-0ceaefa1-69ba-4598-a22c-09a6ac19f8ca">
Figure&nbsp;2: One random and one clustered pattern at three stages: exact coordinates, stored on a 5 unit grid (symbol size shows how many records share a cell), and one record per occupied cell.
</figcaption>
</figure>
</div>
</div>
</div>
</section>
<section id="one-record-per-cell-turns-the-verdict-round" class="level2">
<h2 id="one-record-per-cell-turns-the-verdict-round-h" class="anchored" data-anchor-id="one-record-per-cell-turns-the-verdict-round">One record per cell turns the verdict round</h2>
<p>Cleaning the same stored records to one per cell reverses the call. At 5 units the number of records falls from 300 to 212.2 on average (the occupancy formula, the number of cells times the chance a cell holds at least one record, gives 211.2), the median index rises to 1.500, and 100 of 100 draws are called regular. At 10 units, with 94.9 records kept, the median is 1.949 and 100 of 100 draws are called regular.</p>
<div class="cell">
<div class="code-copy-outer-scaffold"><div class="sourceCode cell-code" id="cb9" style="background: #f1f3f5;"><pre class="sourceCode r code-with-copy"><code class="sourceCode r"><span id="cb9-1">lower_bound <span class="ot" style="color: #003B4F;
background-color: null;
font-style: inherit;">&lt;-</span> <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">2</span> <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">*</span> sim_res<span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">$</span>h <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">*</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">sqrt</span>(sim_res<span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">$</span>n_kept <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">/</span> area)</span>
<span id="cb9-2">above_bound <span class="ot" style="color: #003B4F;
background-color: null;
font-style: inherit;">&lt;-</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">mean</span>((sim_res<span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">$</span>r_clean <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">&gt;=</span> lower_bound <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">-</span> <span class="fl" style="color: #AD0000;
background-color: null;
font-style: inherit;">1e-9</span>)[sim_res<span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">$</span>h <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">&gt;</span> <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">0</span>])</span>
<span id="cb9-3">bound_h5    <span class="ot" style="color: #003B4F;
background-color: null;
font-style: inherit;">&lt;-</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">median</span>(lower_bound[sim_res<span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">$</span>h <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">==</span> <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">5</span>])</span>
<span id="cb9-4">bound_h10   <span class="ot" style="color: #003B4F;
background-color: null;
font-style: inherit;">&lt;-</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">median</span>(lower_bound[sim_res<span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">$</span>h <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">==</span> <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">10</span>])</span>
<span id="cb9-5">min_nn_h5   <span class="ot" style="color: #003B4F;
background-color: null;
font-style: inherit;">&lt;-</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">min</span>(sim_res<span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">$</span>min_nn_clean[sim_res<span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">$</span>h <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">==</span> <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">5</span>])</span>
<span id="cb9-6">env_hi_h2   <span class="ot" style="color: #003B4F;
background-color: null;
font-style: inherit;">&lt;-</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">median</span>(<span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">vapply</span>(sim_res<span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">$</span>n_kept[sim_res<span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">$</span>h <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">==</span> <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">2</span>], <span class="cf" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">function</span>(k) <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">env_exact</span>(k)[<span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">2</span>], <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">0</span>))</span>
<span id="cb9-7">bound_h1    <span class="ot" style="color: #003B4F;
background-color: null;
font-style: inherit;">&lt;-</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">median</span>(lower_bound[sim_res<span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">$</span>h <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">==</span> <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">1</span>])</span>
<span id="cb9-8">bound_h2    <span class="ot" style="color: #003B4F;
background-color: null;
font-style: inherit;">&lt;-</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">median</span>(lower_bound[sim_res<span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">$</span>h <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">==</span> <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">2</span>])</span>
<span id="cb9-9">at_floor_h10 <span class="ot" style="color: #003B4F;
background-color: null;
font-style: inherit;">&lt;-</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">mean</span>(<span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">abs</span>(sim_res<span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">$</span>r_clean <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">-</span> lower_bound)[sim_res<span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">$</span>h <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">==</span> <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">10</span>] <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">&lt;</span> <span class="fl" style="color: #AD0000;
background-color: null;
font-style: inherit;">1e-9</span>)</span>
<span id="cb9-10">short_nn_h2 <span class="ot" style="color: #003B4F;
background-color: null;
font-style: inherit;">&lt;-</span> <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">1</span> <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">-</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">exp</span>(<span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">-</span>pi <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">*</span> h2<span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">$</span>n_kept <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">/</span> area <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">*</span> <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">2</span><span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">^</span><span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">2</span>)</span></code></pre></div></div>
</div>
<p>The mechanism is geometric. After the clean-up every record sits at the centre of a different cell, so the pattern is a subset of a lattice and no two records can be closer than one cell width: the smallest nearest-neighbour distance in any cleaned 5 unit pattern is 5.00. The index therefore cannot fall below the cell size over the random expectation at the reduced count, two h times the square root of the kept count over the area. At 5 and 10 units that floor alone settles the verdict. At 5 units it has a median of 1.459 across draws, already far above any envelope, and at 10 units it is 1.949, and there the cleaned index equals its floor in 98 of 100 draws, the ones in which every record’s nearest neighbour is exactly one cell away; with 94.9 of 100 cells occupied on average, an occupied cell with no occupied cell directly beside it is rare. Across all draws at the four cell sizes the cleaned index sits on or above its floor in a share of 1.000 of cases, which is a check on the code rather than a finding. The raw records were read by a statistic with an atom at zero; the cleaned ones are read by a statistic with a lower bound far from zero.</p>
<p>The finer end of the table is the sharper half of the finding. At 2 units the stored records are read almost correctly, as noted above, but after cleaning 81 of 100 draws are called regular (standard error of the share 0.039), with a median index of 1.115. The clean-up bites at a finer cell than the rounding does. Even at 1 unit, a tenth of a kilometre in the atlas reading, 11 of 100 cleaned draws are called regular, against 5 of 100 for the unrounded control.</p>
<p>Reading the cleaned index against the original envelope for 300 points, which is what happens when a script builds its envelope once from the raw record count, moves the counts to 86 of 100 at 2 units and 14 of 100 at 1 unit. The upper limit of the envelope for 300 points is 1.081, and the median upper limit of the envelopes at the reduced counts for 2 units is 1.090. That difference is of the order of the simulation noise in an envelope quantile from 199 patterns, so building the envelope at the wrong count adds a little to the error here but is not its source. Nor is the floor at this cell size: its median is 0.673 at 2 units and 0.344 at 1 unit, far below the envelope. What moves the index at the fine end is the minimum spacing itself. Among exact random points at the cleaned count for 2 units, about 0.30 of nearest-neighbour distances are shorter than 2 units (the Poisson nearest-neighbour formula, one minus e to the power of minus pi times the density times the squared distance), and after cleaning none can be.</p>
<div class="cell">
<div class="code-copy-outer-scaffold"><div class="sourceCode cell-code" id="cb10" style="background: #f1f3f5;"><pre class="sourceCode r code-with-copy"><code class="sourceCode r"><span id="cb10-1">long_r <span class="ot" style="color: #003B4F;
background-color: null;
font-style: inherit;">&lt;-</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">rbind</span>(</span>
<span id="cb10-2">  <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">data.frame</span>(<span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">h =</span> sim_res<span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">$</span>h, <span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">r_val =</span> sim_res<span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">$</span>r_raw, <span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">step =</span> <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"as stored, 300 records"</span>),</span>
<span id="cb10-3">  <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">data.frame</span>(<span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">h =</span> sim_res<span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">$</span>h, <span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">r_val =</span> sim_res<span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">$</span>r_clean, <span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">step =</span> <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"one record per cell"</span>))</span>
<span id="cb10-4">long_r<span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">$</span>step <span class="ot" style="color: #003B4F;
background-color: null;
font-style: inherit;">&lt;-</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">factor</span>(long_r<span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">$</span>step, <span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">levels =</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">c</span>(<span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"as stored, 300 records"</span>, <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"one record per cell"</span>))</span>
<span id="cb10-5">env_df <span class="ot" style="color: #003B4F;
background-color: null;
font-style: inherit;">&lt;-</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">do.call</span>(rbind, <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">lapply</span>(cells_h, <span class="cf" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">function</span>(h) {</span>
<span id="cb10-6">  med_n <span class="ot" style="color: #003B4F;
background-color: null;
font-style: inherit;">&lt;-</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">round</span>(<span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">median</span>(sim_res<span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">$</span>n_kept[sim_res<span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">$</span>h <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">==</span> h]))</span>
<span id="cb10-7">  <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">rbind</span>(<span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">data.frame</span>(<span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">h =</span> h, <span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">lo =</span> env_300[<span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">1</span>], <span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">hi =</span> env_300[<span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">2</span>], <span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">step =</span> <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"as stored, 300 records"</span>),</span>
<span id="cb10-8">        <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">data.frame</span>(<span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">h =</span> h, <span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">lo =</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">env_exact</span>(med_n)[<span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">1</span>], <span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">hi =</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">env_exact</span>(med_n)[<span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">2</span>],</span>
<span id="cb10-9">                   <span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">step =</span> <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"one record per cell"</span>))</span>
<span id="cb10-10">}))</span>
<span id="cb10-11">env_df<span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">$</span>step <span class="ot" style="color: #003B4F;
background-color: null;
font-style: inherit;">&lt;-</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">factor</span>(env_df<span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">$</span>step, <span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">levels =</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">levels</span>(long_r<span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">$</span>step))</span>
<span id="cb10-12">h_lab <span class="ot" style="color: #003B4F;
background-color: null;
font-style: inherit;">&lt;-</span> <span class="cf" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">function</span>(v) <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">factor</span>(<span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">ifelse</span>(v <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">==</span> <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">0</span>, <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"0 (exact)"</span>, <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">as.character</span>(v)),</span>
<span id="cb10-13">                            <span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">levels =</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">c</span>(<span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"0 (exact)"</span>, <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"1"</span>, <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"2"</span>, <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"5"</span>, <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"10"</span>))</span>
<span id="cb10-14">long_r<span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">$</span>h_f <span class="ot" style="color: #003B4F;
background-color: null;
font-style: inherit;">&lt;-</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">h_lab</span>(long_r<span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">$</span>h); env_df<span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">$</span>h_f <span class="ot" style="color: #003B4F;
background-color: null;
font-style: inherit;">&lt;-</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">h_lab</span>(env_df<span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">$</span>h)</span>
<span id="cb10-15"></span>
<span id="cb10-16"><span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">ggplot</span>(long_r, <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">aes</span>(h_f, r_val)) <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">+</span></span>
<span id="cb10-17">  <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">geom_tile</span>(<span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">data =</span> env_df, <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">aes</span>(<span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">x =</span> h_f, <span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">y =</span> (lo <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">+</span> hi) <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">/</span> <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">2</span>, <span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">height =</span> hi <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">-</span> lo),</span>
<span id="cb10-18">            <span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">inherit.aes =</span> <span class="cn" style="color: #8f5902;
background-color: null;
font-style: inherit;">FALSE</span>, <span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">fill =</span> te_gold, <span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">colour =</span> te_gold, <span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">alpha =</span> <span class="fl" style="color: #AD0000;
background-color: null;
font-style: inherit;">0.45</span>, <span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">width =</span> <span class="fl" style="color: #AD0000;
background-color: null;
font-style: inherit;">0.7</span>) <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">+</span></span>
<span id="cb10-19">  <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">geom_jitter</span>(<span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">aes</span>(<span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">colour =</span> step), <span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">width =</span> <span class="fl" style="color: #AD0000;
background-color: null;
font-style: inherit;">0.18</span>, <span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">height =</span> <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">0</span>, <span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">size =</span> <span class="fl" style="color: #AD0000;
background-color: null;
font-style: inherit;">1.1</span>, <span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">alpha =</span> <span class="fl" style="color: #AD0000;
background-color: null;
font-style: inherit;">0.6</span>) <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">+</span></span>
<span id="cb10-20">  <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">scale_colour_manual</span>(<span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">values =</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">c</span>(te_forest, te_rust), <span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">guide =</span> <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"none"</span>) <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">+</span></span>
<span id="cb10-21">  <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">facet_wrap</span>(<span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">~</span> step) <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">+</span></span>
<span id="cb10-22">  <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">labs</span>(<span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">x =</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">sprintf</span>(<span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"cell size of the storage grid (units; random spacing of 300 records is %.2f)"</span>, mean_nn0),</span>
<span id="cb10-23">       <span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">y =</span> <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"Clark-Evans index, naive"</span>,</span>
<span id="cb10-24">       <span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">title =</span> <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"The same records, called clustered and then regular"</span>,</span>
<span id="cb10-25">       <span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">subtitle =</span> <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"gold boxes: 2.5 to 97.5 per cent envelope of exact random points at the same count"</span>) <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">+</span></span>
<span id="cb10-26">  <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">theme_datasheet</span>() <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">+</span></span>
<span id="cb10-27">  <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">theme</span>(<span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">strip.text =</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">element_text</span>(<span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">colour =</span> te_ink, <span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">face =</span> <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"bold"</span>))</span></code></pre></div></div>
<div class="cell-output-display">
<div id="fig-verdicts" class="quarto-float quarto-figure quarto-figure-center anchored" alt="Two panels of jittered points on warm off-white paper, titled The same records, called clustered and then regular. The vertical axis is the naive Clark-Evans index from zero to two, the horizontal axis the cell size of the storage grid: zero (exact), one, two, five and ten. Gold boxes mark the envelope of exact random points, spanning about ninety-seven hundredths to one point zero eight, and wider in the right panel at five and ten, where fewer records remain. In the left panel, as stored with 300 records, dark green points sit inside the boxes at zero, one and two, fall below the box to around eight tenths at five, and drop to around one or two tenths at ten. In the right panel, one record per cell, red points sit inside the box at zero, straddle its top at one, sit mostly above it at two near one point one, and rise far above the boxes to about one point five at five and about one point nine five at ten.">
<figure class="quarto-float quarto-float-fig figure">
<div aria-describedby="fig-verdicts-caption-0ceaefa1-69ba-4598-a22c-09a6ac19f8ca">
<img src="https://tidyecology.com/posts/snapped-coordinates-and-clustering/index_files/figure-html/fig-verdicts-1.png" class="img-fluid figure-img" alt="Two panels of jittered points on warm off-white paper, titled The same records, called clustered and then regular. The vertical axis is the naive Clark-Evans index from zero to two, the horizontal axis the cell size of the storage grid: zero (exact), one, two, five and ten. Gold boxes mark the envelope of exact random points, spanning about ninety-seven hundredths to one point zero eight, and wider in the right panel at five and ten, where fewer records remain. In the left panel, as stored with 300 records, dark green points sit inside the boxes at zero, one and two, fall below the box to around eight tenths at five, and drop to around one or two tenths at ten. In the right panel, one record per cell, red points sit inside the box at zero, straddle its top at one, sit mostly above it at two near one point one, and rise far above the boxes to about one point five at five and about one point nine five at ten." width="672">
</div>
<figcaption class="quarto-float-caption-bottom quarto-float-caption quarto-float-fig" id="fig-verdicts-caption-0ceaefa1-69ba-4598-a22c-09a6ac19f8ca">
Figure&nbsp;3: Clark-Evans index for 100 random patterns at each cell size, as stored and after one record per cell, against the envelope for exact random points at the matching record count.
</figcaption>
</figure>
</div>
</div>
</div>
</section>
<section id="a-real-clustering-verdict-does-not-survive-the-same-two-steps" class="level2">
<h2 id="a-real-clustering-verdict-does-not-survive-the-same-two-steps-h" class="anchored" data-anchor-id="a-real-clustering-verdict-does-not-survive-the-same-two-steps">A real clustering verdict does not survive the same two steps</h2>
<p>The first two sections manufacture a pattern where there is none. The more damaging case runs the other way. A Thomas cluster process places 30 parent points at random and 10 offspring around each with a normal spread of 3 units, and offspring falling outside the window are dropped. This is a pattern that is clustered by construction, with a spread of the same order as the 5 unit cell. It goes through the same storage grid and the same clean-up.</p>
<div class="cell">
<div class="code-copy-outer-scaffold"><div class="sourceCode cell-code" id="cb11" style="background: #f1f3f5;"><pre class="sourceCode r code-with-copy"><code class="sourceCode r"><span id="cb11-1"><span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">set.seed</span>(<span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">6060</span>)</span>
<span id="cb11-2">th_rows <span class="ot" style="color: #003B4F;
background-color: null;
font-style: inherit;">&lt;-</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">vector</span>(<span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"list"</span>, n_draw)</span>
<span id="cb11-3"><span class="cf" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">for</span> (d_i <span class="cf" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">in</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">seq_len</span>(n_draw)) {</span>
<span id="cb11-4">  pts0   <span class="ot" style="color: #003B4F;
background-color: null;
font-style: inherit;">&lt;-</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">thomas_pts</span>()</span>
<span id="cb11-5">  n0     <span class="ot" style="color: #003B4F;
background-color: null;
font-style: inherit;">&lt;-</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">length</span>(pts0<span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">$</span>x)</span>
<span id="cb11-6">  r0     <span class="ot" style="color: #003B4F;
background-color: null;
font-style: inherit;">&lt;-</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">ce_index</span>(pts0<span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">$</span>x, pts0<span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">$</span>y)</span>
<span id="cb11-7">  stored <span class="ot" style="color: #003B4F;
background-color: null;
font-style: inherit;">&lt;-</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">snap_pts</span>(pts0, <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">5</span>)</span>
<span id="cb11-8">  nn_st  <span class="ot" style="color: #003B4F;
background-color: null;
font-style: inherit;">&lt;-</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">nn_dist</span>(stored<span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">$</span>x, stored<span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">$</span>y)</span>
<span id="cb11-9">  r_st   <span class="ot" style="color: #003B4F;
background-color: null;
font-style: inherit;">&lt;-</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">mean</span>(nn_st) <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">/</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">ce_expect</span>(n0)</span>
<span id="cb11-10">  cleaned <span class="ot" style="color: #003B4F;
background-color: null;
font-style: inherit;">&lt;-</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">one_per_cell</span>(stored)</span>
<span id="cb11-11">  n_kept  <span class="ot" style="color: #003B4F;
background-color: null;
font-style: inherit;">&lt;-</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">length</span>(cleaned<span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">$</span>x)</span>
<span id="cb11-12">  r_cl    <span class="ot" style="color: #003B4F;
background-color: null;
font-style: inherit;">&lt;-</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">ce_index</span>(cleaned<span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">$</span>x, cleaned<span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">$</span>y)</span>
<span id="cb11-13">  th_rows[[d_i]] <span class="ot" style="color: #003B4F;
background-color: null;
font-style: inherit;">&lt;-</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">data.frame</span>(</span>
<span id="cb11-14">    <span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">n0 =</span> n0, <span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">r0 =</span> r0, <span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">call0 =</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">call_it</span>(r0, <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">env_exact</span>(n0)),</span>
<span id="cb11-15">    <span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">r_st =</span> r_st, <span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">zero_share =</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">mean</span>(nn_st <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">==</span> <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">0</span>), <span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">call_st =</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">call_it</span>(r_st, <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">env_exact</span>(n0)),</span>
<span id="cb11-16">    <span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">n_kept =</span> n_kept, <span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">r_cl =</span> r_cl, <span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">call_cl =</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">call_it</span>(r_cl, <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">env_exact</span>(n_kept)))</span>
<span id="cb11-17">}</span>
<span id="cb11-18">th_res <span class="ot" style="color: #003B4F;
background-color: null;
font-style: inherit;">&lt;-</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">do.call</span>(rbind, th_rows)</span>
<span id="cb11-19">th_sum <span class="ot" style="color: #003B4F;
background-color: null;
font-style: inherit;">&lt;-</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">list</span>(</span>
<span id="cb11-20">  <span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">n0 =</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">median</span>(th_res<span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">$</span>n0), <span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">r0 =</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">median</span>(th_res<span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">$</span>r0), <span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">clu0 =</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">mean</span>(th_res<span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">$</span>call0 <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">==</span> <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"clustered"</span>),</span>
<span id="cb11-21">  <span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">r_st =</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">median</span>(th_res<span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">$</span>r_st), <span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">zero =</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">mean</span>(th_res<span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">$</span>zero_share),</span>
<span id="cb11-22">  <span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">clu_st =</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">mean</span>(th_res<span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">$</span>call_st <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">==</span> <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"clustered"</span>),</span>
<span id="cb11-23">  <span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">n_kept =</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">median</span>(th_res<span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">$</span>n_kept), <span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">r_cl =</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">median</span>(th_res<span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">$</span>r_cl),</span>
<span id="cb11-24">  <span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">clu_cl =</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">mean</span>(th_res<span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">$</span>call_cl <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">==</span> <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"clustered"</span>), <span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">rnd_cl =</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">mean</span>(th_res<span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">$</span>call_cl <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">==</span> <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"random"</span>),</span>
<span id="cb11-25">  <span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">reg_cl =</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">mean</span>(th_res<span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">$</span>call_cl <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">==</span> <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"regular"</span>))</span></code></pre></div></div>
</div>
<p>With exact coordinates the pattern is read correctly: a median of 287 records survive the window, the median index is 0.596, and 100 of 100 draws are called clustered. Storing the records on the 5 unit grid exaggerates the clustering, since offspring of one parent tend to share cells: the zero share is 0.814 and the median index drops to 0.317. The clean-up then leaves a median of 127 records, the median index is 1.134, and 0 of 100 draws are called clustered: 55 are called random and 45 regular.</p>
<p>The six maps above (the second figure) show why this is not a failure to detect something faint. The cleaned Thomas pattern is still visibly a set of tight patches of occupied cells separated by empty ground. What the patches no longer have is short distances inside them, and the nearest-neighbour index looks at nothing else.</p>
</section>
<section id="an-envelope-on-the-storage-grid" class="level2">
<h2 id="an-envelope-on-the-storage-grid-h" class="anchored" data-anchor-id="an-envelope-on-the-storage-grid">An envelope on the storage grid</h2>
<p>The repair a spatial statistician would suggest is to build the null on the same support as the data: simulate random points, then apply the same grid and the same clean-up, so the envelope carries the atom at zero and the lattice floor as well. For stored records that means random patterns of 300 points snapped to the grid. For cleaned records there is a simpler exact form. Under complete spatial randomness every cell is equally likely to be occupied, so given the number of occupied cells, the set of occupied cells is a random subset of the grid of that size; the envelope comes from drawing that many cells at random without replacement and placing a record at each centre. This conditions on the count the analyst actually has after cleaning, and needs no knowledge of how many records there were before.</p>
<div class="cell">
<div class="code-copy-outer-scaffold"><div class="sourceCode cell-code" id="cb12" style="background: #f1f3f5;"><pre class="sourceCode r code-with-copy"><code class="sourceCode r"><span id="cb12-1"><span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">set.seed</span>(<span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">4747</span>)</span>
<span id="cb12-2">grid_env_store <span class="ot" style="color: #003B4F;
background-color: null;
font-style: inherit;">&lt;-</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">new.env</span>()</span>
<span id="cb12-3">env_grid <span class="ot" style="color: #003B4F;
background-color: null;
font-style: inherit;">&lt;-</span> <span class="cf" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">function</span>(h, n_occ) {</span>
<span id="cb12-4">  key <span class="ot" style="color: #003B4F;
background-color: null;
font-style: inherit;">&lt;-</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">paste</span>(h, n_occ)</span>
<span id="cb12-5">  <span class="cf" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">if</span> (<span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">is.null</span>(grid_env_store[[key]])) {</span>
<span id="cb12-6">    k_side <span class="ot" style="color: #003B4F;
background-color: null;
font-style: inherit;">&lt;-</span> side <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">/</span> h</span>
<span id="cb12-7">    sims <span class="ot" style="color: #003B4F;
background-color: null;
font-style: inherit;">&lt;-</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">replicate</span>(n_env, {</span>
<span id="cb12-8">      cell_id <span class="ot" style="color: #003B4F;
background-color: null;
font-style: inherit;">&lt;-</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">sample.int</span>(k_side <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">*</span> k_side, n_occ)</span>
<span id="cb12-9">      <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">ce_index</span>(((cell_id <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">-</span> <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">1</span>) <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">%%</span> k_side <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">+</span> <span class="fl" style="color: #AD0000;
background-color: null;
font-style: inherit;">0.5</span>) <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">*</span> h, ((cell_id <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">-</span> <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">1</span>) <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">%/%</span> k_side <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">+</span> <span class="fl" style="color: #AD0000;
background-color: null;
font-style: inherit;">0.5</span>) <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">*</span> h)</span>
<span id="cb12-10">    })</span>
<span id="cb12-11">    grid_env_store[[key]] <span class="ot" style="color: #003B4F;
background-color: null;
font-style: inherit;">&lt;-</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">quantile</span>(sims, <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">c</span>(<span class="fl" style="color: #AD0000;
background-color: null;
font-style: inherit;">0.025</span>, <span class="fl" style="color: #AD0000;
background-color: null;
font-style: inherit;">0.975</span>), <span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">names =</span> <span class="cn" style="color: #8f5902;
background-color: null;
font-style: inherit;">FALSE</span>)</span>
<span id="cb12-12">  }</span>
<span id="cb12-13">  grid_env_store[[key]]</span>
<span id="cb12-14">}</span>
<span id="cb12-15">env_snapped <span class="ot" style="color: #003B4F;
background-color: null;
font-style: inherit;">&lt;-</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">lapply</span>(<span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">c</span>(<span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">2</span>, <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">5</span>, <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">10</span>), <span class="cf" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">function</span>(h) {</span>
<span id="cb12-16">  sims <span class="ot" style="color: #003B4F;
background-color: null;
font-style: inherit;">&lt;-</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">replicate</span>(n_env, { q <span class="ot" style="color: #003B4F;
background-color: null;
font-style: inherit;">&lt;-</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">snap_pts</span>(<span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">csr_pts</span>(n_rec), h); <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">ce_index</span>(q<span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">$</span>x, q<span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">$</span>y) })</span>
<span id="cb12-17">  <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">quantile</span>(sims, <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">c</span>(<span class="fl" style="color: #AD0000;
background-color: null;
font-style: inherit;">0.025</span>, <span class="fl" style="color: #AD0000;
background-color: null;
font-style: inherit;">0.975</span>), <span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">names =</span> <span class="cn" style="color: #8f5902;
background-color: null;
font-style: inherit;">FALSE</span>)</span>
<span id="cb12-18">})</span>
<span id="cb12-19"><span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">names</span>(env_snapped) <span class="ot" style="color: #003B4F;
background-color: null;
font-style: inherit;">&lt;-</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">c</span>(<span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"2"</span>, <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"5"</span>, <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"10"</span>)</span>
<span id="cb12-20"></span>
<span id="cb12-21">rep_rows <span class="ot" style="color: #003B4F;
background-color: null;
font-style: inherit;">&lt;-</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">do.call</span>(rbind, <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">lapply</span>(<span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">c</span>(<span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">2</span>, <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">5</span>, <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">10</span>), <span class="cf" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">function</span>(h) {</span>
<span id="cb12-22">  s <span class="ot" style="color: #003B4F;
background-color: null;
font-style: inherit;">&lt;-</span> sim_res[sim_res<span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">$</span>h <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">==</span> h, ]</span>
<span id="cb12-23">  raw_grid   <span class="ot" style="color: #003B4F;
background-color: null;
font-style: inherit;">&lt;-</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">call_it</span>(s<span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">$</span>r_raw, env_snapped[[<span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">as.character</span>(h)]])</span>
<span id="cb12-24">  clean_grid <span class="ot" style="color: #003B4F;
background-color: null;
font-style: inherit;">&lt;-</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">mapply</span>(<span class="cf" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">function</span>(r_val, n_k) <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">call_it</span>(r_val, <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">env_grid</span>(h, n_k)), s<span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">$</span>r_clean, s<span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">$</span>n_kept)</span>
<span id="cb12-25">  <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">data.frame</span>(<span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">h =</span> h,</span>
<span id="cb12-26">             <span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">raw_exact =</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">mean</span>(s<span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">$</span>raw_call <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">!=</span> <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"random"</span>), <span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">raw_grid =</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">mean</span>(raw_grid <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">!=</span> <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"random"</span>),</span>
<span id="cb12-27">             <span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">clean_exact =</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">mean</span>(s<span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">$</span>clean_call <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">!=</span> <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"random"</span>), <span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">clean_grid =</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">mean</span>(clean_grid <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">!=</span> <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"random"</span>))</span>
<span id="cb12-28">}))</span>
<span id="cb12-29">th_grid_call <span class="ot" style="color: #003B4F;
background-color: null;
font-style: inherit;">&lt;-</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">mapply</span>(<span class="cf" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">function</span>(r_val, n_k) <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">call_it</span>(r_val, <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">env_grid</span>(<span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">5</span>, n_k)),</span>
<span id="cb12-30">                       th_res<span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">$</span>r_cl, th_res<span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">$</span>n_kept)</span>
<span id="cb12-31">th_grid_clu  <span class="ot" style="color: #003B4F;
background-color: null;
font-style: inherit;">&lt;-</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">mean</span>(th_grid_call <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">==</span> <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"clustered"</span>)</span>
<span id="cb12-32">rep_h <span class="ot" style="color: #003B4F;
background-color: null;
font-style: inherit;">&lt;-</span> <span class="cf" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">function</span>(h) rep_rows[rep_rows<span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">$</span>h <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">==</span> h, ]</span>
<span id="cb12-33">r2 <span class="ot" style="color: #003B4F;
background-color: null;
font-style: inherit;">&lt;-</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">rep_h</span>(<span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">2</span>); r5 <span class="ot" style="color: #003B4F;
background-color: null;
font-style: inherit;">&lt;-</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">rep_h</span>(<span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">5</span>); r10 <span class="ot" style="color: #003B4F;
background-color: null;
font-style: inherit;">&lt;-</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">rep_h</span>(<span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">10</span>)</span>
<span id="cb12-34">worst_grid <span class="ot" style="color: #003B4F;
background-color: null;
font-style: inherit;">&lt;-</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">max</span>(<span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">c</span>(rep_rows<span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">$</span>raw_grid, rep_rows<span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">$</span>clean_grid))</span></code></pre></div></div>
</div>
<p>On the stored records the envelope from snapped random patterns runs from 0.721 to 0.941 at 5 units, well below the exact-coordinate envelope, and the number of random patterns called non-random falls from 99 of 100 to 6 of 100. On the cleaned records the grid-subset envelope does the same in the other direction: the count called non-random at 5 units falls from 100 of 100 to 8 of 100, and at 2 units from 81 of 100 to 8 of 100. Across the three cell sizes and both steps the largest non-random share under the grid envelopes is 0.08, against a nominal 0.05, with a Monte Carlo standard error of about 0.022 at the nominal level. So the repair fixes both directions at once on random data.</p>
<p>The part that matters more is the clustered pattern. Against the grid-subset envelope the cleaned Thomas records are called clustered in 100 of 100 draws, where the exact-coordinate envelope gave 0 of 100. The information was not destroyed by the clean-up; it moved from the distances inside a patch to the arrangement of occupied cells, and a null built on the grid can still see it.</p>
<div class="cell">
<div class="code-copy-outer-scaffold"><div class="sourceCode cell-code" id="cb13" style="background: #f1f3f5;"><pre class="sourceCode r code-with-copy"><code class="sourceCode r"><span id="cb13-1">rep_long <span class="ot" style="color: #003B4F;
background-color: null;
font-style: inherit;">&lt;-</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">rbind</span>(</span>
<span id="cb13-2">  <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">data.frame</span>(<span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">case =</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">sprintf</span>(<span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"random, as stored, cell %d"</span>, rep_rows<span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">$</span>h),</span>
<span id="cb13-3">             <span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">exact =</span> rep_rows<span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">$</span>raw_exact, <span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">grid =</span> rep_rows<span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">$</span>raw_grid),</span>
<span id="cb13-4">  <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">data.frame</span>(<span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">case =</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">sprintf</span>(<span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"random, one per cell, cell %d"</span>, rep_rows<span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">$</span>h),</span>
<span id="cb13-5">             <span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">exact =</span> rep_rows<span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">$</span>clean_exact, <span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">grid =</span> rep_rows<span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">$</span>clean_grid),</span>
<span id="cb13-6">  <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">data.frame</span>(<span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">case =</span> <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"clustered, one per cell, cell 5"</span>, <span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">exact =</span> th_sum<span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">$</span>clu_cl, <span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">grid =</span> th_grid_clu))</span>
<span id="cb13-7">rep_long<span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">$</span>case <span class="ot" style="color: #003B4F;
background-color: null;
font-style: inherit;">&lt;-</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">factor</span>(rep_long<span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">$</span>case, <span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">levels =</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">rev</span>(rep_long<span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">$</span>case))</span>
<span id="cb13-8">rep_plot <span class="ot" style="color: #003B4F;
background-color: null;
font-style: inherit;">&lt;-</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">rbind</span>(</span>
<span id="cb13-9">  <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">data.frame</span>(<span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">case =</span> rep_long<span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">$</span>case, <span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">share =</span> rep_long<span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">$</span>exact, <span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">env =</span> <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"envelope on exact coordinates"</span>),</span>
<span id="cb13-10">  <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">data.frame</span>(<span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">case =</span> rep_long<span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">$</span>case, <span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">share =</span> rep_long<span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">$</span>grid, <span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">env =</span> <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"envelope on the storage grid"</span>))</span>
<span id="cb13-11">rep_plot<span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">$</span>se <span class="ot" style="color: #003B4F;
background-color: null;
font-style: inherit;">&lt;-</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">share_se</span>(rep_plot<span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">$</span>share)</span>
<span id="cb13-12"></span>
<span id="cb13-13"><span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">ggplot</span>(rep_plot, <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">aes</span>(share, case, <span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">colour =</span> env)) <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">+</span></span>
<span id="cb13-14">  <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">geom_vline</span>(<span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">xintercept =</span> <span class="fl" style="color: #AD0000;
background-color: null;
font-style: inherit;">0.05</span>, <span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">linetype =</span> <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"dashed"</span>, <span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">colour =</span> te_body, <span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">linewidth =</span> <span class="fl" style="color: #AD0000;
background-color: null;
font-style: inherit;">0.5</span>) <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">+</span></span>
<span id="cb13-15">  <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">geom_errorbar</span>(<span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">aes</span>(<span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">xmin =</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">pmax</span>(share <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">-</span> <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">2</span> <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">*</span> se, <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">0</span>), <span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">xmax =</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">pmin</span>(share <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">+</span> <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">2</span> <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">*</span> se, <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">1</span>)),</span>
<span id="cb13-16">                <span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">orientation =</span> <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"y"</span>, <span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">width =</span> <span class="fl" style="color: #AD0000;
background-color: null;
font-style: inherit;">0.25</span>, <span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">linewidth =</span> <span class="fl" style="color: #AD0000;
background-color: null;
font-style: inherit;">0.6</span>,</span>
<span id="cb13-17">                <span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">position =</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">position_dodge</span>(<span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">width =</span> <span class="fl" style="color: #AD0000;
background-color: null;
font-style: inherit;">0.55</span>)) <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">+</span></span>
<span id="cb13-18">  <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">geom_point</span>(<span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">size =</span> <span class="fl" style="color: #AD0000;
background-color: null;
font-style: inherit;">2.6</span>, <span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">position =</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">position_dodge</span>(<span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">width =</span> <span class="fl" style="color: #AD0000;
background-color: null;
font-style: inherit;">0.55</span>)) <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">+</span></span>
<span id="cb13-19">  <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">scale_colour_manual</span>(<span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">values =</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">c</span>(te_rust, te_forest), <span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">name =</span> <span class="cn" style="color: #8f5902;
background-color: null;
font-style: inherit;">NULL</span>) <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">+</span></span>
<span id="cb13-20">  <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">scale_x_continuous</span>(<span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">limits =</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">c</span>(<span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">0</span>, <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">1</span>), <span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">breaks =</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">seq</span>(<span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">0</span>, <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">1</span>, <span class="fl" style="color: #AD0000;
background-color: null;
font-style: inherit;">0.2</span>)) <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">+</span></span>
<span id="cb13-21">  <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">labs</span>(<span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">x =</span> <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"share of patterns given the verdict"</span>, <span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">y =</span> <span class="cn" style="color: #8f5902;
background-color: null;
font-style: inherit;">NULL</span>,</span>
<span id="cb13-22">       <span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">title =</span> <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"A null on the grid fixes both directions"</span>,</span>
<span id="cb13-23">       <span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">subtitle =</span> <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"dashed line: the nominal five per cent"</span>) <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">+</span></span>
<span id="cb13-24">  <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">theme_datasheet</span>() <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">+</span></span>
<span id="cb13-25">  <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">theme</span>(<span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">legend.position =</span> <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"bottom"</span>)</span></code></pre></div></div>
<div class="cell-output-display">
<div id="fig-repair" class="quarto-float quarto-figure quarto-figure-center anchored" alt="A dot plot on warm off-white paper titled A null on the grid fixes both directions. Seven rows list cases: random as stored at cells two, five and ten; random one per cell at cells two, five and ten; and clustered one per cell at cell five. The horizontal axis is the share of patterns given the verdict, from zero to one, with a dashed vertical line at five hundredths. Red points for the envelope on exact coordinates sit near one for random as stored at cells five and ten and for random one per cell at cells five and ten, at about eight tenths for random one per cell at cell two, near one tenth for random as stored at cell two, and at zero for the clustered row. Dark green points for the envelope on the storage grid sit between about two and eight hundredths for every random row, close to the dashed line, and at one for the clustered row. Short horizontal bars span plus or minus two standard errors.">
<figure class="quarto-float quarto-float-fig figure">
<div aria-describedby="fig-repair-caption-0ceaefa1-69ba-4598-a22c-09a6ac19f8ca">
<img src="https://tidyecology.com/posts/snapped-coordinates-and-clustering/index_files/figure-html/fig-repair-1.png" class="img-fluid figure-img" alt="A dot plot on warm off-white paper titled A null on the grid fixes both directions. Seven rows list cases: random as stored at cells two, five and ten; random one per cell at cells two, five and ten; and clustered one per cell at cell five. The horizontal axis is the share of patterns given the verdict, from zero to one, with a dashed vertical line at five hundredths. Red points for the envelope on exact coordinates sit near one for random as stored at cells five and ten and for random one per cell at cells five and ten, at about eight tenths for random one per cell at cell two, near one tenth for random as stored at cell two, and at zero for the clustered row. Dark green points for the envelope on the storage grid sit between about two and eight hundredths for every random row, close to the dashed line, and at one for the clustered row. Short horizontal bars span plus or minus two standard errors." width="672">
</div>
<figcaption class="quarto-float-caption-bottom quarto-float-caption quarto-float-fig" id="fig-repair-caption-0ceaefa1-69ba-4598-a22c-09a6ac19f8ca">
Figure&nbsp;4: Share of 100 patterns given a non-random verdict (for the clustered pattern, a clustered verdict), with the envelope built on exact coordinates and on the storage grid. Bars span plus or minus two Monte Carlo standard errors.
</figcaption>
</figure>
</div>
</div>
</div>
</section>
<section id="what-to-report" class="level2">
<h2 id="what-to-report-h" class="anchored" data-anchor-id="what-to-report">What to report</h2>
<p>Check the storage before running any distance statistic. Two numbers do it and both are one line of R: the share of records whose nearest neighbour is at distance exactly zero, and the number of distinct values in each coordinate column.</p>
<div class="cell">
<div class="code-copy-outer-scaffold"><div class="sourceCode cell-code" id="cb14" style="background: #f1f3f5;"><pre class="sourceCode r code-with-copy"><code class="sourceCode r"><span id="cb14-1"><span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">set.seed</span>(<span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">515</span>)</span>
<span id="cb14-2">diag_pts <span class="ot" style="color: #003B4F;
background-color: null;
font-style: inherit;">&lt;-</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">csr_pts</span>(n_rec)</span>
<span id="cb14-3">diag_tab <span class="ot" style="color: #003B4F;
background-color: null;
font-style: inherit;">&lt;-</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">do.call</span>(rbind, <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">lapply</span>(cells_h, <span class="cf" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">function</span>(h) {</span>
<span id="cb14-4">  st <span class="ot" style="color: #003B4F;
background-color: null;
font-style: inherit;">&lt;-</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">snap_pts</span>(diag_pts, h)</span>
<span id="cb14-5">  <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">data.frame</span>(<span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">cell =</span> h, <span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">zero_nn =</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">round</span>(<span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">mean</span>(<span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">nn_dist</span>(st<span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">$</span>x, st<span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">$</span>y) <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">==</span> <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">0</span>), <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">3</span>),</span>
<span id="cb14-6">             <span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">distinct_x =</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">length</span>(<span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">unique</span>(st<span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">$</span>x)), <span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">distinct_y =</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">length</span>(<span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">unique</span>(st<span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">$</span>y)))</span>
<span id="cb14-7">}))</span>
<span id="cb14-8">diag_tab</span></code></pre></div></div>
<div class="cell-output cell-output-stdout">
<pre><code>  cell zero_nn distinct_x distinct_y
1    0   0.000        300        300
2    1   0.013         94         98
3    2   0.153         50         50
4    5   0.563         20         20
5   10   0.937         10         10</code></pre>
</div>
</div>
<p>On exact coordinates there are as many distinct values as records and no zero distances. On a 5 unit grid there are 20 distinct x values among 300 records. In a real download the same check is a count of decimal places: a coordinate with two decimal places of a degree is a grid of roughly a kilometre, and a column where most values have two decimals and a few have six is a mixture of storage grids, which no single-grid null in this post can handle (that case is not simulated here). Count the decimals on the text as downloaded, since a numeric column drops trailing zeros. A stated coordinate uncertainty, where it exists, gives the same information more directly, but the cleaning tutorial on this site keeps blank uncertainties rather than dropping them, and the decimal count works on every record. At the level of a whole dataset, CoordinateCleaner’s <code>cd_round()</code> automates a related check: it flags datasets whose coordinates show the periodic spacing of a lattice, as atlas data often do.</p>
<p>If the records are on a grid, say which grid, and build the null on it. For stored records that means simulating random points and snapping them the same way; for records cleaned to one per cell it means drawing the same number of cells at random from the grid. Report the index with that envelope, and report the zero share and the kept count next to the occupancy formula, so a reader can see the snap has been accounted for.</p>
<p>Do not read a Clark-Evans index from gridded records against one, and do not read it against an envelope of exact random points. The table above gives the sizes of those errors for one design. If the cleaned records are going into a species distribution model rather than a point-pattern test, the thinning section of the presence-only post is the relevant measurement, and its damage is to the slope, not to the verdict.</p>
</section>
<section id="honest-limits" class="level2">
<h2 id="honest-limits-h" class="anchored" data-anchor-id="honest-limits">Honest limits</h2>
<p>Everything is measured for 300 records in a square window, with cell sizes that divide the side exactly. A grid that does not align with the study boundary leaves partial cells at the edges, and the occupancy formula becomes an approximation there. Rounded decimal degrees are not square cells away from the equator, and a mixture of storage grids in one dataset, which is common in atlas data, was not simulated.</p>
<p>The statistic is the naive Clark-Evans index, chosen because it is common and because its edge bias forced the envelopes to be built honestly. An edge-corrected index would move the control row towards one but would not change the atom at zero or the lattice floor, which are the mechanisms here. The pair correlation function at short distances would show the ties even more plainly, as a spike at zero, and Ripley’s K would inherit them at every distance; neither was measured.</p>
<p>The clustered case is one Thomas process with a cluster spread of 3 units against a 5 unit cell. Other cluster scales were not measured, and the direction is not obvious in advance: the lattice floor applies to every cleaned pattern, whatever its clustering, so larger clusters are not safe merely because they are larger. The grid-subset repair was shown to recover the clustered verdict at this one scale, and it assumes the records were homogeneous before storage; with an intensity trend it inherits every problem an inhomogeneous pattern has against a homogeneous null.</p>
<p>Finally, the grid-subset envelope conditions on the number of occupied cells, which is right for a test of arrangement given occupancy. It says nothing about whether the number of occupied cells is itself unusual, which for a gridded atlas is often the more useful question.</p>
</section>
<section id="references" class="level2">
<h2 id="references-h" class="anchored" data-anchor-id="references">References</h2>
<p>Clark PJ, Evans FC 1954 Ecology 35(4):445-453 (<a href="https://doi.org/10.2307/1931034">10.2307/1931034</a>)</p>
<p>Zizka A, Silvestro D, Andermann T, Azevedo J, Duarte Ritter C, Edler D, Farooq H, Herdean A, Ariza M, Scharn R, Svantesson S, Wengstrom N, Zizka V, Antonelli A 2019 Methods in Ecology and Evolution 10(5):744-751 (<a href="https://doi.org/10.1111/2041-210X.13152">10.1111/2041-210X.13152</a>)</p>
<p>Maldonado C, Molina CI, Zizka A, Persson C, Taylor CM, Alban J, Chilquillo E, Ronsted N, Antonelli A 2015 Global Ecology and Biogeography 24(8):973-984 (<a href="https://doi.org/10.1111/geb.12326">10.1111/geb.12326</a>)</p>
<p>Baddeley A, Rubak E, Turner R 2015 Spatial Point Patterns: Methodology and Applications with R (ISBN 978-1-4822-1020-0)</p>
</section>
<section id="related-tutorials" class="level2">
<h2 id="related-tutorials-h" class="anchored" data-anchor-id="related-tutorials">Related tutorials</h2>
<ul>
<li><a href="https://tidyecology.com/posts/nearest-neighbour-clark-evans/">Nearest-neighbour analysis and Clark-Evans in R</a></li>
<li><a href="https://tidyecology.com/posts/checking-a-point-pattern-analysis/">Checking a point pattern analysis</a></li>
<li><a href="https://tidyecology.com/posts/sampling-bias-in-presence-only-models/">Sampling bias in presence-only models</a></li>
<li><a href="https://tidyecology.com/posts/cleaning-gbif-occurrence-data/">Cleaning GBIF and iNaturalist records in R</a></li>
</ul>
<details class="te-repro" data-pagefind-ignore="">
<summary>Reproducibility</summary>
<ul>
<li>Code last run: 2026-10-15</li>
<li>R version 4.5.3 (2026-03-11), aarch64-apple-darwin20</li>
<li>Packages: ggplot2 4.0.3, patchwork 1.3.2</li>
</ul>
</details>


<!-- -->

</section>

 ]]></description>
  <category>R</category>
  <category>point patterns</category>
  <category>spatial ecology</category>
  <category>occurrence data</category>
  <category>data cleaning</category>
  <category>ecology tutorial</category>
  <guid isPermaLink="false">https://tidyecology.com/posts/snapped-coordinates-and-clustering/</guid>
  <pubDate>Sat, 26 Sep 2026 08:00:00 GMT</pubDate>
  <media:content url="https://tidyecology.com/posts/snapped-coordinates-and-clustering/thumbnail.png" medium="image" type="image/png" height="104" width="144"/>
</item>
<item>
  <title>Reprojecting a raster in QGIS and R: opposite defaults</title>
  <dc:creator>Tidy Ecology</dc:creator>
  <link>https://tidyecology.com/posts/reprojecting-a-raster-in-qgis-and-r/</link>
  <description><![CDATA[ 





<p><em>Corrected 14 October 2026: the post said the middle class gains because the mean of the two end codes is the middle code; it now says averaging adds only codes that lie between the codes it averages, and the middle code lies between the most pairs. The heading of the elevation section also said nearest keeps the values; it now says nearest never alters a value.</em></p>
<p><em>Corrected 1 October 2026: the post said nearest neighbour keeps every value and returns the old minimum and maximum because it only copies; it now says nearest never alters a value, so it cannot go beyond the old range, and that both extreme cells happened to be among those it copied.</em></p>
<p>A land-cover map classified from Landsat scenes arrives in UTM zone 34 north, the zone the scenes were delivered in. The protected-area boundaries and the national grid it has to be reported on are in Stereo70 (EPSG:3844), the Romanian national system, so the map is reprojected: once in QGIS, to look at it over the other layers, and once in R with <code>terra</code>, for the analysis. The two versions disagree along the patch boundaries, and the R version holds class codes that are not whole numbers. A digital elevation model goes through the same step, and the slope map made from one of its two versions is crossed by a lattice of faint straight lines. Nothing failed. The two programs resampled the cells in different ways, and neither said which.</p>
<p>Every reprojection of a raster builds a new grid in the new coordinate system and has to decide what value each new cell takes from the old ones. <a href="https://tidyecology.com/posts/rasterising-a-vector-layer/">Rasterising a vector layer</a> measures the rule that decides which cells a polygon fills; this post is the rule one step later, when a grid becomes another grid. <a href="https://tidyecology.com/posts/checking-a-remote-sensing-covariate/">Checking a remote sensing covariate</a> compares the nearest pixel and bilinear interpolation as ways of reading a satellite image at survey stations; the same two rules are at work here, applied to every cell of the output. Which coordinate system to choose in the first place is the subject of <a href="https://tidyecology.com/posts/choosing-a-projection-for-area-and-distance/">Choosing a projection for area and distance</a>, and is not repeated. <a href="https://tidyecology.com/posts/terra-raster-basics/">Raster data in R with terra</a> is the place to start if a <code>SpatRaster</code> is new to you. Like <a href="https://tidyecology.com/posts/area-in-qgis-and-r/">Area in QGIS and R</a>, the page has no screenshots: menu paths are in bold, the QGIS commands are shown exactly as they ran, and the R chunks read their output rasters back from this post’s folder.</p>
<section id="the-short-answer" class="level2">
<h2 id="the-short-answer-h" class="anchored" data-anchor-id="the-short-answer">The short answer</h2>
<p>The two tools make opposite choices when you do not choose. QGIS <strong>Raster &gt; Projections &gt; Warp (Reproject)</strong> copies the value of the nearest old cell into each new cell. <code>terra::project()</code> interpolates between the four nearest old cells, unless the raster has a category table (or is an RGB image), in which case it copies the nearest one too. A land-cover GeoTIFF of plain integer codes, with no category names or attribute table stored in the file or beside it (a colour table alone does not count), is not a factor, so <code>terra</code> averages the codes: along every boundary it writes values between classes, and after rounding some of those are classes that were never there. For a map of classes, pass <code>method = "near"</code> to <code>project()</code>, or give the raster its category table with <code>levels()</code> first; QGIS needs nothing. For an elevation or temperature surface the choice is the other way round: bilinear keeps the shape of the surface but cuts the top off sharp peaks, while nearest never alters a value but moves some of them, and slope computed from the result shows it. Choose <strong>Bilinear (2x2 Kernel)</strong> in the Warp dialog, or leave <code>terra</code> on its default. Both tools pick the output cell size on their own, and they pick the same one; to control the grid, give both the same template.</p>
<table class="caption-top table">
<colgroup>
<col style="width: 33%">
<col style="width: 33%">
<col style="width: 33%">
</colgroup>
<thead>
<tr class="header">
<th style="text-align: left;">In QGIS (Warp)</th>
<th style="text-align: left;">In R (<code>terra</code>)</th>
<th style="text-align: left;">What happens</th>
</tr>
</thead>
<tbody>
<tr class="odd">
<td style="text-align: left;"><em>Resampling method to use</em> left at <code>Nearest Neighbour</code></td>
<td style="text-align: left;"><code>project(x, "EPSG:3844", method = "near")</code></td>
<td style="text-align: left;">each new cell copies one old cell</td>
</tr>
<tr class="even">
<td style="text-align: left;"><em>Resampling method to use</em> set to <code>Bilinear (2x2 Kernel)</code></td>
<td style="text-align: left;"><code>project(x, "EPSG:3844")</code> on a raster with no category table</td>
<td style="text-align: left;">each new cell is a weighted mean of four old cells</td>
</tr>
<tr class="odd">
<td style="text-align: left;">(the QGIS default)</td>
<td style="text-align: left;"><code>project(x, "EPSG:3844")</code> after <code>levels(x) &lt;- ...</code></td>
<td style="text-align: left;">nearest cell, and the output keeps the categories</td>
</tr>
<tr class="even">
<td style="text-align: left;"><em>Output data type</em> (under Advanced Parameters) left at <code>Use Input Layer Data Type</code></td>
<td style="text-align: left;">no equivalent: bilinear output is floating point</td>
<td style="text-align: left;">QGIS rounds bilinear values back into the input’s integer type</td>
</tr>
<tr class="odd">
<td style="text-align: left;"><em>Output file resolution in target georeferenced units</em></td>
<td style="text-align: left;"><code>project(x, "EPSG:3844", res = 30)</code></td>
<td style="text-align: left;">same cell size, grids anchored at different corners</td>
</tr>
<tr class="even">
<td style="text-align: left;"><em>Georeferenced extents</em> plus resolution</td>
<td style="text-align: left;"><code>project(x, template)</code></td>
<td style="text-align: left;">the same grid in both, cell for cell</td>
</tr>
<tr class="odd">
<td style="text-align: left;"><strong>Layer Properties &gt; Symbology</strong>, <em>Resampling</em></td>
<td style="text-align: left;">none: it changes the screen, not the file</td>
<td style="text-align: left;">display only; nearest neighbour unless changed, according to the QGIS source</td>
</tr>
</tbody>
</table>
<p>The sections below measure each row.</p>
<div class="cell">
<div class="code-copy-outer-scaffold"><div class="sourceCode cell-code" id="cb1" style="background: #f1f3f5;"><pre class="sourceCode r code-with-copy"><code class="sourceCode r"><span id="cb1-1"><span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">library</span>(terra)</span>
<span id="cb1-2"><span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">library</span>(ggplot2)</span>
<span id="cb1-3"><span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">terraOptions</span>(<span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">progress =</span> <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">0</span>)</span>
<span id="cb1-4"></span>
<span id="cb1-5">te_paper  <span class="ot" style="color: #003B4F;
background-color: null;
font-style: inherit;">&lt;-</span> <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"#f5f4ee"</span>; te_ink    <span class="ot" style="color: #003B4F;
background-color: null;
font-style: inherit;">&lt;-</span> <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"#16241d"</span>; te_body   <span class="ot" style="color: #003B4F;
background-color: null;
font-style: inherit;">&lt;-</span> <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"#2c3a31"</span></span>
<span id="cb1-6">te_forest <span class="ot" style="color: #003B4F;
background-color: null;
font-style: inherit;">&lt;-</span> <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"#275139"</span>; te_rust   <span class="ot" style="color: #003B4F;
background-color: null;
font-style: inherit;">&lt;-</span> <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"#b5534e"</span>; te_gold   <span class="ot" style="color: #003B4F;
background-color: null;
font-style: inherit;">&lt;-</span> <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"#c9b458"</span></span>
<span id="cb1-7">te_line   <span class="ot" style="color: #003B4F;
background-color: null;
font-style: inherit;">&lt;-</span> <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"#dad9ca"</span></span>
<span id="cb1-8"></span>
<span id="cb1-9">theme_datasheet <span class="ot" style="color: #003B4F;
background-color: null;
font-style: inherit;">&lt;-</span> <span class="cf" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">function</span>() <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">theme_minimal</span>(<span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">base_size =</span> <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">12</span>) <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">+</span></span>
<span id="cb1-10">  <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">theme</span>(<span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">plot.background =</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">element_rect</span>(<span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">fill =</span> te_paper, <span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">colour =</span> <span class="cn" style="color: #8f5902;
background-color: null;
font-style: inherit;">NA</span>),</span>
<span id="cb1-11">        <span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">panel.background =</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">element_rect</span>(<span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">fill =</span> te_paper, <span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">colour =</span> <span class="cn" style="color: #8f5902;
background-color: null;
font-style: inherit;">NA</span>),</span>
<span id="cb1-12">        <span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">panel.grid.major =</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">element_line</span>(<span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">colour =</span> te_line, <span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">linewidth =</span> <span class="fl" style="color: #AD0000;
background-color: null;
font-style: inherit;">0.3</span>),</span>
<span id="cb1-13">        <span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">panel.grid.minor =</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">element_blank</span>(), <span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">text =</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">element_text</span>(<span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">colour =</span> te_body),</span>
<span id="cb1-14">        <span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">plot.title =</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">element_text</span>(<span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">colour =</span> te_ink, <span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">face =</span> <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"bold"</span>),</span>
<span id="cb1-15">        <span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">plot.subtitle =</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">element_text</span>(<span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">colour =</span> te_body), <span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">axis.text =</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">element_text</span>(<span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">colour =</span> te_body))</span>
<span id="cb1-16">class_col <span class="ot" style="color: #003B4F;
background-color: null;
font-style: inherit;">&lt;-</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">c</span>(<span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">water =</span> <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"#5b8aa6"</span>, <span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">wetland =</span> <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"#8fb3a3"</span>, <span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">grassland =</span> te_gold,</span>
<span id="cb1-17">               <span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">scrub =</span> te_rust, <span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">forest =</span> te_forest)</span>
<span id="cb1-18">terra_ver <span class="ot" style="color: #003B4F;
background-color: null;
font-style: inherit;">&lt;-</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">as.character</span>(<span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">packageVersion</span>(<span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"terra"</span>)); gdal_r <span class="ot" style="color: #003B4F;
background-color: null;
font-style: inherit;">&lt;-</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">gdal</span>(); proj_r <span class="ot" style="color: #003B4F;
background-color: null;
font-style: inherit;">&lt;-</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">gdal</span>(<span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">lib =</span> <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"proj"</span>)</span>
<span id="cb1-19">qgis_ver  <span class="ot" style="color: #003B4F;
background-color: null;
font-style: inherit;">&lt;-</span> <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"3.34.4"</span>; gdal_q <span class="ot" style="color: #003B4F;
background-color: null;
font-style: inherit;">&lt;-</span> <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"3.8.4"</span>; proj_q <span class="ot" style="color: #003B4F;
background-color: null;
font-style: inherit;">&lt;-</span> <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"9.4.0"</span>   <span class="co" style="color: #5E5E5E;
background-color: null;
font-style: inherit;"># qgis_process --version, where the files were made</span></span>
<span id="cb1-20">n_cells <span class="ot" style="color: #003B4F;
background-color: null;
font-style: inherit;">&lt;-</span> <span class="cf" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">function</span>(n) <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">sprintf</span>(<span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"%d %s"</span>, n, <span class="cf" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">if</span> (n <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">==</span> <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">1</span>) <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"cell"</span> <span class="cf" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">else</span> <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"cells"</span>)</span></code></pre></div></div>
</div>
</section>
<section id="two-rasters-written-by-r" class="level2">
<h2 id="two-rasters-written-by-r-h" class="anchored" data-anchor-id="two-rasters-written-by-r">Two rasters, written by R</h2>
<p>Both inputs are synthetic and sit in UTM zone 34 north, in a block of Transylvania. The land-cover map is 200 by 200 cells of 30 metres. Its patches are the areas closest to 70 random centres, and each patch gets one of five class codes at random: 1 water, 2 wetland, 3 grassland, 4 scrub, 5 forest. The codes are labels, not quantities, and because they are assigned at random, water often borders forest, which is what a real classification does too. The elevation model is 120 by 120 cells of 30 metres over part of the same block: a broad hill, a small conical knoll 30 metres high and 120 metres in radius, a gentle tilt to the east and half a metre of noise. The chunk writes both as GeoTIFFs next to this page, and those two files are the input to every QGIS command below.</p>
<div class="cell">
<div class="code-copy-outer-scaffold"><div class="sourceCode cell-code" id="cb2" style="background: #f1f3f5;"><pre class="sourceCode r code-with-copy"><code class="sourceCode r"><span id="cb2-1">utm <span class="ot" style="color: #003B4F;
background-color: null;
font-style: inherit;">&lt;-</span> <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"EPSG:32634"</span>; stereo <span class="ot" style="color: #003B4F;
background-color: null;
font-style: inherit;">&lt;-</span> <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"EPSG:3844"</span></span>
<span id="cb2-2">block <span class="ot" style="color: #003B4F;
background-color: null;
font-style: inherit;">&lt;-</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">rast</span>(<span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">nrows =</span> <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">200</span>, <span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">ncols =</span> <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">200</span>, <span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">xmin =</span> <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">650000</span>, <span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">xmax =</span> <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">656000</span>,</span>
<span id="cb2-3">              <span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">ymin =</span> <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">5176000</span>, <span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">ymax =</span> <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">5182000</span>, <span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">crs =</span> utm)</span>
<span id="cb2-4">block_xy <span class="ot" style="color: #003B4F;
background-color: null;
font-style: inherit;">&lt;-</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">xyFromCell</span>(block, <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">seq_len</span>(<span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">ncell</span>(block)))</span>
<span id="cb2-5">voronoi_cover <span class="ot" style="color: #003B4F;
background-color: null;
font-style: inherit;">&lt;-</span> <span class="cf" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">function</span>(n_patch) {   <span class="co" style="color: #5E5E5E;
background-color: null;
font-style: inherit;"># patches around random centres, random class codes</span></span>
<span id="cb2-6">  px <span class="ot" style="color: #003B4F;
background-color: null;
font-style: inherit;">&lt;-</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">runif</span>(n_patch, <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">650000</span>, <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">656000</span>); py <span class="ot" style="color: #003B4F;
background-color: null;
font-style: inherit;">&lt;-</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">runif</span>(n_patch, <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">5176000</span>, <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">5182000</span>)</span>
<span id="cb2-7">  code <span class="ot" style="color: #003B4F;
background-color: null;
font-style: inherit;">&lt;-</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">sample</span>(<span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">1</span><span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">:</span><span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">5</span>, n_patch, <span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">replace =</span> <span class="cn" style="color: #8f5902;
background-color: null;
font-style: inherit;">TRUE</span>)</span>
<span id="cb2-8">  nearest <span class="ot" style="color: #003B4F;
background-color: null;
font-style: inherit;">&lt;-</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">integer</span>(<span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">nrow</span>(block_xy))</span>
<span id="cb2-9">  <span class="cf" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">for</span> (b <span class="cf" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">in</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">split</span>(<span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">seq_len</span>(<span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">nrow</span>(block_xy)), <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">ceiling</span>(<span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">seq_len</span>(<span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">nrow</span>(block_xy)) <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">/</span> <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">2000</span>))) {</span>
<span id="cb2-10">    d2 <span class="ot" style="color: #003B4F;
background-color: null;
font-style: inherit;">&lt;-</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">outer</span>(block_xy[b, <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">1</span>], px, <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"-"</span>)<span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">^</span><span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">2</span> <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">+</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">outer</span>(block_xy[b, <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">2</span>], py, <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"-"</span>)<span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">^</span><span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">2</span></span>
<span id="cb2-11">    nearest[b] <span class="ot" style="color: #003B4F;
background-color: null;
font-style: inherit;">&lt;-</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">max.col</span>(<span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">-</span>d2, <span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">ties.method =</span> <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"first"</span>)</span>
<span id="cb2-12">  }</span>
<span id="cb2-13">  <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">setValues</span>(block, code[nearest])</span>
<span id="cb2-14">}</span>
<span id="cb2-15"><span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">set.seed</span>(<span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">20261012</span>)</span>
<span id="cb2-16">cover_made <span class="ot" style="color: #003B4F;
background-color: null;
font-style: inherit;">&lt;-</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">voronoi_cover</span>(<span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">70</span>); <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">names</span>(cover_made) <span class="ot" style="color: #003B4F;
background-color: null;
font-style: inherit;">&lt;-</span> <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"cover"</span></span>
<span id="cb2-17"><span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">writeRaster</span>(cover_made, <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"landcover-utm.tif"</span>, <span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">overwrite =</span> <span class="cn" style="color: #8f5902;
background-color: null;
font-style: inherit;">TRUE</span>, <span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">datatype =</span> <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"INT1U"</span>,</span>
<span id="cb2-18">            <span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">gdal =</span> <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"COMPRESS=DEFLATE"</span>)</span>
<span id="cb2-19">cover <span class="ot" style="color: #003B4F;
background-color: null;
font-style: inherit;">&lt;-</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">rast</span>(<span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"landcover-utm.tif"</span>)</span>
<span id="cb2-20">classes <span class="ot" style="color: #003B4F;
background-color: null;
font-style: inherit;">&lt;-</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">c</span>(<span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"water"</span>, <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"wetland"</span>, <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"grassland"</span>, <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"scrub"</span>, <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"forest"</span>)</span>
<span id="cb2-21"></span>
<span id="cb2-22">hill_xy <span class="ot" style="color: #003B4F;
background-color: null;
font-style: inherit;">&lt;-</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">c</span>(<span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">652260</span>, <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">5179160</span>); knoll_xy <span class="ot" style="color: #003B4F;
background-color: null;
font-style: inherit;">&lt;-</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">c</span>(<span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">653590</span>, <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">5178080</span>)</span>
<span id="cb2-23">surface <span class="ot" style="color: #003B4F;
background-color: null;
font-style: inherit;">&lt;-</span> <span class="cf" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">function</span>(x, y) {            <span class="co" style="color: #5E5E5E;
background-color: null;
font-style: inherit;"># the elevation model without its noise, metres</span></span>
<span id="cb2-24">  <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">420</span> <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">+</span> <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">180</span> <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">*</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">exp</span>(<span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">-</span>((x <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">-</span> hill_xy[<span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">1</span>])<span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">^</span><span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">2</span> <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">+</span> (y <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">-</span> hill_xy[<span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">2</span>])<span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">^</span><span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">2</span>) <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">/</span> (<span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">2</span> <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">*</span> <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">650</span><span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">^</span><span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">2</span>)) <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">+</span></span>
<span id="cb2-25">    <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">30</span> <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">*</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">pmax</span>(<span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">0</span>, <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">1</span> <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">-</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">sqrt</span>((x <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">-</span> knoll_xy[<span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">1</span>])<span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">^</span><span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">2</span> <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">+</span> (y <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">-</span> knoll_xy[<span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">2</span>])<span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">^</span><span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">2</span>) <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">/</span> <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">120</span>) <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">+</span></span>
<span id="cb2-26">    <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">40</span> <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">*</span> (x <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">-</span> <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">651000</span>) <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">/</span> <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">3600</span></span>
<span id="cb2-27">}</span>
<span id="cb2-28"><span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">set.seed</span>(<span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">20261013</span>)</span>
<span id="cb2-29">dem_grid <span class="ot" style="color: #003B4F;
background-color: null;
font-style: inherit;">&lt;-</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">rast</span>(<span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">nrows =</span> <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">120</span>, <span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">ncols =</span> <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">120</span>, <span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">xmin =</span> <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">651000</span>, <span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">xmax =</span> <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">654600</span>,</span>
<span id="cb2-30">                 <span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">ymin =</span> <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">5177000</span>, <span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">ymax =</span> <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">5180600</span>, <span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">crs =</span> utm)</span>
<span id="cb2-31">dem_xy   <span class="ot" style="color: #003B4F;
background-color: null;
font-style: inherit;">&lt;-</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">xyFromCell</span>(dem_grid, <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">seq_len</span>(<span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">ncell</span>(dem_grid)))</span>
<span id="cb2-32">dem_made <span class="ot" style="color: #003B4F;
background-color: null;
font-style: inherit;">&lt;-</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">setValues</span>(dem_grid, <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">surface</span>(dem_xy[, <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">1</span>], dem_xy[, <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">2</span>]) <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">+</span></span>
<span id="cb2-33">                        <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">rnorm</span>(<span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">ncell</span>(dem_grid), <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">0</span>, <span class="fl" style="color: #AD0000;
background-color: null;
font-style: inherit;">0.5</span>))</span>
<span id="cb2-34"><span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">names</span>(dem_made) <span class="ot" style="color: #003B4F;
background-color: null;
font-style: inherit;">&lt;-</span> <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"elevation"</span></span>
<span id="cb2-35"><span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">writeRaster</span>(dem_made, <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"dem-utm.tif"</span>, <span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">overwrite =</span> <span class="cn" style="color: #8f5902;
background-color: null;
font-style: inherit;">TRUE</span>, <span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">datatype =</span> <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"FLT4S"</span>,</span>
<span id="cb2-36">            <span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">gdal =</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">c</span>(<span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"COMPRESS=DEFLATE"</span>, <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"PREDICTOR=3"</span>))</span>
<span id="cb2-37">dem <span class="ot" style="color: #003B4F;
background-color: null;
font-style: inherit;">&lt;-</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">rast</span>(<span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"dem-utm.tif"</span>)</span>
<span id="cb2-38">cover_share <span class="ot" style="color: #003B4F;
background-color: null;
font-style: inherit;">&lt;-</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">prop.table</span>(<span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">table</span>(<span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">factor</span>(<span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">values</span>(cover)[, <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">1</span>], <span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">levels =</span> <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">1</span><span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">:</span><span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">5</span>)))</span></code></pre></div></div>
</div>
</section>
<section id="two-tools-two-defaults" class="level2">
<h2 id="two-tools-two-defaults-h" class="anchored" data-anchor-id="two-tools-two-defaults">Two tools, two defaults</h2>
<p>In QGIS the tool is <strong>Raster &gt; Projections &gt; Warp (Reproject)</strong>, which is the GDAL <code>gdalwarp</code> program behind a dialog, <code>gdal:warpreproject</code> in the Processing toolbox. Its <em>Resampling method to use</em> starts at <em>Nearest Neighbour</em>, and <code>qgis_process help gdal:warpreproject</code> prints the same thing: <code>RESAMPLING</code>, default value 0, and 0 is Nearest Neighbour. The commands below ran once each against QGIS 3.34.4 on Linux, in this post’s folder. The first is the default, the second asks for bilinear, and the rest are used further down. <code>OPTIONS=COMPRESS=DEFLATE</code> only compresses the files and does not change a value. On this build each run starts with two lines reading <code>ERROR: Status 2: File EPSG:3844 could not be found</code> and then completes normally; the outputs were not affected.</p>
<div class="code-copy-outer-scaffold"><div class="sourceCode" id="cb3" style="background: #f1f3f5;"><pre class="sourceCode bash code-with-copy"><code class="sourceCode bash"><span id="cb3-1"><span class="bu" style="color: null;
background-color: null;
font-style: inherit;">export</span> <span class="va" style="color: #111111;
background-color: null;
font-style: inherit;">QT_QPA_PLATFORM</span><span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span>offscreen</span>
<span id="cb3-2"><span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">warp()</span> <span class="kw" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">{</span>  <span class="co" style="color: #5E5E5E;
background-color: null;
font-style: inherit;"># input, output, then any extra parameters</span></span>
<span id="cb3-3">  <span class="ex" style="color: null;
background-color: null;
font-style: inherit;">qgis_process</span> run gdal:warpreproject <span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">--</span> INPUT=<span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"</span><span class="va" style="color: #111111;
background-color: null;
font-style: inherit;">$1</span><span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"</span> TARGET_CRS=EPSG:3844 <span class="dt" style="color: #AD0000;
background-color: null;
font-style: inherit;">\</span></span>
<span id="cb3-4">    OPTIONS=COMPRESS=DEFLATE OUTPUT=<span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"</span><span class="va" style="color: #111111;
background-color: null;
font-style: inherit;">$2</span><span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"</span> <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"</span><span class="va" style="color: #111111;
background-color: null;
font-style: inherit;">${@</span><span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">:</span><span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">3</span><span class="va" style="color: #111111;
background-color: null;
font-style: inherit;">}</span><span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"</span></span>
<span id="cb3-5"><span class="kw" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">}</span></span>
<span id="cb3-6"><span class="ex" style="color: null;
background-color: null;
font-style: inherit;">warp</span> landcover-utm.tif qgis-landcover-near.tif</span>
<span id="cb3-7"><span class="ex" style="color: null;
background-color: null;
font-style: inherit;">warp</span> landcover-utm.tif qgis-landcover-bilinear.tif RESAMPLING=1</span>
<span id="cb3-8"><span class="ex" style="color: null;
background-color: null;
font-style: inherit;">warp</span> landcover-utm.tif qgis-landcover-exact.tif EXTRA=<span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"-et 0"</span></span>
<span id="cb3-9"><span class="ex" style="color: null;
background-color: null;
font-style: inherit;">warp</span> landcover-utm.tif qgis-landcover-bilinear-exact.tif RESAMPLING=1 EXTRA=<span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"-et 0"</span></span>
<span id="cb3-10"><span class="ex" style="color: null;
background-color: null;
font-style: inherit;">warp</span> landcover-utm.tif qgis-landcover-res30.tif TARGET_RESOLUTION=30</span>
<span id="cb3-11"><span class="ex" style="color: null;
background-color: null;
font-style: inherit;">warp</span> landcover-utm.tif qgis-landcover-template.tif TARGET_RESOLUTION=30 <span class="dt" style="color: #AD0000;
background-color: null;
font-style: inherit;">\</span></span>
<span id="cb3-12">  TARGET_EXTENT=<span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"344400,350730,581820,588150 [EPSG:3844]"</span></span>
<span id="cb3-13"><span class="ex" style="color: null;
background-color: null;
font-style: inherit;">warp</span> dem-utm.tif qgis-dem-near.tif</span>
<span id="cb3-14"><span class="ex" style="color: null;
background-color: null;
font-style: inherit;">warp</span> dem-utm.tif qgis-dem-bilinear.tif RESAMPLING=1</span></code></pre></div></div>
<p>In <code>terra</code>, <code>project()</code> chooses when <code>method</code> is not given. The rule is two lines in the package source: if the raster is a factor, that is, has a category table, or is flagged as an RGB image, the method is <code>"near"</code>, and otherwise it is <code>"bilinear"</code>. <code>rast()</code> makes a factor only when the file carries category names or a raster attribute table, inside the GeoTIFF or beside it in a <code>.tif.aux.xml</code> or <code>.vat.dbf</code> file. A colour table alone does not count (and bilinear output drops it). The land-cover file here has none of these.</p>
<div class="cell">
<div class="code-copy-outer-scaffold"><div class="sourceCode cell-code" id="cb4" style="background: #f1f3f5;"><pre class="sourceCode r code-with-copy"><code class="sourceCode r"><span id="cb4-1">cover_is_factor <span class="ot" style="color: #003B4F;
background-color: null;
font-style: inherit;">&lt;-</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">is.factor</span>(cover)</span>
<span id="cb4-2">t_default <span class="ot" style="color: #003B4F;
background-color: null;
font-style: inherit;">&lt;-</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">project</span>(cover, stereo)                   <span class="co" style="color: #5E5E5E;
background-color: null;
font-style: inherit;"># terra, no method given</span></span>
<span id="cb4-3">t_near    <span class="ot" style="color: #003B4F;
background-color: null;
font-style: inherit;">&lt;-</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">project</span>(cover, stereo, <span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">method =</span> <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"near"</span>)</span>
<span id="cb4-4">q_near    <span class="ot" style="color: #003B4F;
background-color: null;
font-style: inherit;">&lt;-</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">rast</span>(<span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"qgis-landcover-near.tif"</span>)          <span class="co" style="color: #5E5E5E;
background-color: null;
font-style: inherit;"># QGIS, no method given</span></span>
<span id="cb4-5">q_bil     <span class="ot" style="color: #003B4F;
background-color: null;
font-style: inherit;">&lt;-</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">rast</span>(<span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"qgis-landcover-bilinear.tif"</span>)</span>
<span id="cb4-6">q_exact   <span class="ot" style="color: #003B4F;
background-color: null;
font-style: inherit;">&lt;-</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">rast</span>(<span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"qgis-landcover-exact.tif"</span>)</span>
<span id="cb4-7">q_bil_ex  <span class="ot" style="color: #003B4F;
background-color: null;
font-style: inherit;">&lt;-</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">rast</span>(<span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"qgis-landcover-bilinear-exact.tif"</span>)</span>
<span id="cb4-8">td <span class="ot" style="color: #003B4F;
background-color: null;
font-style: inherit;">&lt;-</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">values</span>(t_default)[, <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">1</span>]; ok <span class="ot" style="color: #003B4F;
background-color: null;
font-style: inherit;">&lt;-</span> <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">!</span><span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">is.na</span>(td)</span>
<span id="cb4-9">non_int   <span class="ot" style="color: #003B4F;
background-color: null;
font-style: inherit;">&lt;-</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">mean</span>(td[ok] <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">!=</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">round</span>(td[ok]))</span>
<span id="cb4-10">same_grid <span class="ot" style="color: #003B4F;
background-color: null;
font-style: inherit;">&lt;-</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">isTRUE</span>(<span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">all.equal</span>(<span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">as.vector</span>(<span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">ext</span>(q_near)), <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">as.vector</span>(<span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">ext</span>(t_default)))) <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">&amp;&amp;</span></span>
<span id="cb4-11">  <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">all</span>(<span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">dim</span>(q_near) <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">==</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">dim</span>(t_default))</span>
<span id="cb4-12">n_out     <span class="ot" style="color: #003B4F;
background-color: null;
font-style: inherit;">&lt;-</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">sum</span>(ok)</span>
<span id="cb4-13">diff_near  <span class="ot" style="color: #003B4F;
background-color: null;
font-style: inherit;">&lt;-</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">sum</span>(<span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">values</span>(q_near)[, <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">1</span>] <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">!=</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">values</span>(t_near)[, <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">1</span>], <span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">na.rm =</span> <span class="cn" style="color: #8f5902;
background-color: null;
font-style: inherit;">TRUE</span>)</span>
<span id="cb4-14">diff_exact <span class="ot" style="color: #003B4F;
background-color: null;
font-style: inherit;">&lt;-</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">sum</span>(<span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">values</span>(q_exact)[, <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">1</span>] <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">!=</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">values</span>(t_near)[, <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">1</span>], <span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">na.rm =</span> <span class="cn" style="color: #8f5902;
background-color: null;
font-style: inherit;">TRUE</span>)</span>
<span id="cb4-15">diff_bil   <span class="ot" style="color: #003B4F;
background-color: null;
font-style: inherit;">&lt;-</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">sum</span>(<span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">values</span>(q_bil)[, <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">1</span>] <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">!=</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">round</span>(td), <span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">na.rm =</span> <span class="cn" style="color: #8f5902;
background-color: null;
font-style: inherit;">TRUE</span>)</span>
<span id="cb4-16">diff_bil_ex <span class="ot" style="color: #003B4F;
background-color: null;
font-style: inherit;">&lt;-</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">sum</span>(<span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">values</span>(q_bil_ex)[, <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">1</span>] <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">!=</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">round</span>(td), <span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">na.rm =</span> <span class="cn" style="color: #8f5902;
background-color: null;
font-style: inherit;">TRUE</span>)</span>
<span id="cb4-17">q_codes    <span class="ot" style="color: #003B4F;
background-color: null;
font-style: inherit;">&lt;-</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">sort</span>(<span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">unique</span>(<span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">na.omit</span>(<span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">values</span>(q_near)[, <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">1</span>])))</span>
<span id="cb4-18"><span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">stopifnot</span>(<span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">!</span>cover_is_factor, non_int <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">&gt;</span> <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">0</span>)   <span class="co" style="color: #5E5E5E;
background-color: null;
font-style: inherit;"># the default went bilinear on this terra</span></span>
<span id="cb4-19"><span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">stopifnot</span>(same_grid, diff_exact <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">==</span> <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">0</span>)   <span class="co" style="color: #5E5E5E;
background-color: null;
font-style: inherit;"># stop the page if the QGIS files and terra's grid part ways</span></span></code></pre></div></div>
</div>
<p><code>is.factor()</code> on the map read from its file is FALSE, so <code>project()</code> with no method went bilinear, and 7.7 per cent of the 40001 output cells hold a value that is not a whole number. The QGIS default output holds only the codes 1, 2, 3, 4, 5. The two tools agree on the grid itself, the same extent and the same number of rows and columns, because both ask GDAL for the suggested output grid.</p>
<p>With the method matched, QGIS’s default output and <code>project(method = "near")</code> differ in 1 cell out of 40001. <code>gdalwarp</code> transforms coordinates exactly only at a sparse set of points and interpolates in between while the error stays under an eighth of a cell (its <code>-et</code> option); <code>terra</code> uses the exact transformation, so a cell centre very close to a cell edge can pick a different neighbour. With <code>EXTRA="-et 0"</code> the shortcut is off and the difference is 0 cells. The QGIS bilinear output is a byte raster like its input, because <em>Output data type</em> defaults to the input’s type, and it differs from <code>terra</code>’s bilinear values rounded to whole numbers in 2 cells; with <code>-et 0</code>, in 0 cells.</p>
</section>
<section id="what-bilinear-does-to-class-codes" class="level2">
<h2 id="what-bilinear-does-to-class-codes-h" class="anchored" data-anchor-id="what-bilinear-does-to-class-codes">What bilinear does to class codes</h2>
<p>Averaging the codes on either side of a boundary is harmless where the two classes have neighbouring codes: a cell between grassland (3) and scrub (4) gets a value between 3 and 4, and rounding returns one of the two. It is not harmless between water (1) and forest (5), where the average passes through 2, 3 and 4, and rounding produces a strip of wetland, grassland or scrub that does not exist on the ground.</p>
<p>To count those cells without counting ordinary shifts, each output cell centre is transformed back into the old grid, and its code is compared with the codes present in the 3 by 3 block of old cells around the one it falls in. Nearest neighbour copies the cell the centre falls in or, with the <code>gdalwarp</code> shortcut, one next to it; bilinear averages four cells inside the same block. A code absent from the block cannot come from moving a boundary by less than a cell, so it is counted as invented. The arithmetic can also land on a code that happens to occur elsewhere in the block, and those cells are not counted, so the count is, if anything, slightly low.</p>
<div class="cell">
<div class="code-copy-outer-scaffold"><div class="sourceCode cell-code" id="cb5" style="background: #f1f3f5;"><pre class="sourceCode r code-with-copy"><code class="sourceCode r"><span id="cb5-1">code_check <span class="ot" style="color: #003B4F;
background-color: null;
font-style: inherit;">&lt;-</span> <span class="cf" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">function</span>(lc, out) {</span>
<span id="cb5-2">  present <span class="ot" style="color: #003B4F;
background-color: null;
font-style: inherit;">&lt;-</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">rast</span>(<span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">lapply</span>(<span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">1</span><span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">:</span><span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">5</span>, <span class="cf" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">function</span>(k) <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">focal</span>(lc <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">==</span> k, <span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">w =</span> <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">3</span>, <span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">fun =</span> <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"max"</span>, <span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">na.rm =</span> <span class="cn" style="color: #8f5902;
background-color: null;
font-style: inherit;">TRUE</span>)))</span>
<span id="cb5-3">  v <span class="ot" style="color: #003B4F;
background-color: null;
font-style: inherit;">&lt;-</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">values</span>(out)[, <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">1</span>]; keep <span class="ot" style="color: #003B4F;
background-color: null;
font-style: inherit;">&lt;-</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">which</span>(<span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">!</span><span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">is.na</span>(v))</span>
<span id="cb5-4">  back <span class="ot" style="color: #003B4F;
background-color: null;
font-style: inherit;">&lt;-</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">project</span>(<span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">xyFromCell</span>(out, keep), stereo, utm)   <span class="co" style="color: #5E5E5E;
background-color: null;
font-style: inherit;"># output centres in the old grid</span></span>
<span id="cb5-5">  in_block <span class="ot" style="color: #003B4F;
background-color: null;
font-style: inherit;">&lt;-</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">as.matrix</span>(<span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">extract</span>(present, back))</span>
<span id="cb5-6">  here <span class="ot" style="color: #003B4F;
background-color: null;
font-style: inherit;">&lt;-</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">extract</span>(lc, back)[, <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">1</span>]                         <span class="co" style="color: #5E5E5E;
background-color: null;
font-style: inherit;"># the old cell the centre falls in</span></span>
<span id="cb5-7">  code <span class="ot" style="color: #003B4F;
background-color: null;
font-style: inherit;">&lt;-</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">round</span>(v[keep]); inv <span class="ot" style="color: #003B4F;
background-color: null;
font-style: inherit;">&lt;-</span> in_block[<span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">cbind</span>(<span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">seq_along</span>(code), code)] <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">!=</span> <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">1</span></span>
<span id="cb5-8">  flag <span class="ot" style="color: #003B4F;
background-color: null;
font-style: inherit;">&lt;-</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">rep</span>(<span class="cn" style="color: #8f5902;
background-color: null;
font-style: inherit;">NA_real_</span>, <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">length</span>(v)); flag[keep] <span class="ot" style="color: #003B4F;
background-color: null;
font-style: inherit;">&lt;-</span> inv  <span class="co" style="color: #5E5E5E;
background-color: null;
font-style: inherit;"># kept as a raster for the figure</span></span>
<span id="cb5-9">  <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">structure</span>(<span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">c</span>(<span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">edge =</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">mean</span>(<span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">values</span>(<span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">sum</span>(present))[, <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">1</span>] <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">&gt;</span> <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">1</span>), <span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">non_int =</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">mean</span>(v[keep] <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">!=</span> code),</span>
<span id="cb5-10">              <span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">changed =</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">mean</span>(code <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">!=</span> here), <span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">invented =</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">mean</span>(inv)),</span>
<span id="cb5-11">            <span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">flag =</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">setValues</span>(<span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">rast</span>(out), flag))</span>
<span id="cb5-12">}</span>
<span id="cb5-13">chk_qnear <span class="ot" style="color: #003B4F;
background-color: null;
font-style: inherit;">&lt;-</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">code_check</span>(cover, q_near)</span>
<span id="cb5-14">chk_tdef  <span class="ot" style="color: #003B4F;
background-color: null;
font-style: inherit;">&lt;-</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">code_check</span>(cover, t_default)</span>
<span id="cb5-15">chk_qbil  <span class="ot" style="color: #003B4F;
background-color: null;
font-style: inherit;">&lt;-</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">code_check</span>(cover, q_bil)</span>
<span id="cb5-16">share_of <span class="ot" style="color: #003B4F;
background-color: null;
font-style: inherit;">&lt;-</span> <span class="cf" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">function</span>(r) {</span>
<span id="cb5-17">  v <span class="ot" style="color: #003B4F;
background-color: null;
font-style: inherit;">&lt;-</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">round</span>(<span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">values</span>(r)[, <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">1</span>]); <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">prop.table</span>(<span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">table</span>(<span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">factor</span>(v[<span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">!</span><span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">is.na</span>(v)], <span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">levels =</span> <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">1</span><span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">:</span><span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">5</span>)))</span>
<span id="cb5-18">}</span>
<span id="cb5-19">share_tab <span class="ot" style="color: #003B4F;
background-color: null;
font-style: inherit;">&lt;-</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">rbind</span>(cover_share, <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">share_of</span>(q_near), <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">share_of</span>(t_default), <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">share_of</span>(q_bil))</span>
<span id="cb5-20"><span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">dimnames</span>(share_tab) <span class="ot" style="color: #003B4F;
background-color: null;
font-style: inherit;">&lt;-</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">list</span>(<span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">c</span>(<span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"old map, UTM 34N"</span>, <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"QGIS default (nearest)"</span>,</span>
<span id="cb5-21">                              <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"terra default (bilinear), rounded"</span>, <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"QGIS bilinear (byte output)"</span>),</span>
<span id="cb5-22">                            classes)</span>
<span id="cb5-23">knitr<span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">::</span><span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">kable</span>(share_tab, <span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">digits =</span> <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">4</span>,</span>
<span id="cb5-24">             <span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">caption =</span> <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"Share of cells in each class, before and after reprojection to Stereo70."</span>)</span></code></pre></div></div>
<div class="cell-output-display">
<table class="caption-top table table-sm table-striped small">
<caption>Share of cells in each class, before and after reprojection to Stereo70.</caption>
<colgroup>
<col style="width: 46%">
<col style="width: 9%">
<col style="width: 10%">
<col style="width: 13%">
<col style="width: 9%">
<col style="width: 9%">
</colgroup>
<thead>
<tr class="header">
<th style="text-align: left;"></th>
<th style="text-align: right;">water</th>
<th style="text-align: right;">wetland</th>
<th style="text-align: right;">grassland</th>
<th style="text-align: right;">scrub</th>
<th style="text-align: right;">forest</th>
</tr>
</thead>
<tbody>
<tr class="odd">
<td style="text-align: left;">old map, UTM 34N</td>
<td style="text-align: right;">0.2595</td>
<td style="text-align: right;">0.2122</td>
<td style="text-align: right;">0.1024</td>
<td style="text-align: right;">0.2082</td>
<td style="text-align: right;">0.2177</td>
</tr>
<tr class="even">
<td style="text-align: left;">QGIS default (nearest)</td>
<td style="text-align: right;">0.2595</td>
<td style="text-align: right;">0.2122</td>
<td style="text-align: right;">0.1024</td>
<td style="text-align: right;">0.2083</td>
<td style="text-align: right;">0.2177</td>
</tr>
<tr class="odd">
<td style="text-align: left;">terra default (bilinear), rounded</td>
<td style="text-align: right;">0.2522</td>
<td style="text-align: right;">0.2146</td>
<td style="text-align: right;">0.1127</td>
<td style="text-align: right;">0.2104</td>
<td style="text-align: right;">0.2100</td>
</tr>
<tr class="even">
<td style="text-align: left;">QGIS bilinear (byte output)</td>
<td style="text-align: right;">0.2522</td>
<td style="text-align: right;">0.2146</td>
<td style="text-align: right;">0.1127</td>
<td style="text-align: right;">0.2104</td>
<td style="text-align: right;">0.2100</td>
</tr>
</tbody>
</table>
</div>
</div>
<p>Of the cells in the rounded <code>terra</code> default, 3.1 per cent carry a different class from the old cell their centre falls in, and 2.9 per cent carry a class found nowhere in the surrounding block. QGIS’s bilinear output, rounded by GDAL, invents classes in 2.9 per cent of its cells, the same cells give or take the shortcut, and because it is stored as whole numbers nothing about it looks wrong. QGIS’s nearest neighbour output differs from the old cell under the centre in 1 cell, the shortcut again, and its count of invented cells is 0, which is what a measure that ignores shifts of less than a cell has to return for a method that only copies.</p>
<p>The class shares follow. The nearest neighbour map keeps every share to within 0.0001. In the rounded bilinear map the two classes at the ends of the code list lose, water from 0.2595 to 0.2522 and forest from 0.2177 to 0.2100, and grassland, the middle code, gains, from 0.1024 to 0.1127. That direction comes from the numbering, not from the landscape: averaging can only add codes that lie strictly between the codes it averages, the middle code lies between more pairs of codes than any other, and the two end codes lie between none.</p>
<div class="cell">
<div class="code-copy-outer-scaffold"><div class="sourceCode cell-code" id="cb6" style="background: #f1f3f5;"><pre class="sourceCode r code-with-copy"><code class="sourceCode r"><span id="cb6-1">inv_r  <span class="ot" style="color: #003B4F;
background-color: null;
font-style: inherit;">&lt;-</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">attr</span>(chk_tdef, <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"flag"</span>)</span>
<span id="cb6-2">dens   <span class="ot" style="color: #003B4F;
background-color: null;
font-style: inherit;">&lt;-</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">focal</span>(inv_r, <span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">w =</span> <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">25</span>, <span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">fun =</span> <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"sum"</span>, <span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">na.rm =</span> <span class="cn" style="color: #8f5902;
background-color: null;
font-style: inherit;">TRUE</span>)</span>
<span id="cb6-3">centre <span class="ot" style="color: #003B4F;
background-color: null;
font-style: inherit;">&lt;-</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">xyFromCell</span>(dens, <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">which.max</span>(<span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">values</span>(dens)[, <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">1</span>]))</span>
<span id="cb6-4">zoom   <span class="ot" style="color: #003B4F;
background-color: null;
font-style: inherit;">&lt;-</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">ext</span>(centre[<span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">1</span>] <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">-</span> <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">390</span>, centre[<span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">1</span>] <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">+</span> <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">390</span>, centre[<span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">2</span>] <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">-</span> <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">390</span>, centre[<span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">2</span>] <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">+</span> <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">390</span>)</span>
<span id="cb6-5">panel_df <span class="ot" style="color: #003B4F;
background-color: null;
font-style: inherit;">&lt;-</span> <span class="cf" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">function</span>(r, lab) {</span>
<span id="cb6-6">  d <span class="ot" style="color: #003B4F;
background-color: null;
font-style: inherit;">&lt;-</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">as.data.frame</span>(<span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">round</span>(<span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">crop</span>(r, zoom)), <span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">xy =</span> <span class="cn" style="color: #8f5902;
background-color: null;
font-style: inherit;">TRUE</span>, <span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">na.rm =</span> <span class="cn" style="color: #8f5902;
background-color: null;
font-style: inherit;">TRUE</span>)</span>
<span id="cb6-7">  <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">data.frame</span>(<span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">x =</span> d<span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">$</span>x, <span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">y =</span> d<span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">$</span>y, <span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">class =</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">factor</span>(classes[d[, <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">3</span>]], <span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">levels =</span> classes), <span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">panel =</span> lab)</span>
<span id="cb6-8">}</span>
<span id="cb6-9">labs2 <span class="ot" style="color: #003B4F;
background-color: null;
font-style: inherit;">&lt;-</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">c</span>(<span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"QGIS default: nearest"</span>, <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"terra default: bilinear, rounded"</span>)</span>
<span id="cb6-10">zoom_df <span class="ot" style="color: #003B4F;
background-color: null;
font-style: inherit;">&lt;-</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">rbind</span>(<span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">panel_df</span>(q_near, labs2[<span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">1</span>]), <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">panel_df</span>(t_default, labs2[<span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">2</span>]))</span>
<span id="cb6-11">zoom_df<span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">$</span>panel <span class="ot" style="color: #003B4F;
background-color: null;
font-style: inherit;">&lt;-</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">factor</span>(zoom_df<span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">$</span>panel, <span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">levels =</span> labs2)</span>
<span id="cb6-12">ring_df <span class="ot" style="color: #003B4F;
background-color: null;
font-style: inherit;">&lt;-</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">as.data.frame</span>(<span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">crop</span>(inv_r, zoom), <span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">xy =</span> <span class="cn" style="color: #8f5902;
background-color: null;
font-style: inherit;">TRUE</span>, <span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">na.rm =</span> <span class="cn" style="color: #8f5902;
background-color: null;
font-style: inherit;">TRUE</span>)</span>
<span id="cb6-13">ring_df <span class="ot" style="color: #003B4F;
background-color: null;
font-style: inherit;">&lt;-</span> ring_df[ring_df[, <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">3</span>] <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">==</span> <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">1</span>, <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">c</span>(<span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"x"</span>, <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"y"</span>)]; ring_df<span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">$</span>panel <span class="ot" style="color: #003B4F;
background-color: null;
font-style: inherit;">&lt;-</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">factor</span>(labs2[<span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">2</span>], <span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">levels =</span> labs2)</span>
<span id="cb6-14"><span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">ggplot</span>(zoom_df, <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">aes</span>(x, y)) <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">+</span></span>
<span id="cb6-15">  <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">geom_raster</span>(<span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">aes</span>(<span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">fill =</span> class)) <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">+</span></span>
<span id="cb6-16">  <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">geom_point</span>(<span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">data =</span> ring_df, <span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">shape =</span> <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">21</span>, <span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">size =</span> <span class="fl" style="color: #AD0000;
background-color: null;
font-style: inherit;">1.6</span>, <span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">stroke =</span> <span class="fl" style="color: #AD0000;
background-color: null;
font-style: inherit;">0.6</span>, <span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">colour =</span> te_ink,</span>
<span id="cb6-17">             <span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">fill =</span> te_paper) <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">+</span></span>
<span id="cb6-18">  <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">facet_wrap</span>(<span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">~</span> panel) <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">+</span></span>
<span id="cb6-19">  <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">scale_fill_manual</span>(<span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">values =</span> class_col, <span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">name =</span> <span class="cn" style="color: #8f5902;
background-color: null;
font-style: inherit;">NULL</span>, <span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">drop =</span> <span class="cn" style="color: #8f5902;
background-color: null;
font-style: inherit;">FALSE</span>) <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">+</span></span>
<span id="cb6-20">  <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">coord_equal</span>(<span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">expand =</span> <span class="cn" style="color: #8f5902;
background-color: null;
font-style: inherit;">FALSE</span>) <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">+</span></span>
<span id="cb6-21">  <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">labs</span>(<span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">x =</span> <span class="cn" style="color: #8f5902;
background-color: null;
font-style: inherit;">NULL</span>, <span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">y =</span> <span class="cn" style="color: #8f5902;
background-color: null;
font-style: inherit;">NULL</span>, <span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">title =</span> <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"The same boundary, reprojected twice"</span>,</span>
<span id="cb6-22">       <span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">subtitle =</span> <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"rings: a class absent from the old 3 x 3 block"</span>) <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">+</span></span>
<span id="cb6-23">  <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">theme_datasheet</span>() <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">+</span></span>
<span id="cb6-24">  <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">theme</span>(<span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">axis.text =</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">element_blank</span>(), <span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">panel.grid.major =</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">element_blank</span>(),</span>
<span id="cb6-25">        <span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">legend.position =</span> <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"bottom"</span>)</span></code></pre></div></div>
<div class="cell-output cell-output-stderr">
<pre><code>Warning: Raster pixels are placed at uneven horizontal intervals and will be shifted
ℹ Consider using `geom_tile()` instead.
Raster pixels are placed at uneven horizontal intervals and will be shifted
ℹ Consider using `geom_tile()` instead.</code></pre>
</div>
<div class="cell-output-display">
<div id="fig-border" class="quarto-float quarto-figure quarto-figure-center anchored" alt="Two square map panels of the same small window, side by side, coloured by land-cover class: water blue, wetland pale green, grassland gold, scrub rust and forest dark green. Both show a large rust scrub patch on the left, water to its right and along the top, and a dark green forest strip at the lower right. The left panel, QGIS default: nearest, holds only those three colours, with stepped boundaries. The right panel, terra default: bilinear, rounded, has the same patches edged by strips one cell wide of gold grassland and pale green wetland, along the scrub and water boundary, the water and forest boundary and the left edge, and almost every strip cell carries a small white ring; two single ringed rust cells sit on the water and forest boundary. A legend of the five classes runs along the bottom.">
<figure class="quarto-float quarto-float-fig figure">
<div aria-describedby="fig-border-caption-0ceaefa1-69ba-4598-a22c-09a6ac19f8ca">
<img src="https://tidyecology.com/posts/reprojecting-a-raster-in-qgis-and-r/index_files/figure-html/fig-border-1.png" class="img-fluid figure-img" alt="Two square map panels of the same small window, side by side, coloured by land-cover class: water blue, wetland pale green, grassland gold, scrub rust and forest dark green. Both show a large rust scrub patch on the left, water to its right and along the top, and a dark green forest strip at the lower right. The left panel, QGIS default: nearest, holds only those three colours, with stepped boundaries. The right panel, terra default: bilinear, rounded, has the same patches edged by strips one cell wide of gold grassland and pale green wetland, along the scrub and water boundary, the water and forest boundary and the left edge, and almost every strip cell carries a small white ring; two single ringed rust cells sit on the water and forest boundary. A legend of the five classes runs along the bottom." width="720">
</div>
<figcaption class="quarto-float-caption-bottom quarto-float-caption quarto-float-fig" id="fig-border-caption-0ceaefa1-69ba-4598-a22c-09a6ac19f8ca">
Figure&nbsp;1: A small window of the map after reprojection to Stereo70, placed where invented cells are densest. Left: QGIS with its default, nearest neighbour. Right: terra with its default, bilinear, rounded to the nearest code. Cells marked with a ring hold a class that does not occur in the old 3 by 3 block around them.
</figcaption>
</figure>
</div>
</div>
</div>
<p>How much of a map this touches depends on how much of it lies on a boundary, because bilinear only makes a non-integer value where the four old cells around a point disagree. The chunk below repeats the check on five new maps built the same way, with fewer or more patches, and records for each the share of old cells next to a different class, which you can compute for your own map before reprojecting it.</p>
<div class="cell">
<div class="code-copy-outer-scaffold"><div class="sourceCode cell-code" id="cb8" style="background: #f1f3f5;"><pre class="sourceCode r code-with-copy"><code class="sourceCode r"><span id="cb8-1">n_patches <span class="ot" style="color: #003B4F;
background-color: null;
font-style: inherit;">&lt;-</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">c</span>(<span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">20</span>, <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">70</span>, <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">250</span>, <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">900</span>, <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">3200</span>); <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">set.seed</span>(<span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">20261014</span>)</span>
<span id="cb8-2">sweep <span class="ot" style="color: #003B4F;
background-color: null;
font-style: inherit;">&lt;-</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">data.frame</span>(<span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">patches =</span> n_patches, <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">t</span>(<span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">sapply</span>(n_patches, <span class="cf" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">function</span>(n) {</span>
<span id="cb8-3">  lc <span class="ot" style="color: #003B4F;
background-color: null;
font-style: inherit;">&lt;-</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">voronoi_cover</span>(n); <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">code_check</span>(lc, <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">project</span>(lc, stereo)) })))</span>
<span id="cb8-4">ratio_nonint <span class="ot" style="color: #003B4F;
background-color: null;
font-style: inherit;">&lt;-</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">range</span>(sweep<span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">$</span>non_int <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">/</span> sweep<span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">$</span>edge)</span>
<span id="cb8-5">ratio_inv    <span class="ot" style="color: #003B4F;
background-color: null;
font-style: inherit;">&lt;-</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">range</span>(sweep<span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">$</span>invented <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">/</span> sweep<span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">$</span>edge)</span></code></pre></div></div>
</div>
<p>The share of output cells with a non-integer value runs from 0.50 to 0.61 times the share of old cells on a boundary, and the share with an invented class from 0.15 to 0.17 times. On the most fragmented of the five maps, 80 per cent of the old cells are on a boundary, 49 per cent of the output is not a whole number and 12 per cent is an invented class. The more scattered single cells a classification has, the further towards that end it sits.</p>
</section>
<section id="telling-terra-that-the-codes-are-classes" class="level2">
<h2 id="telling-terra-that-the-codes-are-classes-h" class="anchored" data-anchor-id="telling-terra-that-the-codes-are-classes">Telling terra that the codes are classes</h2>
<p>The usual advice, as in Lovelace, Nowosad and Muenchow’s Geocomputation with R (2019; free online as a later edition at <a href="https://r.geocompx.org/reproj-geo-data.html">r.geocompx.org</a>), is nearest neighbour for a categorical raster and bilinear for a continuous one. The catch is that <code>terra</code> can only follow it if the raster says which kind it is. There are two fixes on the R side and both are one line. Pass <code>method = "near"</code>, or give the raster its category table before projecting, so that <code>terra</code> knows the codes are labels. With the table in place the default switches to nearest, and the output keeps the table.</p>
<div class="cell">
<div class="code-copy-outer-scaffold"><div class="sourceCode cell-code" id="cb9" style="background: #f1f3f5;"><pre class="sourceCode r code-with-copy"><code class="sourceCode r"><span id="cb9-1">cover_lab <span class="ot" style="color: #003B4F;
background-color: null;
font-style: inherit;">&lt;-</span> cover</span>
<span id="cb9-2"><span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">levels</span>(cover_lab) <span class="ot" style="color: #003B4F;
background-color: null;
font-style: inherit;">&lt;-</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">data.frame</span>(<span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">id =</span> <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">1</span><span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">:</span><span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">5</span>, <span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">cover =</span> classes)</span>
<span id="cb9-3">t_lab <span class="ot" style="color: #003B4F;
background-color: null;
font-style: inherit;">&lt;-</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">project</span>(cover_lab, stereo)</span>
<span id="cb9-4">lab_is_factor <span class="ot" style="color: #003B4F;
background-color: null;
font-style: inherit;">&lt;-</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">is.factor</span>(t_lab)</span>
<span id="cb9-5">lab_same <span class="ot" style="color: #003B4F;
background-color: null;
font-style: inherit;">&lt;-</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">identical</span>(<span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">as.vector</span>(<span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">values</span>(t_lab)), <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">as.vector</span>(<span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">values</span>(t_near)))</span>
<span id="cb9-6"><span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">stopifnot</span>(lab_is_factor, lab_same)</span></code></pre></div></div>
</div>
<p>The projected map with a category table is still a factor, and its cells are identical to those from <code>method = "near"</code>. Setting the table is the better habit of the two, because it also travels with the map into <code>plot()</code>, <code>freq()</code> and anything else that reads categories.</p>
</section>
<section id="a-dem-nearest-never-alters-a-value-bilinear-keeps-the-shape" class="level2">
<h2 id="a-dem-nearest-never-alters-a-value-bilinear-keeps-the-shape-h" class="anchored" data-anchor-id="a-dem-nearest-never-alters-a-value-bilinear-keeps-the-shape">A DEM: nearest never alters a value, bilinear keeps the shape</h2>
<p>For an elevation model the question turns round. Averaging elevations is what you want; copying a cell that is up to half a cell away moves the surface sideways. The QGIS default and the <code>terra</code> default are compared below on the elevation model, with the two QGIS outputs read from their files.</p>
<div class="cell">
<div class="code-copy-outer-scaffold"><div class="sourceCode cell-code" id="cb10" style="background: #f1f3f5;"><pre class="sourceCode r code-with-copy"><code class="sourceCode r"><span id="cb10-1">q_dem_near <span class="ot" style="color: #003B4F;
background-color: null;
font-style: inherit;">&lt;-</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">rast</span>(<span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"qgis-dem-near.tif"</span>); q_dem_bil <span class="ot" style="color: #003B4F;
background-color: null;
font-style: inherit;">&lt;-</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">rast</span>(<span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"qgis-dem-bilinear.tif"</span>)</span>
<span id="cb10-2">t_dem_bil  <span class="ot" style="color: #003B4F;
background-color: null;
font-style: inherit;">&lt;-</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">project</span>(dem, stereo); t_dem_near <span class="ot" style="color: #003B4F;
background-color: null;
font-style: inherit;">&lt;-</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">project</span>(dem, stereo, <span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">method =</span> <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"near"</span>)</span>
<span id="cb10-3">dem_diff_near <span class="ot" style="color: #003B4F;
background-color: null;
font-style: inherit;">&lt;-</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">sum</span>(<span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">values</span>(q_dem_near)[, <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">1</span>] <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">!=</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">values</span>(t_dem_near)[, <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">1</span>], <span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">na.rm =</span> <span class="cn" style="color: #8f5902;
background-color: null;
font-style: inherit;">TRUE</span>)</span>
<span id="cb10-4">dem_gap_bil   <span class="ot" style="color: #003B4F;
background-color: null;
font-style: inherit;">&lt;-</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">max</span>(<span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">abs</span>(<span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">values</span>(q_dem_bil)[, <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">1</span>] <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">-</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">values</span>(t_dem_bil)[, <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">1</span>]), <span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">na.rm =</span> <span class="cn" style="color: #8f5902;
background-color: null;
font-style: inherit;">TRUE</span>)</span>
<span id="cb10-5">peak_in <span class="ot" style="color: #003B4F;
background-color: null;
font-style: inherit;">&lt;-</span> <span class="cf" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">function</span>(r, xy, half) {       <span class="co" style="color: #5E5E5E;
background-color: null;
font-style: inherit;"># highest cell within a square around a point</span></span>
<span id="cb10-6">  e <span class="ot" style="color: #003B4F;
background-color: null;
font-style: inherit;">&lt;-</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">ext</span>(xy[<span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">1</span>] <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">-</span> half, xy[<span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">1</span>] <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">+</span> half, xy[<span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">2</span>] <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">-</span> half, xy[<span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">2</span>] <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">+</span> half)</span>
<span id="cb10-7">  <span class="cf" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">if</span> (<span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">crs</span>(r) <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">!=</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">crs</span>(dem)) e <span class="ot" style="color: #003B4F;
background-color: null;
font-style: inherit;">&lt;-</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">ext</span>(<span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">project</span>(e, utm, stereo))</span>
<span id="cb10-8">  <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">max</span>(<span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">values</span>(<span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">crop</span>(r, e)), <span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">na.rm =</span> <span class="cn" style="color: #8f5902;
background-color: null;
font-style: inherit;">TRUE</span>)</span>
<span id="cb10-9">}</span>
<span id="cb10-10">dem_row <span class="ot" style="color: #003B4F;
background-color: null;
font-style: inherit;">&lt;-</span> <span class="cf" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">function</span>(r) {</span>
<span id="cb10-11">  v <span class="ot" style="color: #003B4F;
background-color: null;
font-style: inherit;">&lt;-</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">values</span>(r)[, <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">1</span>]</span>
<span id="cb10-12">  <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">c</span>(<span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">min =</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">min</span>(v, <span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">na.rm =</span> <span class="cn" style="color: #8f5902;
background-color: null;
font-style: inherit;">TRUE</span>), <span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">max =</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">max</span>(v, <span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">na.rm =</span> <span class="cn" style="color: #8f5902;
background-color: null;
font-style: inherit;">TRUE</span>), <span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">mean =</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">mean</span>(v, <span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">na.rm =</span> <span class="cn" style="color: #8f5902;
background-color: null;
font-style: inherit;">TRUE</span>),</span>
<span id="cb10-13">    <span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">hill =</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">peak_in</span>(r, hill_xy, <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">300</span>), <span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">knoll =</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">peak_in</span>(r, knoll_xy, <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">150</span>))</span>
<span id="cb10-14">}</span>
<span id="cb10-15">dem_tab <span class="ot" style="color: #003B4F;
background-color: null;
font-style: inherit;">&lt;-</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">rbind</span>(<span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">dem_row</span>(dem), <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">dem_row</span>(q_dem_near), <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">dem_row</span>(t_dem_bil))</span>
<span id="cb10-16"><span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">rownames</span>(dem_tab) <span class="ot" style="color: #003B4F;
background-color: null;
font-style: inherit;">&lt;-</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">c</span>(<span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"old DEM, UTM 34N"</span>, <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"QGIS default (nearest)"</span>, <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"terra default (bilinear)"</span>)</span>
<span id="cb10-17">knitr<span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">::</span><span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">kable</span>(dem_tab, <span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">digits =</span> <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">2</span>, <span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">col.names =</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">c</span>(<span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"min"</span>, <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"max"</span>, <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"mean"</span>, <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"hill top"</span>, <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"knoll top"</span>),</span>
<span id="cb10-18">             <span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">caption =</span> <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"Elevation in metres, before and after reprojection to Stereo70."</span>)</span></code></pre></div></div>
<div class="cell-output-display">
<table class="caption-top table table-sm table-striped small">
<caption>Elevation in metres, before and after reprojection to Stereo70.</caption>
<thead>
<tr class="header">
<th style="text-align: left;"></th>
<th style="text-align: right;">min</th>
<th style="text-align: right;">max</th>
<th style="text-align: right;">mean</th>
<th style="text-align: right;">hill top</th>
<th style="text-align: right;">knoll top</th>
</tr>
</thead>
<tbody>
<tr class="odd">
<td style="text-align: left;">old DEM, UTM 34N</td>
<td style="text-align: right;">419.05</td>
<td style="text-align: right;">614.53</td>
<td style="text-align: right;">475.42</td>
<td style="text-align: right;">614.53</td>
<td style="text-align: right;">481.54</td>
</tr>
<tr class="even">
<td style="text-align: left;">QGIS default (nearest)</td>
<td style="text-align: right;">419.05</td>
<td style="text-align: right;">614.53</td>
<td style="text-align: right;">475.42</td>
<td style="text-align: right;">614.53</td>
<td style="text-align: right;">481.54</td>
</tr>
<tr class="odd">
<td style="text-align: left;">terra default (bilinear)</td>
<td style="text-align: right;">419.27</td>
<td style="text-align: right;">614.31</td>
<td style="text-align: right;">475.42</td>
<td style="text-align: right;">614.31</td>
<td style="text-align: right;">478.80</td>
</tr>
</tbody>
</table>
</div>
<div class="code-copy-outer-scaffold"><div class="sourceCode cell-code" id="cb11" style="background: #f1f3f5;"><pre class="sourceCode r code-with-copy"><code class="sourceCode r"><span id="cb11-1">knoll_drop <span class="ot" style="color: #003B4F;
background-color: null;
font-style: inherit;">&lt;-</span> dem_tab[<span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">1</span>, <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"knoll"</span>] <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">-</span> dem_tab[<span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">3</span>, <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"knoll"</span>]</span>
<span id="cb11-2">tab_gap <span class="ot" style="color: #003B4F;
background-color: null;
font-style: inherit;">&lt;-</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">max</span>(<span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">abs</span>(<span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">dem_row</span>(t_dem_near) <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">-</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">dem_row</span>(q_dem_near)),</span>
<span id="cb11-3">               <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">abs</span>(<span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">dem_row</span>(q_dem_bil) <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">-</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">dem_row</span>(t_dem_bil)))</span>
<span id="cb11-4">mean_move <span class="ot" style="color: #003B4F;
background-color: null;
font-style: inherit;">&lt;-</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">max</span>(<span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">abs</span>(dem_tab[<span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">2</span><span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">:</span><span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">3</span>, <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"mean"</span>] <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">-</span> dem_tab[<span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">1</span>, <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"mean"</span>]))</span>
<span id="cb11-5">hill_drop  <span class="ot" style="color: #003B4F;
background-color: null;
font-style: inherit;">&lt;-</span> dem_tab[<span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">1</span>, <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"hill"</span>] <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">-</span> dem_tab[<span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">3</span>, <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"hill"</span>]</span></code></pre></div></div>
</div>
<p>QGIS’s nearest output matches <code>project(method = "near")</code> in all but 7 cells, and its bilinear output matches the <code>terra</code> default to within 2.5 millimetres, and swapping the tool behind either row changes no entry of the table by more than 1.5 millimetres. Nearest neighbour returns exactly the old minimum and maximum here: it only copies, so it cannot go beyond them, and both extreme cells happened to be among those it copied. Bilinear lowers the knoll top by 2.73 metres, 9 per cent of its 30 metre height, and the hill top by 0.22 metres: a weighted mean of four cells cannot exceed the highest of them, and how much it loses depends on how sharply the surface bends at the top. The knoll is a cone, as sharp as a summit gets at this cell size; the hill is broad. Neither mean moves by more than 0.002 metres.</p>
<div class="cell">
<div class="code-copy-outer-scaffold"><div class="sourceCode cell-code" id="cb12" style="background: #f1f3f5;"><pre class="sourceCode r code-with-copy"><code class="sourceCode r"><span id="cb12-1">knoll_s <span class="ot" style="color: #003B4F;
background-color: null;
font-style: inherit;">&lt;-</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">project</span>(<span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">matrix</span>(knoll_xy, <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">1</span>), utm, stereo)</span>
<span id="cb12-2">prof_row <span class="ot" style="color: #003B4F;
background-color: null;
font-style: inherit;">&lt;-</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">rowFromY</span>(t_dem_bil, knoll_s[<span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">2</span>])</span>
<span id="cb12-3">prof_x   <span class="ot" style="color: #003B4F;
background-color: null;
font-style: inherit;">&lt;-</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">xFromCol</span>(t_dem_bil, <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">seq_len</span>(<span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">ncol</span>(t_dem_bil)))</span>
<span id="cb12-4">near_x   <span class="ot" style="color: #003B4F;
background-color: null;
font-style: inherit;">&lt;-</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">abs</span>(prof_x <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">-</span> knoll_s[<span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">1</span>]) <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">&lt;=</span> <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">240</span></span>
<span id="cb12-5">prof_xy  <span class="ot" style="color: #003B4F;
background-color: null;
font-style: inherit;">&lt;-</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">cbind</span>(prof_x[near_x], <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">yFromRow</span>(t_dem_bil, prof_row))</span>
<span id="cb12-6">fine_x   <span class="ot" style="color: #003B4F;
background-color: null;
font-style: inherit;">&lt;-</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">seq</span>(<span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">min</span>(prof_xy[, <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">1</span>]), <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">max</span>(prof_xy[, <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">1</span>]), <span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">length.out =</span> <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">400</span>)</span>
<span id="cb12-7">fine_utm <span class="ot" style="color: #003B4F;
background-color: null;
font-style: inherit;">&lt;-</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">project</span>(<span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">cbind</span>(fine_x, prof_xy[<span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">1</span>, <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">2</span>]), stereo, utm)</span>
<span id="cb12-8">d0 <span class="ot" style="color: #003B4F;
background-color: null;
font-style: inherit;">&lt;-</span> prof_xy[, <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">1</span>] <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">-</span> knoll_s[<span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">1</span>]</span>
<span id="cb12-9">prof_df <span class="ot" style="color: #003B4F;
background-color: null;
font-style: inherit;">&lt;-</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">rbind</span>(<span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">data.frame</span>(<span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">d =</span> d0, <span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">z =</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">extract</span>(q_dem_near, prof_xy)[, <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">1</span>], <span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">what =</span> <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"QGIS default: nearest"</span>),</span>
<span id="cb12-10">                 <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">data.frame</span>(<span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">d =</span> d0, <span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">z =</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">extract</span>(t_dem_bil, prof_xy)[, <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">1</span>], <span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">what =</span> <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"terra default: bilinear"</span>))</span>
<span id="cb12-11">true_df <span class="ot" style="color: #003B4F;
background-color: null;
font-style: inherit;">&lt;-</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">data.frame</span>(<span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">d =</span> fine_x <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">-</span> knoll_s[<span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">1</span>], <span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">z =</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">surface</span>(fine_utm[, <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">1</span>], fine_utm[, <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">2</span>]))</span>
<span id="cb12-12"><span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">ggplot</span>(prof_df, <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">aes</span>(d, z)) <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">+</span></span>
<span id="cb12-13">  <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">geom_line</span>(<span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">data =</span> true_df, <span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">colour =</span> <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"grey55"</span>, <span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">linewidth =</span> <span class="fl" style="color: #AD0000;
background-color: null;
font-style: inherit;">1.6</span>, <span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">alpha =</span> <span class="fl" style="color: #AD0000;
background-color: null;
font-style: inherit;">0.6</span>) <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">+</span></span>
<span id="cb12-14">  <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">geom_step</span>(<span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">data =</span> prof_df[prof_df<span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">$</span>what <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">==</span> <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"QGIS default: nearest"</span>, ],</span>
<span id="cb12-15">            <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">aes</span>(<span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">x =</span> d <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">-</span> <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">15</span>), <span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">colour =</span> te_forest, <span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">linewidth =</span> <span class="fl" style="color: #AD0000;
background-color: null;
font-style: inherit;">0.7</span>) <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">+</span></span>
<span id="cb12-16">  <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">geom_line</span>(<span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">data =</span> prof_df[prof_df<span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">$</span>what <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">==</span> <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"terra default: bilinear"</span>, ],</span>
<span id="cb12-17">            <span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">colour =</span> te_rust, <span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">linewidth =</span> <span class="fl" style="color: #AD0000;
background-color: null;
font-style: inherit;">0.8</span>) <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">+</span></span>
<span id="cb12-18">  <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">geom_point</span>(<span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">aes</span>(<span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">colour =</span> what), <span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">size =</span> <span class="fl" style="color: #AD0000;
background-color: null;
font-style: inherit;">1.8</span>) <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">+</span></span>
<span id="cb12-19">  <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">scale_colour_manual</span>(<span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">values =</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">c</span>(te_forest, te_rust), <span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">name =</span> <span class="cn" style="color: #8f5902;
background-color: null;
font-style: inherit;">NULL</span>) <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">+</span></span>
<span id="cb12-20">  <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">labs</span>(<span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">x =</span> <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"distance east of the knoll centre (m)"</span>, <span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">y =</span> <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"elevation (m)"</span>,</span>
<span id="cb12-21">       <span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">title =</span> <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"Nearest copies cells, bilinear rounds the top off"</span>,</span>
<span id="cb12-22">       <span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">subtitle =</span> <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"grey: the surface without noise"</span>) <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">+</span></span>
<span id="cb12-23">  <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">theme_datasheet</span>() <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">+</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">theme</span>(<span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">legend.position =</span> <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"bottom"</span>)</span></code></pre></div></div>
<div class="cell-output-display">
<div id="fig-knoll" class="quarto-float quarto-figure quarto-figure-center anchored" alt="An elevation profile in metres, from about 454 to 482, against distance east of the knoll centre from about minus 240 to plus 220 metres. A thick grey line, the noise-free surface, is nearly flat near 455 on both sides and rises to a sharp peak of about 482 at zero. Dark green points joined by a stepped line, QGIS default: nearest, follow it in flat treads 30 metres wide, with the highest tread at about 480 just east of the centre. Rust points joined by a straight line, terra default: bilinear, follow the grey line closely on the flanks and cut the peak off at about 479.">
<figure class="quarto-float quarto-float-fig figure">
<div aria-describedby="fig-knoll-caption-0ceaefa1-69ba-4598-a22c-09a6ac19f8ca">
<img src="https://tidyecology.com/posts/reprojecting-a-raster-in-qgis-and-r/index_files/figure-html/fig-knoll-1.png" class="img-fluid figure-img" alt="An elevation profile in metres, from about 454 to 482, against distance east of the knoll centre from about minus 240 to plus 220 metres. A thick grey line, the noise-free surface, is nearly flat near 455 on both sides and rises to a sharp peak of about 482 at zero. Dark green points joined by a stepped line, QGIS default: nearest, follow it in flat treads 30 metres wide, with the highest tread at about 480 just east of the centre. Rust points joined by a straight line, terra default: bilinear, follow the grey line closely on the flanks and cut the peak off at about 479." width="720">
</div>
<figcaption class="quarto-float-caption-bottom quarto-float-caption quarto-float-fig" id="fig-knoll-caption-0ceaefa1-69ba-4598-a22c-09a6ac19f8ca">
Figure&nbsp;2: A west to east profile through the knoll along one row of the Stereo70 grid. The grey line is the surface the DEM was made from, without its noise; the steps are QGIS’s nearest neighbour output and the rust line is terra’s bilinear output.
</figcaption>
</figure>
</div>
</div>
</div>
<p>The price of nearest neighbour shows up in what is computed from the surface. The new grid is turned against the old one, so its rows run across the old rows at a small angle, and nearest neighbour settles the misfit in steps: along lines a fixed number of cells apart, the copied pattern jumps by one old row (or column). Slope is computed from differences between neighbouring cells, and across such a line the difference between two neighbouring new cells is taken between old cells that are also one row (or column) apart, so it picks up the slope in the other direction as well. The chunk measures the angle and computes slope with <code>terrain()</code> on the old DEM and on both outputs, against the slope of the noise-free surface at each cell centre.</p>
<div class="cell">
<div class="code-copy-outer-scaffold"><div class="sourceCode cell-code" id="cb13" style="background: #f1f3f5;"><pre class="sourceCode r code-with-copy"><code class="sourceCode r"><span id="cb13-1">ab <span class="ot" style="color: #003B4F;
background-color: null;
font-style: inherit;">&lt;-</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">project</span>(<span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">rbind</span>(<span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">c</span>(<span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">652000</span>, <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">5178000</span>), <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">c</span>(<span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">653000</span>, <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">5178000</span>)), utm, stereo)</span>
<span id="cb13-2">turn_deg <span class="ot" style="color: #003B4F;
background-color: null;
font-style: inherit;">&lt;-</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">atan2</span>(ab[<span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">2</span>, <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">2</span>] <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">-</span> ab[<span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">1</span>, <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">2</span>], ab[<span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">2</span>, <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">1</span>] <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">-</span> ab[<span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">1</span>, <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">1</span>]) <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">*</span> <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">180</span> <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">/</span> pi</span>
<span id="cb13-3">drift <span class="ot" style="color: #003B4F;
background-color: null;
font-style: inherit;">&lt;-</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">tan</span>(<span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">abs</span>(turn_deg) <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">*</span> pi <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">/</span> <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">180</span>)   <span class="co" style="color: #5E5E5E;
background-color: null;
font-style: inherit;"># how fast one grid's rows cross the other's</span></span>
<span id="cb13-4">true_slope <span class="ot" style="color: #003B4F;
background-color: null;
font-style: inherit;">&lt;-</span> <span class="cf" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">function</span>(x, y, <span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">h =</span> <span class="fl" style="color: #AD0000;
background-color: null;
font-style: inherit;">0.01</span>) {</span>
<span id="cb13-5">  gx <span class="ot" style="color: #003B4F;
background-color: null;
font-style: inherit;">&lt;-</span> (<span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">surface</span>(x <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">+</span> h, y) <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">-</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">surface</span>(x <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">-</span> h, y)) <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">/</span> (<span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">2</span> <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">*</span> h)</span>
<span id="cb13-6">  gy <span class="ot" style="color: #003B4F;
background-color: null;
font-style: inherit;">&lt;-</span> (<span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">surface</span>(x, y <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">+</span> h) <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">-</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">surface</span>(x, y <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">-</span> h)) <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">/</span> (<span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">2</span> <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">*</span> h)</span>
<span id="cb13-7">  <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">atan</span>(<span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">sqrt</span>(gx<span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">^</span><span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">2</span> <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">+</span> gy<span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">^</span><span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">2</span>)) <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">*</span> <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">180</span> <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">/</span> pi</span>
<span id="cb13-8">}</span>
<span id="cb13-9">slope_err <span class="ot" style="color: #003B4F;
background-color: null;
font-style: inherit;">&lt;-</span> <span class="cf" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">function</span>(r) {</span>
<span id="cb13-10">  s  <span class="ot" style="color: #003B4F;
background-color: null;
font-style: inherit;">&lt;-</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">values</span>(<span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">terrain</span>(r, <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"slope"</span>))[, <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">1</span>]</span>
<span id="cb13-11">  xy <span class="ot" style="color: #003B4F;
background-color: null;
font-style: inherit;">&lt;-</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">xyFromCell</span>(r, <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">seq_len</span>(<span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">ncell</span>(r)))</span>
<span id="cb13-12">  <span class="cf" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">if</span> (<span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">crs</span>(r) <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">!=</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">crs</span>(dem)) xy <span class="ot" style="color: #003B4F;
background-color: null;
font-style: inherit;">&lt;-</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">project</span>(xy, stereo, utm)</span>
<span id="cb13-13">  s <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">-</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">true_slope</span>(xy[, <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">1</span>], xy[, <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">2</span>])</span>
<span id="cb13-14">}</span>
<span id="cb13-15">err_old <span class="ot" style="color: #003B4F;
background-color: null;
font-style: inherit;">&lt;-</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">slope_err</span>(dem); err_near <span class="ot" style="color: #003B4F;
background-color: null;
font-style: inherit;">&lt;-</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">slope_err</span>(q_dem_near); err_bil <span class="ot" style="color: #003B4F;
background-color: null;
font-style: inherit;">&lt;-</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">slope_err</span>(t_dem_bil)</span>
<span id="cb13-16">slope_first <span class="ot" style="color: #003B4F;
background-color: null;
font-style: inherit;">&lt;-</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">project</span>(<span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">terrain</span>(dem, <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"slope"</span>), stereo)   <span class="co" style="color: #5E5E5E;
background-color: null;
font-style: inherit;"># slope in UTM, then reprojected</span></span>
<span id="cb13-17">sf_xy <span class="ot" style="color: #003B4F;
background-color: null;
font-style: inherit;">&lt;-</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">project</span>(<span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">xyFromCell</span>(slope_first, <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">seq_len</span>(<span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">ncell</span>(slope_first))), stereo, utm)</span>
<span id="cb13-18">err_first <span class="ot" style="color: #003B4F;
background-color: null;
font-style: inherit;">&lt;-</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">values</span>(slope_first)[, <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">1</span>] <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">-</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">true_slope</span>(sf_xy[, <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">1</span>], sf_xy[, <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">2</span>])</span>
<span id="cb13-19">rmse <span class="ot" style="color: #003B4F;
background-color: null;
font-style: inherit;">&lt;-</span> <span class="cf" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">function</span>(e) <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">sqrt</span>(<span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">mean</span>(e<span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">^</span><span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">2</span>, <span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">na.rm =</span> <span class="cn" style="color: #8f5902;
background-color: null;
font-style: inherit;">TRUE</span>))</span>
<span id="cb13-20">big_share <span class="ot" style="color: #003B4F;
background-color: null;
font-style: inherit;">&lt;-</span> <span class="cf" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">function</span>(e) <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">mean</span>(<span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">abs</span>(e) <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">&gt;</span> <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">2</span>, <span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">na.rm =</span> <span class="cn" style="color: #8f5902;
background-color: null;
font-style: inherit;">TRUE</span>)</span></code></pre></div></div>
</div>
<p>Here the Stereo70 grid is turned by 2.90 degrees against UTM zone 34 north. The rows of one grid drift across the rows of the other at the tangent of that angle, 5.07 per cent of a cell for every cell travelled, so there is a step every 20 cells or so in each direction.</p>
<p>The slope error, the computed slope minus the slope of the noise-free surface, has a root mean square of 0.47 degrees on the old DEM, where it is the half metre of noise talking. On QGIS’s nearest output it rises to 0.62 degrees, and 1.5 per cent of cells are more than 2 degrees out, against 0.2 per cent on the old DEM. On <code>terra</code>’s bilinear output it falls to 0.41 degrees, with 0.3 per cent over 2 degrees, because averaging four cells also averages away part of the noise. The seams are strongest where the ground is steep, on the flanks of the hill, and faint on the gentle ground to the east, because shifting the pattern by one cell changes an elevation difference by the local slope times the cell size. Computing slope first, on the old grid, and then reprojecting the slope raster with bilinear gives 0.41 degrees, with 0.3 per cent over 2 degrees.</p>
<div class="cell">
<div class="code-copy-outer-scaffold"><div class="sourceCode cell-code" id="cb14" style="background: #f1f3f5;"><pre class="sourceCode r code-with-copy"><code class="sourceCode r"><span id="cb14-1">seam_df <span class="ot" style="color: #003B4F;
background-color: null;
font-style: inherit;">&lt;-</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">rbind</span>(</span>
<span id="cb14-2">  <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">data.frame</span>(<span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">xyFromCell</span>(q_dem_near, <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">seq_len</span>(<span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">ncell</span>(q_dem_near))), <span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">err =</span> err_near,</span>
<span id="cb14-3">             <span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">panel =</span> <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"QGIS default: nearest"</span>),</span>
<span id="cb14-4">  <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">data.frame</span>(<span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">xyFromCell</span>(t_dem_bil, <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">seq_len</span>(<span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">ncell</span>(t_dem_bil))), <span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">err =</span> err_bil,</span>
<span id="cb14-5">             <span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">panel =</span> <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"terra default: bilinear"</span>))</span>
<span id="cb14-6">seam_df <span class="ot" style="color: #003B4F;
background-color: null;
font-style: inherit;">&lt;-</span> seam_df[<span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">!</span><span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">is.na</span>(seam_df<span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">$</span>err), ]</span>
<span id="cb14-7">seam_plot <span class="ot" style="color: #003B4F;
background-color: null;
font-style: inherit;">&lt;-</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">ggplot</span>(seam_df, <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">aes</span>(x, y, <span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">fill =</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">pmax</span>(<span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">-</span><span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">3</span>, <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">pmin</span>(<span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">3</span>, err)))) <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">+</span></span>
<span id="cb14-8">  <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">geom_raster</span>() <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">+</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">facet_wrap</span>(<span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">~</span> panel) <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">+</span></span>
<span id="cb14-9">  <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">scale_fill_gradient2</span>(<span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">low =</span> te_rust, <span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">mid =</span> te_paper, <span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">high =</span> te_forest, <span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">midpoint =</span> <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">0</span>,</span>
<span id="cb14-10">                       <span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">limits =</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">c</span>(<span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">-</span><span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">3</span>, <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">3</span>), <span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">name =</span> <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"slope error</span><span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">\n</span><span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">(degrees)"</span>) <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">+</span></span>
<span id="cb14-11">  <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">coord_equal</span>(<span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">expand =</span> <span class="cn" style="color: #8f5902;
background-color: null;
font-style: inherit;">FALSE</span>) <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">+</span></span>
<span id="cb14-12">  <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">labs</span>(<span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">x =</span> <span class="cn" style="color: #8f5902;
background-color: null;
font-style: inherit;">NULL</span>, <span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">y =</span> <span class="cn" style="color: #8f5902;
background-color: null;
font-style: inherit;">NULL</span>, <span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">title =</span> <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"Nearest neighbour leaves seams in the slope map"</span>,</span>
<span id="cb14-13">       <span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">subtitle =</span> <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"computed slope minus true slope"</span>) <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">+</span></span>
<span id="cb14-14">  <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">theme_datasheet</span>() <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">+</span></span>
<span id="cb14-15">  <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">theme</span>(<span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">axis.text =</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">element_blank</span>(), <span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">panel.grid.major =</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">element_blank</span>())</span>
<span id="cb14-16">seam_plot</span></code></pre></div></div>
<div class="cell-output cell-output-stderr">
<pre><code>Warning: Raster pixels are placed at uneven horizontal intervals and will be shifted
ℹ Consider using `geom_tile()` instead.
Raster pixels are placed at uneven horizontal intervals and will be shifted
ℹ Consider using `geom_tile()` instead.</code></pre>
</div>
<div class="cell-output-display">
<div id="fig-seams" class="quarto-float quarto-figure quarto-figure-center anchored" alt="Two maps of slope error in degrees side by side, coloured from rust at minus 3 through off-white at zero to dark green at plus 3, each a slightly rotated square of fine speckle. The left map, QGIS default: nearest, is crossed in its upper left two thirds by straight dark green and rust lines one cell wide, running across and down the map about 600 metres apart and forming a loose grid that fades towards the right. The right map, terra default: bilinear, shows only speckle and no lines. Both have a small dark green and rust ring at lower right, the conical knoll.">
<figure class="quarto-float quarto-float-fig figure">
<div aria-describedby="fig-seams-caption-0ceaefa1-69ba-4598-a22c-09a6ac19f8ca">
<img src="https://tidyecology.com/posts/reprojecting-a-raster-in-qgis-and-r/index_files/figure-html/fig-seams-1.png" class="img-fluid figure-img" alt="Two maps of slope error in degrees side by side, coloured from rust at minus 3 through off-white at zero to dark green at plus 3, each a slightly rotated square of fine speckle. The left map, QGIS default: nearest, is crossed in its upper left two thirds by straight dark green and rust lines one cell wide, running across and down the map about 600 metres apart and forming a loose grid that fades towards the right. The right map, terra default: bilinear, shows only speckle and no lines. Both have a small dark green and rust ring at lower right, the conical knoll." width="720">
</div>
<figcaption class="quarto-float-caption-bottom quarto-float-caption quarto-float-fig" id="fig-seams-caption-0ceaefa1-69ba-4598-a22c-09a6ac19f8ca">
Figure&nbsp;3: Slope computed with terrain() after reprojection to Stereo70, minus the slope of the noise-free surface at each cell centre, in degrees, clipped at 3. Left: QGIS with its default, nearest neighbour. Right: terra with its default, bilinear. The small ring at lower right is the rim and tip of the conical knoll, where the true slope jumps and both outputs miss it.
</figcaption>
</figure>
</div>
</div>
</div>
<div class="cell">
<div class="code-copy-outer-scaffold"><div class="sourceCode cell-code" id="cb16" style="background: #f1f3f5;"><pre class="sourceCode r code-with-copy"><code class="sourceCode r"><span id="cb16-1"><span class="co" style="color: #5E5E5E;
background-color: null;
font-style: inherit;"># a round trip: into Stereo70 and back onto the old grid, same method both ways</span></span>
<span id="cb16-2">back_near <span class="ot" style="color: #003B4F;
background-color: null;
font-style: inherit;">&lt;-</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">project</span>(t_dem_near, dem, <span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">method =</span> <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"near"</span>); back_bil <span class="ot" style="color: #003B4F;
background-color: null;
font-style: inherit;">&lt;-</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">project</span>(t_dem_bil, dem)</span>
<span id="cb16-3">d_near <span class="ot" style="color: #003B4F;
background-color: null;
font-style: inherit;">&lt;-</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">values</span>(back_near)[, <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">1</span>] <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">-</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">values</span>(dem)[, <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">1</span>]</span>
<span id="cb16-4">d_bil  <span class="ot" style="color: #003B4F;
background-color: null;
font-style: inherit;">&lt;-</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">values</span>(back_bil)[, <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">1</span>] <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">-</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">values</span>(dem)[, <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">1</span>]</span>
<span id="cb16-5">rt_exact <span class="ot" style="color: #003B4F;
background-color: null;
font-style: inherit;">&lt;-</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">mean</span>(d_near <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">==</span> <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">0</span>, <span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">na.rm =</span> <span class="cn" style="color: #8f5902;
background-color: null;
font-style: inherit;">TRUE</span>)</span>
<span id="cb16-6">rt_knoll <span class="ot" style="color: #003B4F;
background-color: null;
font-style: inherit;">&lt;-</span> dem_tab[<span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">1</span>, <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"knoll"</span>] <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">-</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">peak_in</span>(back_bil, knoll_xy, <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">150</span>)</span>
<span id="cb16-7">rt_bil_exact <span class="ot" style="color: #003B4F;
background-color: null;
font-style: inherit;">&lt;-</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">sum</span>(d_bil <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">==</span> <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">0</span>, <span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">na.rm =</span> <span class="cn" style="color: #8f5902;
background-color: null;
font-style: inherit;">TRUE</span>)</span>
<span id="cb16-8"><span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">stopifnot</span>(<span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">isTRUE</span>(<span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">all.equal</span>(rt_knoll, <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">max</span>(<span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">abs</span>(d_bil), <span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">na.rm =</span> <span class="cn" style="color: #8f5902;
background-color: null;
font-style: inherit;">TRUE</span>))))   <span class="co" style="color: #5E5E5E;
background-color: null;
font-style: inherit;"># the largest change is the knoll top</span></span></code></pre></div></div>
</div>
<p>A round trip, into Stereo70 and back onto the original grid with the same method both ways, shows the two behaviours side by side. After nearest there and back, 97.4 per cent of the cells hold exactly their old value and the rest hold a neighbour’s, up to 5.62 metres away from their own. After bilinear, 3 cells out of 14399 hold exactly their old value, and the largest change anywhere is the knoll top, now 3.64 metres lower against 2.73 after one pass. Every reprojection of a surface costs something, so reproject once, from the original.</p>
</section>
<section id="the-output-grid" class="level2">
<h2 id="the-output-grid-h" class="anchored" data-anchor-id="the-output-grid">The output grid</h2>
<p>Neither tool asks for a cell size. Both ask GDAL for a suggested output grid, and both got the same one.</p>
<div class="cell">
<div class="code-copy-outer-scaffold"><div class="sourceCode cell-code" id="cb17" style="background: #f1f3f5;"><pre class="sourceCode r code-with-copy"><code class="sourceCode r"><span id="cb17-1">res_auto <span class="ot" style="color: #003B4F;
background-color: null;
font-style: inherit;">&lt;-</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">res</span>(t_default)[<span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">1</span>]</span>
<span id="cb17-2">corners  <span class="ot" style="color: #003B4F;
background-color: null;
font-style: inherit;">&lt;-</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">project</span>(<span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">rbind</span>(<span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">c</span>(<span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">650000</span>, <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">5182000</span>), <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">c</span>(<span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">656000</span>, <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">5176000</span>)), utm, stereo)   <span class="co" style="color: #5E5E5E;
background-color: null;
font-style: inherit;"># old diagonal</span></span>
<span id="cb17-3">diag_res <span class="ot" style="color: #003B4F;
background-color: null;
font-style: inherit;">&lt;-</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">sqrt</span>(<span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">sum</span>(<span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">diff</span>(corners)<span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">^</span><span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">2</span>)) <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">/</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">sqrt</span>(<span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">nrow</span>(cover)<span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">^</span><span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">2</span> <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">+</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">ncol</span>(cover)<span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">^</span><span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">2</span>)</span>
<span id="cb17-4">q_res30  <span class="ot" style="color: #003B4F;
background-color: null;
font-style: inherit;">&lt;-</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">rast</span>(<span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"qgis-landcover-res30.tif"</span>)</span>
<span id="cb17-5">t_res30  <span class="ot" style="color: #003B4F;
background-color: null;
font-style: inherit;">&lt;-</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">project</span>(cover, stereo, <span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">res =</span> <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">30</span>, <span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">method =</span> <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"near"</span>)</span>
<span id="cb17-6">e_q <span class="ot" style="color: #003B4F;
background-color: null;
font-style: inherit;">&lt;-</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">as.vector</span>(<span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">ext</span>(q_res30)); e_t <span class="ot" style="color: #003B4F;
background-color: null;
font-style: inherit;">&lt;-</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">as.vector</span>(<span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">ext</span>(t_res30))</span>
<span id="cb17-7">shift_y  <span class="ot" style="color: #003B4F;
background-color: null;
font-style: inherit;">&lt;-</span> e_q[<span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"ymax"</span>] <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">-</span> e_t[<span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"ymax"</span>]</span>
<span id="cb17-8">diff_res30 <span class="ot" style="color: #003B4F;
background-color: null;
font-style: inherit;">&lt;-</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">sum</span>(<span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">values</span>(q_res30)[, <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">1</span>] <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">!=</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">values</span>(t_res30)[, <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">1</span>], <span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">na.rm =</span> <span class="cn" style="color: #8f5902;
background-color: null;
font-style: inherit;">TRUE</span>)</span>
<span id="cb17-9">suggested <span class="ot" style="color: #003B4F;
background-color: null;
font-style: inherit;">&lt;-</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">as.vector</span>(<span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">ext</span>(t_default))</span>
<span id="cb17-10">template <span class="ot" style="color: #003B4F;
background-color: null;
font-style: inherit;">&lt;-</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">rast</span>(<span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">xmin =</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">floor</span>(suggested[<span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"xmin"</span>] <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">/</span> <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">30</span>) <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">*</span> <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">30</span>, <span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">xmax =</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">ceiling</span>(suggested[<span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"xmax"</span>] <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">/</span> <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">30</span>) <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">*</span> <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">30</span>,</span>
<span id="cb17-11">                 <span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">ymin =</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">floor</span>(suggested[<span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"ymin"</span>] <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">/</span> <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">30</span>) <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">*</span> <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">30</span>, <span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">ymax =</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">ceiling</span>(suggested[<span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"ymax"</span>] <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">/</span> <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">30</span>) <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">*</span> <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">30</span>,</span>
<span id="cb17-12">                 <span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">resolution =</span> <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">30</span>, <span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">crs =</span> stereo)</span>
<span id="cb17-13">q_tmpl <span class="ot" style="color: #003B4F;
background-color: null;
font-style: inherit;">&lt;-</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">rast</span>(<span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"qgis-landcover-template.tif"</span>)</span>
<span id="cb17-14">t_tmpl <span class="ot" style="color: #003B4F;
background-color: null;
font-style: inherit;">&lt;-</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">project</span>(cover, template, <span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">method =</span> <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"near"</span>)</span>
<span id="cb17-15">tmpl_same <span class="ot" style="color: #003B4F;
background-color: null;
font-style: inherit;">&lt;-</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">isTRUE</span>(<span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">all.equal</span>(<span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">as.vector</span>(<span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">ext</span>(q_tmpl)), <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">as.vector</span>(<span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">ext</span>(t_tmpl)))) <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">&amp;&amp;</span></span>
<span id="cb17-16">  <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">all</span>(<span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">dim</span>(q_tmpl) <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">==</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">dim</span>(t_tmpl))</span>
<span id="cb17-17">diff_tmpl <span class="ot" style="color: #003B4F;
background-color: null;
font-style: inherit;">&lt;-</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">sum</span>(<span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">values</span>(q_tmpl)[, <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">1</span>] <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">!=</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">values</span>(t_tmpl)[, <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">1</span>], <span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">na.rm =</span> <span class="cn" style="color: #8f5902;
background-color: null;
font-style: inherit;">TRUE</span>)</span>
<span id="cb17-18">tmpl_ext <span class="ot" style="color: #003B4F;
background-color: null;
font-style: inherit;">&lt;-</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">as.vector</span>(<span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">ext</span>(template))</span>
<span id="cb17-19"><span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">stopifnot</span>(tmpl_same)</span></code></pre></div></div>
</div>
<p>The suggested cell is 30.0015 metres, not 30, because GDAL keeps the map’s diagonal as many cells long as before: the old diagonal, transformed, measures 30.0015 metres per old cell. Asking for 30 metres is <em>Output file resolution in target georeferenced units</em> in the Warp dialog (<code>TARGET_RESOLUTION=30</code>) and <code>res = 30</code> in <code>project()</code>. Both then return 30 metre cells and the same number of rows and columns, but not the same grid: QGIS keeps the top edge of the suggested extent and <code>terra</code> the bottom edge, so the grids are offset by 0.316 metres north to south and 19 cells of the land-cover map differ.</p>
<p>The reliable way to get one grid is to write it down. In <code>terra</code> that is a template raster passed as the second argument of <code>project()</code>; here its edges are the suggested extent rounded outwards to whole multiples of 30 metres, 344400, 350730, 581820 and 588150 (west, east, south, north). In QGIS the same numbers go into <em>Georeferenced extents of output file to be created</em> (under Advanced Parameters) and the resolution into <em>Output file resolution</em>, which is what the <code>qgis-landcover-template.tif</code> command above did. The two grids are then identical, and the two nearest neighbour maps differ in 1 cell, the <code>gdalwarp</code> shortcut again. A template is also how to put a reprojected map exactly on top of another raster you already have: pass that raster.</p>
</section>
<section id="what-the-screen-shows-is-not-the-file" class="level2">
<h2 id="what-the-screen-shows-is-not-the-file-h" class="anchored" data-anchor-id="what-the-screen-shows-is-not-the-file">What the screen shows is not the file</h2>
<p>QGIS also resamples every time it draws a raster, because screen pixels never line up with raster cells. That setting is under <strong>Layer &gt; Layer Properties &gt; Symbology</strong>, in the <em>Resampling</em> frame, separately for zoomed in and zoomed out, and the default for new layers is under <strong>Settings &gt; Options &gt; Rendering</strong>, on the <em>Raster</em> tab, as the QGIS 3.40 user manual describes. It changes what you see and nothing in the file. According to the QGIS source (read, not measured here), a new layer gets nearest neighbour both ways: <code>src/core/raster/qgsrasterlayer.cpp</code> falls back to <code>nearest neighbour</code> in the 3.34, 3.40 and 3.44 branches and on master (checked 2026-09-25), and <code>src/gui/raster/qgsresamplingutils.cpp</code> shows an unset resampler as <em>Nearest Neighbour</em> in the Symbology tab. So a map that looks smooth in QGIS has had its display resampling changed, and a map that looks blocky may still have been reprojected with bilinear. Check the file, not the screen.</p>
</section>
<section id="what-to-report" class="level2">
<h2 id="what-to-report-h" class="anchored" data-anchor-id="what-to-report">What to report</h2>
<p>A methods section that says the land-cover map “was reprojected to Stereo70” leaves out the decision that changed it. Give the target CRS by its code, the datum transformation PROJ used, the resampling method and the output cell size, and say how the grid was fixed: “reprojected from UTM zone 34N (EPSG:32634) to Stereo70 (EPSG:3844) with nearest neighbour resampling onto a 30 m grid aligned to whole multiples of 30 m (terra <code>project()</code>, method near)”. For a categorical map at a similar cell size, nearest neighbour is the method that keeps every code real, and a reader who sees bilinear will know the class boundaries were smeared. For an elevation model, say which one you used and if slope or another derivative comes from a surface that was reprojected with nearest neighbour, compute it on the original grid instead and reproject the result. If the analysis compares class shares or patch counts before and after, say that the numbering of the classes played no part, which is true only with nearest neighbour.</p>
</section>
<section id="where-the-defaults-are-set" class="level2">
<h2 id="where-the-defaults-are-set-h" class="anchored" data-anchor-id="where-the-defaults-are-set">Where the defaults are set</h2>
<p>The QGIS files were made by QGIS 3.34.4 on Linux over GDAL 3.8.4 and PROJ 9.4.0; the R side of this page ran on <code>terra</code> 1.9.50 over GDAL 3.8.5 and PROJ 9.5.1. The <code>terra</code> rule quoted above sits at the top of the <code>project()</code> method for <code>SpatRaster</code>, in <code>R/generics.R</code>, and is the same in <code>terra</code> 1.7.65 and in the <code>rspatial/terra</code> repository on GitHub at version 1.9-51 (the commit of 2026-09-16); the defaults chunk checks it again on whichever version builds the page. <code>resample()</code> has the same rule in current <code>terra</code>, while 1.7.65 checks only whether the raster is a factor. The Warp page of the QGIS 3.40 user manual gives the same default as the <code>qgis_process</code> help. The <code>-et</code> shortcut and its default of an eighth of a cell are in the <code>gdalwarp</code> documentation, and the diagonal rule for the suggested cell size is coded in <code>GDALSuggestedWarpOutput2()</code>, in GDAL’s <code>alg/gdaltransformer.cpp</code>.</p>
</section>
<section id="honest-limits" class="level2">
<h2 id="honest-limits-h" class="anchored" data-anchor-id="honest-limits">Honest limits</h2>
<p>The measurements are on two synthetic rasters, one pair of coordinate systems and a turn of 2.9 degrees between them. A larger turn, as between a UTM zone and a national grid far from its central meridian, puts the nearest neighbour steps closer together. The transformation from UTM on WGS 84 to Stereo70 includes a datum shift, and PROJ has several candidate operations for Romania. The one used here, Pulkovo 1942(58) to WGS 84 (19), with a stated accuracy of 3 metres, is the default in both PROJ 9.4.0 and 9.5.1, and the two give coordinates equal to within a millionth of a metre (checked with sf and pyproj, outside this page); a different PROJ database could pick another operation and shift the whole grid, and the <code>stopifnot()</code> lines in the chunks then stop the page from building rather than compare mismatched grids. The land-cover patches are convex areas around random centres with random codes, so boundaries between distant codes are as common as between close ones; a map numbered so that neighbouring classes have neighbouring codes would invent fewer classes, and the count of invented cells depends on the numbering in a way no rule of thumb captures. The ratios in the sweep come from one map at each fragmentation level. The slope comparison uses a surface with half a metre of noise and one sharp feature; on a very smooth surface the nearest neighbour seams are smaller, and on a rougher one bilinear removes more of the roughness along with the noise, which is a change to the data in its own right. Only nearest and bilinear were compared; cubic and the aggregating methods (average, mode) were not, and mode or average are the usual choices when the new cells are much larger than the old. Reprojection to longitude and latitude, where cells stop being square on the ground, was not measured. QGIS <strong>Export &gt; Save As</strong> with a different CRS reprojects through QGIS’s own code rather than <code>gdalwarp</code> and offers no resampling choice (read from the QGIS 3.34 source, not measured here).</p>
</section>
<section id="references" class="level2">
<h2 id="references-h" class="anchored" data-anchor-id="references">References</h2>
<p>Lovelace R, Nowosad J, Muenchow J 2019 Geocomputation with R. Chapman and Hall/CRC (ISBN 9781138304512; 10.1201/9780203730058)</p>
</section>
<section id="related-tutorials" class="level2">
<h2 id="related-tutorials-h" class="anchored" data-anchor-id="related-tutorials">Related tutorials</h2>
<ul>
<li><a href="https://tidyecology.com/posts/rasterising-a-vector-layer/">Rasterising a vector layer</a></li>
<li><a href="https://tidyecology.com/posts/checking-a-remote-sensing-covariate/">Checking a remote sensing covariate</a></li>
<li><a href="https://tidyecology.com/posts/slope-and-aspect-from-a-dem/">Slope and aspect: what a DEM does not measure</a></li>
<li><a href="https://tidyecology.com/posts/running-qgis-from-the-command-line/">Running QGIS from the command line</a></li>
</ul>
<details class="te-repro" data-pagefind-ignore="">
<summary>Reproducibility</summary>
<ul>
<li>Code last run: 2026-10-15</li>
<li>R version 4.5.3 (2026-03-11), aarch64-apple-darwin20</li>
<li>Packages: ggplot2 4.0.3, terra 1.9-50</li>
</ul>
</details>


<!-- -->

</section>

 ]]></description>
  <category>R</category>
  <category>QGIS</category>
  <category>terra</category>
  <category>GIS</category>
  <category>spatial</category>
  <category>raster data</category>
  <category>ecology tutorial</category>
  <guid isPermaLink="false">https://tidyecology.com/posts/reprojecting-a-raster-in-qgis-and-r/</guid>
  <pubDate>Sat, 26 Sep 2026 07:00:00 GMT</pubDate>
  <media:content url="https://tidyecology.com/posts/reprojecting-a-raster-in-qgis-and-r/thumbnail.png" medium="image" type="image/png" height="104" width="144"/>
</item>
<item>
  <title>Natural breaks in QGIS and R: Jenks on large layers</title>
  <dc:creator>Tidy Ecology</dc:creator>
  <link>https://tidyecology.com/posts/natural-breaks-in-qgis-and-r/</link>
  <description><![CDATA[ 





<p><em>Corrected 14 October 2026: the post said that a layer with a long upper tail was not tested, although this grid has one, and it now says that a longer or sparser upper tail than this grid’s was not tested.</em></p>
<p><em>Corrected 1 October 2026: the post said that on any large layer of positive values Natural Breaks in QGIS gives, in effect, four classes and a legend entry; that was shown only for this grid and its shifted copies, and the sentence now says so, while the advice on reading the legend adds that on a layer crossing zero the padding leaves neither sign.</em></p>
<p><em>Corrected 30 September 2026: the prose said identical() was TRUE for both Equal Interval and Quantile while the table above showed FALSE for Equal Interval; the sentence now reports both results as computed and says the bounds agree to every printed digit.</em></p>
<p>A stacked species distribution model has given you predicted species richness on a one kilometre grid, 300 cells wide and 200 tall, and you want two versions of the same map: a quick one in QGIS to look at, and the figure for the paper drawn in R. In QGIS you open <strong>Layer &gt; Layer Properties &gt; Symbology</strong>, pick <strong>Graduated</strong>, set <strong>Mode</strong> to <strong>Natural Breaks (Jenks)</strong> and press <strong>Classify</strong>. In R you call <code>classInt::classIntervals(style = "jenks")</code>. Both claim to do the same thing, which is to cut the values into classes that are as internally homogeneous as possible, and on this grid they do not return the same classes.</p>
<p><a href="https://tidyecology.com/posts/richness-mapping-sf/">Mapping species richness in R with sf</a> builds a richness grid and hands it to QGIS as a GeoPackage for styling; this post is about the first styling decision after that handoff. <a href="https://tidyecology.com/posts/choosing-colours-for-ecological-data/">Choosing colours for ecological data</a> is about which colours go on the map; the question here is which values each colour is given to. And where <a href="https://tidyecology.com/posts/running-qgis-from-the-command-line/">Running QGIS from the command line</a> compares Processing algorithms with <code>sf</code> and <code>terra</code>, classification is not a Processing algorithm at all: <code>qgis_process</code> has nothing called Jenks, so the QGIS side below is PyQGIS, calling the same renderer code the Symbology dialog calls. The exact algorithm for one variable is Fisher’s (1958), and Jenks and Caspall (1971) framed the choice of classes on a choropleth map as an error to be made as small as possible. What follows is not a new method but a check of two implementations of it against each other.</p>
<p>No chunk on this page calls QGIS, because the page has to build on a machine that does not have it. The R chunks write the input files, a Python script ran once against <strong>QGIS 3.34.4-Prizren</strong> on Linux and wrote its class tables as small CSV files next to this page, and the R chunks read those files back. The script is <a href="https://tidyecology.com/posts/natural-breaks-in-qgis-and-r/qgis-classes.py">qgis-classes.py</a>, in the same folder.</p>
<div class="cell">
<div class="code-copy-outer-scaffold"><div class="sourceCode cell-code" id="cb1" style="background: #f1f3f5;"><pre class="sourceCode r code-with-copy"><code class="sourceCode r"><span id="cb1-1"><span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">library</span>(ggplot2)</span>
<span id="cb1-2"><span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">library</span>(classInt)</span>
<span id="cb1-3"></span>
<span id="cb1-4">te_paper  <span class="ot" style="color: #003B4F;
background-color: null;
font-style: inherit;">&lt;-</span> <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"#f5f4ee"</span>; te_ink    <span class="ot" style="color: #003B4F;
background-color: null;
font-style: inherit;">&lt;-</span> <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"#16241d"</span>; te_body   <span class="ot" style="color: #003B4F;
background-color: null;
font-style: inherit;">&lt;-</span> <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"#2c3a31"</span></span>
<span id="cb1-5">te_forest <span class="ot" style="color: #003B4F;
background-color: null;
font-style: inherit;">&lt;-</span> <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"#275139"</span>; te_rust   <span class="ot" style="color: #003B4F;
background-color: null;
font-style: inherit;">&lt;-</span> <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"#b5534e"</span>; te_gold   <span class="ot" style="color: #003B4F;
background-color: null;
font-style: inherit;">&lt;-</span> <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"#c9b458"</span></span>
<span id="cb1-6">te_line   <span class="ot" style="color: #003B4F;
background-color: null;
font-style: inherit;">&lt;-</span> <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"#dad9ca"</span></span>
<span id="cb1-7"></span>
<span id="cb1-8">theme_datasheet <span class="ot" style="color: #003B4F;
background-color: null;
font-style: inherit;">&lt;-</span> <span class="cf" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">function</span>() {</span>
<span id="cb1-9">  <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">theme_minimal</span>(<span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">base_size =</span> <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">12</span>) <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">+</span></span>
<span id="cb1-10">    <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">theme</span>(<span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">plot.background  =</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">element_rect</span>(<span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">fill =</span> te_paper, <span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">colour =</span> <span class="cn" style="color: #8f5902;
background-color: null;
font-style: inherit;">NA</span>),</span>
<span id="cb1-11">          <span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">panel.background =</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">element_rect</span>(<span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">fill =</span> te_paper, <span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">colour =</span> <span class="cn" style="color: #8f5902;
background-color: null;
font-style: inherit;">NA</span>),</span>
<span id="cb1-12">          <span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">panel.grid.major =</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">element_line</span>(<span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">colour =</span> te_line, <span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">linewidth =</span> <span class="fl" style="color: #AD0000;
background-color: null;
font-style: inherit;">0.3</span>),</span>
<span id="cb1-13">          <span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">panel.grid.minor =</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">element_blank</span>(),</span>
<span id="cb1-14">          <span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">text             =</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">element_text</span>(<span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">colour =</span> te_body),</span>
<span id="cb1-15">          <span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">plot.title       =</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">element_text</span>(<span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">colour =</span> te_ink, <span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">face =</span> <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"bold"</span>),</span>
<span id="cb1-16">          <span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">plot.subtitle    =</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">element_text</span>(<span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">colour =</span> te_body),</span>
<span id="cb1-17">          <span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">axis.text        =</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">element_text</span>(<span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">colour =</span> te_body))</span>
<span id="cb1-18">}</span>
<span id="cb1-19">class_ver <span class="ot" style="color: #003B4F;
background-color: null;
font-style: inherit;">&lt;-</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">as.character</span>(<span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">packageVersion</span>(<span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"classInt"</span>))</span></code></pre></div></div>
</div>
<section id="the-grid-and-the-files-qgis-read" class="level2">
<h2 id="the-grid-and-the-files-qgis-read-h" class="anchored" data-anchor-id="the-grid-and-the-files-qgis-read">The grid, and the files QGIS read</h2>
<p>Richness is built from a regional gradient, three hotspots and cell noise, so the bulk of the cells sit in the high teens and twenties and a long tail runs up to the hotspot cores, the right skewed shape for which Natural Breaks is usually chosen. A second column holds the change in richness between two periods, which runs from losses to gains. The chunk writes the grid in shuffled row order, so that the first <code>n</code> rows of the file are a random <code>n</code> cells of the map, and it writes a ten kilometre version, the mean of each ten by ten block.</p>
<div class="cell">
<div class="code-copy-outer-scaffold"><div class="sourceCode cell-code" id="cb2" style="background: #f1f3f5;"><pre class="sourceCode r code-with-copy"><code class="sourceCode r"><span id="cb2-1"><span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">set.seed</span>(<span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">20261012</span>)</span>
<span id="cb2-2">n_col <span class="ot" style="color: #003B4F;
background-color: null;
font-style: inherit;">&lt;-</span> <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">300</span>; n_row <span class="ot" style="color: #003B4F;
background-color: null;
font-style: inherit;">&lt;-</span> <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">200</span></span>
<span id="cb2-3">cells <span class="ot" style="color: #003B4F;
background-color: null;
font-style: inherit;">&lt;-</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">expand.grid</span>(<span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">col =</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">seq_len</span>(n_col), <span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">row =</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">seq_len</span>(n_row))</span>
<span id="cb2-4">bump  <span class="ot" style="color: #003B4F;
background-color: null;
font-style: inherit;">&lt;-</span> <span class="cf" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">function</span>(cx, cy, s, a) a <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">*</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">exp</span>(<span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">-</span>((cells<span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">$</span>col <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">-</span> cx)<span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">^</span><span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">2</span> <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">+</span> (cells<span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">$</span>row <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">-</span> cy)<span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">^</span><span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">2</span>) <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">/</span> (<span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">2</span> <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">*</span> s<span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">^</span><span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">2</span>))</span>
<span id="cb2-5">cells<span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">$</span>richness <span class="ot" style="color: #003B4F;
background-color: null;
font-style: inherit;">&lt;-</span> <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">16</span> <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">+</span> <span class="fl" style="color: #AD0000;
background-color: null;
font-style: inherit;">0.04</span> <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">*</span> cells<span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">$</span>row <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">+</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">bump</span>(<span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">70</span>, <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">140</span>, <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">18</span>, <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">55</span>) <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">+</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">bump</span>(<span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">210</span>, <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">60</span>, <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">25</span>, <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">40</span>) <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">+</span></span>
<span id="cb2-6">  <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">bump</span>(<span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">250</span>, <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">160</span>, <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">10</span>, <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">70</span>) <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">+</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">rnorm</span>(<span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">nrow</span>(cells), <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">0</span>, <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">3</span>)</span>
<span id="cb2-7">cells<span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">$</span>change <span class="ot" style="color: #003B4F;
background-color: null;
font-style: inherit;">&lt;-</span> <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">-</span><span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">8</span> <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">+</span> <span class="fl" style="color: #AD0000;
background-color: null;
font-style: inherit;">0.08</span> <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">*</span> cells<span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">$</span>row <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">+</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">bump</span>(<span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">210</span>, <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">60</span>, <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">25</span>, <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">-</span><span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">6</span>) <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">+</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">rnorm</span>(<span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">nrow</span>(cells), <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">0</span>, <span class="fl" style="color: #AD0000;
background-color: null;
font-style: inherit;">2.5</span>)</span>
<span id="cb2-8">cells<span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">$</span>richness <span class="ot" style="color: #003B4F;
background-color: null;
font-style: inherit;">&lt;-</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">round</span>(cells<span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">$</span>richness, <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">4</span>); cells<span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">$</span>change <span class="ot" style="color: #003B4F;
background-color: null;
font-style: inherit;">&lt;-</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">round</span>(cells<span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">$</span>change, <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">4</span>)</span>
<span id="cb2-9"><span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">write.csv</span>(cells[<span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">sample</span>(<span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">nrow</span>(cells)), ], <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"richness-1km.csv"</span>, <span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">row.names =</span> <span class="cn" style="color: #8f5902;
background-color: null;
font-style: inherit;">FALSE</span>)</span>
<span id="cb2-10">blk <span class="ot" style="color: #003B4F;
background-color: null;
font-style: inherit;">&lt;-</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">interaction</span>((cells<span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">$</span>col <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">-</span> <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">1</span>) <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">%/%</span> <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">10</span>, (cells<span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">$</span>row <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">-</span> <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">1</span>) <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">%/%</span> <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">10</span>, <span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">drop =</span> <span class="cn" style="color: #8f5902;
background-color: null;
font-style: inherit;">TRUE</span>)</span>
<span id="cb2-11"><span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">write.csv</span>(<span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">data.frame</span>(<span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">col =</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">tapply</span>((cells<span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">$</span>col <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">-</span> <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">1</span>) <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">%/%</span> <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">10</span> <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">+</span> <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">1</span>, blk, <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">`</span><span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">[</span><span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">`</span>, <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">1</span>),</span>
<span id="cb2-12">                     <span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">row =</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">tapply</span>((cells<span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">$</span>row <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">-</span> <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">1</span>) <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">%/%</span> <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">10</span> <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">+</span> <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">1</span>, blk, <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">`</span><span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">[</span><span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">`</span>, <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">1</span>),</span>
<span id="cb2-13">                     <span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">richness =</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">round</span>(<span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">tapply</span>(cells<span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">$</span>richness, blk, mean), <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">4</span>)),</span>
<span id="cb2-14">          <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"richness-10km.csv"</span>, <span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">row.names =</span> <span class="cn" style="color: #8f5902;
background-color: null;
font-style: inherit;">FALSE</span>)</span>
<span id="cb2-15">grid_1km  <span class="ot" style="color: #003B4F;
background-color: null;
font-style: inherit;">&lt;-</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">read.csv</span>(<span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"richness-1km.csv"</span>); grid_10km <span class="ot" style="color: #003B4F;
background-color: null;
font-style: inherit;">&lt;-</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">read.csv</span>(<span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"richness-10km.csv"</span>)</span>
<span id="cb2-16">qgis_in   <span class="ot" style="color: #003B4F;
background-color: null;
font-style: inherit;">&lt;-</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">read.csv</span>(<span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"qgis-input-check.csv"</span>)</span>
<span id="cb2-17">same_input <span class="ot" style="color: #003B4F;
background-color: null;
font-style: inherit;">&lt;-</span> qgis_in<span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">$</span>cells_1km <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">==</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">nrow</span>(grid_1km) <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">&amp;&amp;</span> qgis_in<span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">$</span>cells_10km <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">==</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">nrow</span>(grid_10km) <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">&amp;&amp;</span></span>
<span id="cb2-18">  <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">isTRUE</span>(<span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">all.equal</span>(<span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">c</span>(qgis_in<span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">$</span>sum_10km, qgis_in<span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">$</span>sum_richness, qgis_in<span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">$</span>sum_change),</span>
<span id="cb2-19">                   <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">c</span>(<span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">sum</span>(grid_10km<span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">$</span>richness), <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">sum</span>(grid_1km<span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">$</span>richness), <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">sum</span>(grid_1km<span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">$</span>change)),</span>
<span id="cb2-20">                   <span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">tolerance =</span> <span class="fl" style="color: #AD0000;
background-color: null;
font-style: inherit;">1e-10</span>))</span>
<span id="cb2-21">rich_q <span class="ot" style="color: #003B4F;
background-color: null;
font-style: inherit;">&lt;-</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">quantile</span>(grid_1km<span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">$</span>richness, <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">c</span>(<span class="fl" style="color: #AD0000;
background-color: null;
font-style: inherit;">0.5</span>, <span class="fl" style="color: #AD0000;
background-color: null;
font-style: inherit;">0.99</span>))</span></code></pre></div></div>
</div>
<p>The one kilometre grid has 60000 cells with predicted richness from 5.0 to 97.0, a median of 22.3 and a 99th percentile of 68.4; the ten kilometre grid has 600. The QGIS script recorded how many rows it read from each file and the sum of each column, and comparing those with what R reads here returns TRUE. If you rebuild this page and that says <code>FALSE</code>, the class tables below were computed from a different file and the comparisons stop meaning anything.</p>
</section>
<section id="four-modes-on-a-small-layer" class="level2">
<h2 id="four-modes-on-a-small-layer-h" class="anchored" data-anchor-id="four-modes-on-a-small-layer">Four modes on a small layer</h2>
<p>On the ten kilometre grid every QGIS mode works on all 600 values, with no sampling anywhere. The PyQGIS part is short: build a point layer from the CSV and ask each classification class for five classes. The upper bounds go to <code>qgis-10km-breaks.csv</code>.</p>
<div class="code-copy-outer-scaffold"><div class="sourceCode" id="cb3" style="background: #f1f3f5;"><pre class="sourceCode python code-with-copy"><code class="sourceCode python"><span id="cb3-1"><span class="cf" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">for</span> mode, cls <span class="kw" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">in</span> [(<span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"equal"</span>, QgsClassificationEqualInterval), (<span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"quantile"</span>, QgsClassificationQuantile),</span>
<span id="cb3-2">                  (<span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"jenks"</span>, QgsClassificationJenks), (<span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"pretty"</span>, QgsClassificationPrettyBreaks)]:</span>
<span id="cb3-3">    <span class="cf" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">for</span> i, c <span class="kw" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">in</span> <span class="bu" style="color: null;
background-color: null;
font-style: inherit;">enumerate</span>(cls().classes(lay10, <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"v"</span>, <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">5</span>)):</span>
<span id="cb3-4">        out.append(<span class="bu" style="color: null;
background-color: null;
font-style: inherit;">dict</span>(mode<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span>mode, klass<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span>i <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">+</span> <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">1</span>, lower<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span><span class="bu" style="color: null;
background-color: null;
font-style: inherit;">repr</span>(bounds(c)[<span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">0</span>]), upper<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span><span class="bu" style="color: null;
background-color: null;
font-style: inherit;">repr</span>(bounds(c)[<span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">1</span>])))</span></code></pre></div></div>
<div class="cell">
<div class="code-copy-outer-scaffold"><div class="sourceCode cell-code" id="cb4" style="background: #f1f3f5;"><pre class="sourceCode r code-with-copy"><code class="sourceCode r"><span id="cb4-1">q10 <span class="ot" style="color: #003B4F;
background-color: null;
font-style: inherit;">&lt;-</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">read.csv</span>(<span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"qgis-10km-breaks.csv"</span>); v10 <span class="ot" style="color: #003B4F;
background-color: null;
font-style: inherit;">&lt;-</span> grid_10km<span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">$</span>richness</span>
<span id="cb4-2">qup <span class="ot" style="color: #003B4F;
background-color: null;
font-style: inherit;">&lt;-</span> <span class="cf" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">function</span>(m) q10<span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">$</span>upper[q10<span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">$</span>mode <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">==</span> m]</span>
<span id="cb4-3">r_equal  <span class="ot" style="color: #003B4F;
background-color: null;
font-style: inherit;">&lt;-</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">classIntervals</span>(v10, <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">5</span>, <span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">style =</span> <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"equal"</span>)<span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">$</span>brks[<span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">-</span><span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">1</span>]</span>
<span id="cb4-4">r_quant  <span class="ot" style="color: #003B4F;
background-color: null;
font-style: inherit;">&lt;-</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">quantile</span>(v10, (<span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">1</span><span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">:</span><span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">5</span>) <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">/</span> <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">5</span>, <span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">type =</span> <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">7</span>, <span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">names =</span> <span class="cn" style="color: #8f5902;
background-color: null;
font-style: inherit;">FALSE</span>)</span>
<span id="cb4-5">other_ty <span class="ot" style="color: #003B4F;
background-color: null;
font-style: inherit;">&lt;-</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">sapply</span>(<span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">c</span>(<span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">1</span><span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">:</span><span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">6</span>, <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">8</span><span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">:</span><span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">9</span>), <span class="cf" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">function</span>(ty)</span>
<span id="cb4-6">  <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">max</span>(<span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">abs</span>(<span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">quantile</span>(v10, (<span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">1</span><span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">:</span><span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">5</span>) <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">/</span> <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">5</span>, <span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">type =</span> ty, <span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">names =</span> <span class="cn" style="color: #8f5902;
background-color: null;
font-style: inherit;">FALSE</span>) <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">-</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">qup</span>(<span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"quantile"</span>))))</span>
<span id="cb4-7">r_jenks  <span class="ot" style="color: #003B4F;
background-color: null;
font-style: inherit;">&lt;-</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">classIntervals</span>(v10, <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">5</span>, <span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">style =</span> <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"jenks"</span>)<span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">$</span>brks[<span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">-</span><span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">1</span>]</span>
<span id="cb4-8">r_fisher <span class="ot" style="color: #003B4F;
background-color: null;
font-style: inherit;">&lt;-</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">classIntervals</span>(v10, <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">5</span>, <span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">style =</span> <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"fisher"</span>)</span>
<span id="cb4-9">r_pretty <span class="ot" style="color: #003B4F;
background-color: null;
font-style: inherit;">&lt;-</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">classIntervals</span>(v10, <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">5</span>, <span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">style =</span> <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"pretty"</span>)<span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">$</span>brks[<span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">-</span><span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">1</span>]</span>
<span id="cb4-10">q_pretty <span class="ot" style="color: #003B4F;
background-color: null;
font-style: inherit;">&lt;-</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">qup</span>(<span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"pretty"</span>)</span>
<span id="cb4-11">fmt <span class="ot" style="color: #003B4F;
background-color: null;
font-style: inherit;">&lt;-</span> <span class="cf" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">function</span>(z) <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">paste</span>(<span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">sprintf</span>(<span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"%.4f"</span>, z), <span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">collapse =</span> <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">", "</span>)</span>
<span id="cb4-12">mode_tab <span class="ot" style="color: #003B4F;
background-color: null;
font-style: inherit;">&lt;-</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">data.frame</span>(</span>
<span id="cb4-13">  <span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">qgis_mode =</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">c</span>(<span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"Equal Interval"</span>, <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"Equal Count (Quantile)"</span>, <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"Natural Breaks (Jenks)"</span>,</span>
<span id="cb4-14">                <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"Pretty Breaks"</span>),</span>
<span id="cb4-15">  <span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">r_call =</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">c</span>(<span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">'`classIntervals(style = "equal")`'</span>, <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"`quantile(type = 7)`"</span>,</span>
<span id="cb4-16">             <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">'`classIntervals(style = "jenks")`'</span>, <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">'`classIntervals(style = "pretty")`'</span>),</span>
<span id="cb4-17">  <span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">qgis_upper =</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">c</span>(<span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">fmt</span>(<span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">qup</span>(<span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"equal"</span>)), <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">fmt</span>(<span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">qup</span>(<span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"quantile"</span>)), <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">fmt</span>(<span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">qup</span>(<span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"jenks"</span>)), <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">fmt</span>(q_pretty)),</span>
<span id="cb4-18">  <span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">r_upper =</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">c</span>(<span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">fmt</span>(r_equal), <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">fmt</span>(r_quant), <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">fmt</span>(r_jenks), <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">fmt</span>(r_pretty)),</span>
<span id="cb4-19">  <span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">identical =</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">c</span>(<span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">identical</span>(<span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">qup</span>(<span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"equal"</span>), r_equal), <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">identical</span>(<span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">qup</span>(<span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"quantile"</span>), r_quant),</span>
<span id="cb4-20">                <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">identical</span>(<span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">qup</span>(<span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"jenks"</span>), r_jenks), <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">identical</span>(q_pretty, r_pretty)))</span>
<span id="cb4-21">knitr<span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">::</span><span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">kable</span>(mode_tab, <span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">col.names =</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">c</span>(<span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"QGIS mode"</span>, <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"R call"</span>, <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"QGIS upper bounds"</span>,</span>
<span id="cb4-22">                                     <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"R upper bounds"</span>, <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"identical"</span>),</span>
<span id="cb4-23">             <span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">caption =</span> <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"Five classes asked for, ten kilometre grid, upper bound of each class."</span>)</span></code></pre></div></div>
<div class="cell-output-display">
<table class="caption-top table table-sm table-striped small">
<caption>Five classes asked for, ten kilometre grid, upper bound of each class.</caption>
<colgroup>
<col style="width: 11%">
<col style="width: 18%">
<col style="width: 32%">
<col style="width: 32%">
<col style="width: 5%">
</colgroup>
<thead>
<tr class="header">
<th style="text-align: left;">QGIS mode</th>
<th style="text-align: left;">R call</th>
<th style="text-align: left;">QGIS upper bounds</th>
<th style="text-align: left;">R upper bounds</th>
<th style="text-align: left;">identical</th>
</tr>
</thead>
<tbody>
<tr class="odd">
<td style="text-align: left;">Equal Interval</td>
<td style="text-align: left;"><code>classIntervals(style = "equal")</code></td>
<td style="text-align: left;">27.7735, 39.8101, 51.8466, 63.8832, 75.9197</td>
<td style="text-align: left;">27.7735, 39.8101, 51.8466, 63.8832, 75.9197</td>
<td style="text-align: left;">FALSE</td>
</tr>
<tr class="even">
<td style="text-align: left;">Equal Count (Quantile)</td>
<td style="text-align: left;"><code>quantile(type = 7)</code></td>
<td style="text-align: left;">18.6207, 21.3722, 23.2521, 27.6863, 75.9197</td>
<td style="text-align: left;">18.6207, 21.3722, 23.2521, 27.6863, 75.9197</td>
<td style="text-align: left;">TRUE</td>
</tr>
<tr class="odd">
<td style="text-align: left;">Natural Breaks (Jenks)</td>
<td style="text-align: left;"><code>classIntervals(style = "jenks")</code></td>
<td style="text-align: left;">20.7135, 27.1160, 37.6361, 51.3886, 75.9197</td>
<td style="text-align: left;">20.7995, 27.1160, 37.6361, 51.3886, 75.9197</td>
<td style="text-align: left;">FALSE</td>
</tr>
<tr class="even">
<td style="text-align: left;">Pretty Breaks</td>
<td style="text-align: left;"><code>classIntervals(style = "pretty")</code></td>
<td style="text-align: left;">20.0000, 30.0000, 40.0000, 50.0000, 60.0000, 70.0000, 75.9197</td>
<td style="text-align: left;">20.0000, 30.0000, 40.0000, 50.0000, 60.0000, 70.0000, 80.0000</td>
<td style="text-align: left;">FALSE</td>
</tr>
</tbody>
</table>
</div>
<div class="code-copy-outer-scaffold"><div class="sourceCode cell-code" id="cb5" style="background: #f1f3f5;"><pre class="sourceCode r code-with-copy"><code class="sourceCode r"><span id="cb5-1">n_pretty_q <span class="ot" style="color: #003B4F;
background-color: null;
font-style: inherit;">&lt;-</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">length</span>(q_pretty); n_pretty_r <span class="ot" style="color: #003B4F;
background-color: null;
font-style: inherit;">&lt;-</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">length</span>(r_pretty)</span>
<span id="cb5-2">inner_same <span class="ot" style="color: #003B4F;
background-color: null;
font-style: inherit;">&lt;-</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">all</span>(<span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">head</span>(q_pretty, <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">-</span><span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">1</span>) <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">==</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">head</span>(r_pretty, <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">-</span><span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">1</span>))</span>
<span id="cb5-3">jenks_gap  <span class="ot" style="color: #003B4F;
background-color: null;
font-style: inherit;">&lt;-</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">max</span>(<span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">abs</span>(<span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">qup</span>(<span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"jenks"</span>) <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">-</span> r_jenks)); jenks_ndiff <span class="ot" style="color: #003B4F;
background-color: null;
font-style: inherit;">&lt;-</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">sum</span>(<span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">qup</span>(<span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"jenks"</span>) <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">!=</span> r_jenks)</span></code></pre></div></div>
</div>
<p>Equal Interval and Quantile are the same formulas in both programs, and their bounds agree to every printed digit; as vectors of doubles, <code>identical()</code> gives FALSE for Equal Interval and TRUE for Quantile on the build that rendered this page. Equality to the last bit is not guaranteed, because QGIS adds the equal interval step repeatedly where R multiplies it, and it computes the quantile position in a slightly different order; any difference sits in the last bits of a double, far below anything a legend prints. The QGIS quantile is R’s type 7, the default of <code>quantile()</code>; the other eight types miss it by between 0.0337 and 0.0680 richness units. (The comment above that code in <code>qgsclassificationquantile.cpp</code> describes an <code>(n + 1)</code> rule, which would be type 6; the line underneath it computes <code>q * (n - 1)</code>, which is type 7.) Pretty Breaks agree on every interior break, and both returned 7 classes when asked for five, because a pretty sequence picks the round step first and lets the class count follow. They differ only at the ends: R’s classes run from 10 to 80, while QGIS starts the first class at the data minimum and stops the last at the data maximum, 75.9197. That the interior breaks are equal as doubles is TRUE.</p>
<p>Natural Breaks does not match: of the five upper bounds, 1 differs, the lowest, by 0.0860, and the other four agree.</p>
<section id="where-the-jenks-difference-comes-from" class="level3">
<h3 id="where-the-jenks-difference-comes-from-h" class="anchored" data-anchor-id="where-the-jenks-difference-comes-from">Where the Jenks difference comes from</h3>
<p><code>classInt</code> and QGIS run the same dynamic programming algorithm, and the QGIS source names the <code>classInt</code> code as one of its bases. The algorithm fills a table, row by row, with the cheapest way to split the first <code>l</code> sorted values into <code>j</code> classes, remembering where the last class starts, and then walks back through that table from the top. The difference is in the walk back. <code>classInt</code> stores the position where the last class starts and steps back to the value before it. QGIS stores the position of the last value before the start, then subtracts one more:</p>
<div class="code-copy-outer-scaffold"><div class="sourceCode" id="cb6" style="background: #f1f3f5;"><pre class="sourceCode cpp code-with-copy"><code class="sourceCode cpp"><span id="cb6-1">            matrixOne<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">[</span>l<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">][</span>j<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">]</span> <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> i4<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">;</span></span>
<span id="cb6-2"><span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">...</span></span>
<span id="cb6-3">    k <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> matrixOne<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">[</span>k<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">][</span>j<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">]</span> <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">-</span> <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">1</span><span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">;</span></span></code></pre></div></div>
<p>Those are lines 171 and 188 of <a href="https://github.com/qgis/QGIS/blob/release-3_34/src/core/classification/qgsclassificationjenks.cpp">qgsclassificationjenks.cpp</a> on the 3.34 branch. The break it reports at each step is still a real class boundary, but the next step looks up the best split of one value fewer than it should, so the classes below it come from a different problem, whose answer can be far from the best one. With two classes the walk back takes only one step and the extra subtraction is never used, so only three or more classes are affected. The chunk below ports that function to R line by line, vectorising only the innermost loop, with a switch that removes the extra <code>- 1</code>.</p>
<div class="cell">
<div class="code-copy-outer-scaffold"><div class="sourceCode cell-code" id="cb7" style="background: #f1f3f5;"><pre class="sourceCode r code-with-copy"><code class="sourceCode r"><span id="cb7-1">qgis_jenks <span class="ot" style="color: #003B4F;
background-color: null;
font-style: inherit;">&lt;-</span> <span class="cf" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">function</span>(smp, k, <span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">fix =</span> <span class="cn" style="color: #8f5902;
background-color: null;
font-style: inherit;">FALSE</span>) {</span>
<span id="cb7-2">  smp <span class="ot" style="color: #003B4F;
background-color: null;
font-style: inherit;">&lt;-</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">sort</span>(smp); n <span class="ot" style="color: #003B4F;
background-color: null;
font-style: inherit;">&lt;-</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">length</span>(smp)</span>
<span id="cb7-3">  one <span class="ot" style="color: #003B4F;
background-color: null;
font-style: inherit;">&lt;-</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">matrix</span>(<span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">0</span>L, n <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">+</span> <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">1</span>, k); two <span class="ot" style="color: #003B4F;
background-color: null;
font-style: inherit;">&lt;-</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">matrix</span>(<span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">0</span>, n <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">+</span> <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">1</span>, k)   <span class="co" style="color: #5E5E5E;
background-color: null;
font-style: inherit;"># row l + 1 holds l values</span></span>
<span id="cb7-4">  one[<span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">1</span><span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">:</span><span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">2</span>, ] <span class="ot" style="color: #003B4F;
background-color: null;
font-style: inherit;">&lt;-</span> <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">1</span>L; two[<span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">3</span><span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">:</span>(n <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">+</span> <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">1</span>), ] <span class="ot" style="color: #003B4F;
background-color: null;
font-style: inherit;">&lt;-</span> .Machine<span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">$</span>double.xmax</span>
<span id="cb7-5">  <span class="cf" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">for</span> (l <span class="cf" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">in</span> <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">2</span><span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">:</span>n) {</span>
<span id="cb7-6">    vals <span class="ot" style="color: #003B4F;
background-color: null;
font-style: inherit;">&lt;-</span> smp[l<span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">:</span><span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">1</span>]                         <span class="co" style="color: #5E5E5E;
background-color: null;
font-style: inherit;"># the inner loop visits values l, l - 1, ..., 1</span></span>
<span id="cb7-7">    s1 <span class="ot" style="color: #003B4F;
background-color: null;
font-style: inherit;">&lt;-</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">cumsum</span>(vals); s2 <span class="ot" style="color: #003B4F;
background-color: null;
font-style: inherit;">&lt;-</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">cumsum</span>(vals <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">*</span> vals); w <span class="ot" style="color: #003B4F;
background-color: null;
font-style: inherit;">&lt;-</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">seq_len</span>(l)</span>
<span id="cb7-8">    v  <span class="ot" style="color: #003B4F;
background-color: null;
font-style: inherit;">&lt;-</span> s2 <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">-</span> s1 <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">*</span> s1 <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">/</span> w                   <span class="co" style="color: #5E5E5E;
background-color: null;
font-style: inherit;"># sum of squares of the last w values</span></span>
<span id="cb7-9">    i4 <span class="ot" style="color: #003B4F;
background-color: null;
font-style: inherit;">&lt;-</span> l <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">-</span> w; ok <span class="ot" style="color: #003B4F;
background-color: null;
font-style: inherit;">&lt;-</span> i4 <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">!=</span> <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">0</span></span>
<span id="cb7-10">    <span class="cf" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">for</span> (j <span class="cf" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">in</span> <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">2</span><span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">:</span>k) {</span>
<span id="cb7-11">      cand <span class="ot" style="color: #003B4F;
background-color: null;
font-style: inherit;">&lt;-</span> v[ok] <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">+</span> two[i4[ok] <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">+</span> <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">1</span>, j <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">-</span> <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">1</span>]</span>
<span id="cb7-12">      best <span class="ot" style="color: #003B4F;
background-color: null;
font-style: inherit;">&lt;-</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">max</span>(<span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">which</span>(cand <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">==</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">min</span>(cand)))  <span class="co" style="color: #5E5E5E;
background-color: null;
font-style: inherit;"># QGIS tests &gt;=, so the last minimum wins</span></span>
<span id="cb7-13">      one[l <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">+</span> <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">1</span>, j] <span class="ot" style="color: #003B4F;
background-color: null;
font-style: inherit;">&lt;-</span> i4[ok][best]; two[l <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">+</span> <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">1</span>, j] <span class="ot" style="color: #003B4F;
background-color: null;
font-style: inherit;">&lt;-</span> cand[best]</span>
<span id="cb7-14">    }</span>
<span id="cb7-15">    one[l <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">+</span> <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">1</span>, <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">1</span>] <span class="ot" style="color: #003B4F;
background-color: null;
font-style: inherit;">&lt;-</span> <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">1</span>L; two[l <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">+</span> <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">1</span>, <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">1</span>] <span class="ot" style="color: #003B4F;
background-color: null;
font-style: inherit;">&lt;-</span> v[l]</span>
<span id="cb7-16">  }</span>
<span id="cb7-17">  brk <span class="ot" style="color: #003B4F;
background-color: null;
font-style: inherit;">&lt;-</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">numeric</span>(k); brk[k] <span class="ot" style="color: #003B4F;
background-color: null;
font-style: inherit;">&lt;-</span> smp[n]; kk <span class="ot" style="color: #003B4F;
background-color: null;
font-style: inherit;">&lt;-</span> n</span>
<span id="cb7-18">  <span class="cf" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">for</span> (j <span class="cf" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">in</span> k<span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">:</span><span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">2</span>) {</span>
<span id="cb7-19">    brk[j <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">-</span> <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">1</span>] <span class="ot" style="color: #003B4F;
background-color: null;
font-style: inherit;">&lt;-</span> smp[one[kk <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">+</span> <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">1</span>, j]]</span>
<span id="cb7-20">    kk <span class="ot" style="color: #003B4F;
background-color: null;
font-style: inherit;">&lt;-</span> <span class="cf" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">if</span> (fix) one[kk <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">+</span> <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">1</span>, j] <span class="cf" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">else</span> one[kk <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">+</span> <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">1</span>, j] <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">-</span> <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">1</span></span>
<span id="cb7-21">  }</span>
<span id="cb7-22">  brk</span>
<span id="cb7-23">}</span>
<span id="cb7-24"><span class="co" style="color: #5E5E5E;
background-color: null;
font-style: inherit;"># which class QGIS draws a value in: the first range with lower &lt;= value &lt;= upper</span></span>
<span id="cb7-25">qgis_class <span class="ot" style="color: #003B4F;
background-color: null;
font-style: inherit;">&lt;-</span> <span class="cf" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">function</span>(x, lower, upper) {</span>
<span id="cb7-26">  cl <span class="ot" style="color: #003B4F;
background-color: null;
font-style: inherit;">&lt;-</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">rep</span>(<span class="cn" style="color: #8f5902;
background-color: null;
font-style: inherit;">NA_integer_</span>, <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">length</span>(x))</span>
<span id="cb7-27">  <span class="cf" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">for</span> (k <span class="cf" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">in</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">seq_along</span>(lower)) cl[<span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">is.na</span>(cl) <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">&amp;</span> x <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">&gt;=</span> lower[k] <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">&amp;</span> x <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">&lt;=</span> upper[k]] <span class="ot" style="color: #003B4F;
background-color: null;
font-style: inherit;">&lt;-</span> k</span>
<span id="cb7-28">  cl</span>
<span id="cb7-29">}</span>
<span id="cb7-30">gvf <span class="ot" style="color: #003B4F;
background-color: null;
font-style: inherit;">&lt;-</span> <span class="cf" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">function</span>(x, cl) <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">1</span> <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">-</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">sum</span>(<span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">tapply</span>(x, cl, <span class="cf" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">function</span>(z) <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">sum</span>((z <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">-</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">mean</span>(z))<span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">^</span><span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">2</span>))) <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">/</span></span>
<span id="cb7-31">  <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">sum</span>((x <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">-</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">mean</span>(x))<span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">^</span><span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">2</span>)</span>
<span id="cb7-32">port_same  <span class="ot" style="color: #003B4F;
background-color: null;
font-style: inherit;">&lt;-</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">identical</span>(<span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">qgis_jenks</span>(v10, <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">5</span>), <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">qup</span>(<span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"jenks"</span>))</span>
<span id="cb7-33">fixed_same <span class="ot" style="color: #003B4F;
background-color: null;
font-style: inherit;">&lt;-</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">identical</span>(<span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">qgis_jenks</span>(v10, <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">5</span>, <span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">fix =</span> <span class="cn" style="color: #8f5902;
background-color: null;
font-style: inherit;">TRUE</span>), r_jenks)</span>
<span id="cb7-34">cl_q10  <span class="ot" style="color: #003B4F;
background-color: null;
font-style: inherit;">&lt;-</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">qgis_class</span>(v10, q10<span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">$</span>lower[q10<span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">$</span>mode <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">==</span> <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"jenks"</span>], <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">qup</span>(<span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"jenks"</span>))</span>
<span id="cb7-35">cl_r10  <span class="ot" style="color: #003B4F;
background-color: null;
font-style: inherit;">&lt;-</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">findInterval</span>(v10, r_jenks[<span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">-</span><span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">5</span>], <span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">left.open =</span> <span class="cn" style="color: #8f5902;
background-color: null;
font-style: inherit;">TRUE</span>) <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">+</span> <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">1</span></span>
<span id="cb7-36">cl_f10  <span class="ot" style="color: #003B4F;
background-color: null;
font-style: inherit;">&lt;-</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">findCols</span>(r_fisher)</span>
<span id="cb7-37">moved   <span class="ot" style="color: #003B4F;
background-color: null;
font-style: inherit;">&lt;-</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">sum</span>(cl_q10 <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">!=</span> cl_r10); fisher_part <span class="ot" style="color: #003B4F;
background-color: null;
font-style: inherit;">&lt;-</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">identical</span>(cl_f10, <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">as.integer</span>(cl_r10))</span>
<span id="cb7-38">gvf_q10 <span class="ot" style="color: #003B4F;
background-color: null;
font-style: inherit;">&lt;-</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">gvf</span>(v10, cl_q10); gvf_r10 <span class="ot" style="color: #003B4F;
background-color: null;
font-style: inherit;">&lt;-</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">gvf</span>(v10, cl_r10)</span></code></pre></div></div>
</div>
<p>The port reproduces the QGIS breaks exactly (<code>identical()</code> gives TRUE), and with the extra step removed it reproduces <code>classInt</code> exactly (TRUE). On this layer the cost is small: 7 of 600 cells change class, and the goodness of variance fit, one minus the within class sum of squares over the total sum of squares, is 0.947481 for QGIS against 0.947484 for the optimum. <code>style = "fisher"</code> in <code>classInt</code> finds the same partition as <code>style = "jenks"</code>: that the two put every cell in the same class is TRUE. It reports the breaks differently, as midpoints between the last value of one class and the first of the next, so its first break prints as 20.8093 where <code>jenks</code> prints 20.7995. For a legend that difference is cosmetic; for reproducing someone’s classes it is not.</p>
</section>
<section id="seven-values-with-an-obvious-answer" class="level3">
<h3 id="seven-values-with-an-obvious-answer-h" class="anchored" data-anchor-id="seven-values-with-an-obvious-answer">Seven values with an obvious answer</h3>
<p>On the ten kilometre grid the extra step moved one break a little. Seven values show what it can do. The values 1, 2, 3, 50, 100, 101 and 102 fall into three groups that anyone would draw, and the script classed them through the same Graduated renderer call as before, into two and into three classes, and wrote the ranges to <code>qgis-tiny.csv</code>:</p>
<div class="code-copy-outer-scaffold"><div class="sourceCode" id="cb8" style="background: #f1f3f5;"><pre class="sourceCode python code-with-copy"><code class="sourceCode python"><span id="cb8-1">tiny <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> [<span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">1</span>, <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">2</span>, <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">3</span>, <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">50</span>, <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">100</span>, <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">101</span>, <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">102</span>]</span>
<span id="cb8-2"><span class="cf" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">for</span> k <span class="kw" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">in</span> [<span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">2</span>, <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">3</span>]:</span>
<span id="cb8-3">    ranges, tally <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> graduated_jenks(point_layer(tiny_rows, <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"v"</span>, <span class="bu" style="color: null;
background-color: null;
font-style: inherit;">len</span>(tiny)), k)</span></code></pre></div></div>
<div class="cell">
<div class="code-copy-outer-scaffold"><div class="sourceCode cell-code" id="cb9" style="background: #f1f3f5;"><pre class="sourceCode r code-with-copy"><code class="sourceCode r"><span id="cb9-1">qt <span class="ot" style="color: #003B4F;
background-color: null;
font-style: inherit;">&lt;-</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">read.csv</span>(<span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"qgis-tiny.csv"</span>); x7 <span class="ot" style="color: #003B4F;
background-color: null;
font-style: inherit;">&lt;-</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">c</span>(<span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">1</span>, <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">2</span>, <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">3</span>, <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">50</span>, <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">100</span>, <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">101</span>, <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">102</span>)</span>
<span id="cb9-2">q7_3 <span class="ot" style="color: #003B4F;
background-color: null;
font-style: inherit;">&lt;-</span> qt[qt<span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">$</span>k <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">==</span> <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">3</span>, ]; q7_2 <span class="ot" style="color: #003B4F;
background-color: null;
font-style: inherit;">&lt;-</span> qt[qt<span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">$</span>k <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">==</span> <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">2</span>, ]</span>
<span id="cb9-3">wss <span class="ot" style="color: #003B4F;
background-color: null;
font-style: inherit;">&lt;-</span> <span class="cf" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">function</span>(x, lower, upper)                 <span class="co" style="color: #5E5E5E;
background-color: null;
font-style: inherit;"># within class sum of squares</span></span>
<span id="cb9-4">  <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">sum</span>(<span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">tapply</span>(x, <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">qgis_class</span>(x, lower, upper), <span class="cf" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">function</span>(z) <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">sum</span>((z <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">-</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">mean</span>(z))<span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">^</span><span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">2</span>)))</span>
<span id="cb9-5">up7 <span class="ot" style="color: #003B4F;
background-color: null;
font-style: inherit;">&lt;-</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">list</span>(<span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">qgis  =</span> q7_3<span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">$</span>upper, <span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">port =</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">qgis_jenks</span>(x7, <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">3</span>), <span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">fixed =</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">qgis_jenks</span>(x7, <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">3</span>, <span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">fix =</span> <span class="cn" style="color: #8f5902;
background-color: null;
font-style: inherit;">TRUE</span>),</span>
<span id="cb9-6">            <span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">jenks =</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">classIntervals</span>(x7, <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">3</span>, <span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">style =</span> <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"jenks"</span>)<span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">$</span>brks[<span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">-</span><span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">1</span>])</span>
<span id="cb9-7">tiny_tab <span class="ot" style="color: #003B4F;
background-color: null;
font-style: inherit;">&lt;-</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">data.frame</span>(</span>
<span id="cb9-8">  <span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">route =</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">c</span>(<span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"QGIS, Graduated renderer (`qgis-tiny.csv`)"</span>, <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"R port of the QGIS function"</span>,</span>
<span id="cb9-9">            <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"R port without the extra step"</span>, <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">'`classIntervals(style = "jenks")`'</span>),</span>
<span id="cb9-10">  <span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">upper =</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">sapply</span>(up7, <span class="cf" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">function</span>(u) <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">paste</span>(u, <span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">collapse =</span> <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">", "</span>)),</span>
<span id="cb9-11">  <span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">sizes =</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">sapply</span>(up7, <span class="cf" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">function</span>(u) <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">paste</span>(<span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">tabulate</span>(<span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">qgis_class</span>(x7, <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">c</span>(<span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">min</span>(x7), <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">head</span>(u, <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">-</span><span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">1</span>)), u), <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">3</span>),</span>
<span id="cb9-12">                                        <span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">collapse =</span> <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">", "</span>)),</span>
<span id="cb9-13">  <span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">wss =</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">sapply</span>(up7, <span class="cf" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">function</span>(u) <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">sprintf</span>(<span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"%.1f"</span>, <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">wss</span>(x7, <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">c</span>(<span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">min</span>(x7), <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">head</span>(u, <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">-</span><span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">1</span>)), u))))</span>
<span id="cb9-14">knitr<span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">::</span><span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">kable</span>(tiny_tab, <span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">row.names =</span> <span class="cn" style="color: #8f5902;
background-color: null;
font-style: inherit;">FALSE</span>,</span>
<span id="cb9-15">             <span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">col.names =</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">c</span>(<span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"route"</span>, <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"upper bounds"</span>, <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"values per class"</span>, <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"within class SS"</span>),</span>
<span id="cb9-16">             <span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">caption =</span> <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"Three classes of the seven values 1, 2, 3, 50, 100, 101, 102."</span>)</span></code></pre></div></div>
<div class="cell-output-display">
<table class="caption-top table table-sm table-striped small">
<caption>Three classes of the seven values 1, 2, 3, 50, 100, 101, 102.</caption>
<colgroup>
<col style="width: 48%">
<col style="width: 14%">
<col style="width: 19%">
<col style="width: 17%">
</colgroup>
<thead>
<tr class="header">
<th style="text-align: left;">route</th>
<th style="text-align: left;">upper bounds</th>
<th style="text-align: left;">values per class</th>
<th style="text-align: left;">within class SS</th>
</tr>
</thead>
<tbody>
<tr class="odd">
<td style="text-align: left;">QGIS, Graduated renderer (<code>qgis-tiny.csv</code>)</td>
<td style="text-align: left;">1, 50, 102</td>
<td style="text-align: left;">1, 3, 3</td>
<td style="text-align: left;">1506.7</td>
</tr>
<tr class="even">
<td style="text-align: left;">R port of the QGIS function</td>
<td style="text-align: left;">1, 50, 102</td>
<td style="text-align: left;">1, 3, 3</td>
<td style="text-align: left;">1506.7</td>
</tr>
<tr class="odd">
<td style="text-align: left;">R port without the extra step</td>
<td style="text-align: left;">3, 50, 102</td>
<td style="text-align: left;">3, 1, 3</td>
<td style="text-align: left;">4.0</td>
</tr>
<tr class="even">
<td style="text-align: left;"><code>classIntervals(style = "jenks")</code></td>
<td style="text-align: left;">3, 50, 102</td>
<td style="text-align: left;">3, 1, 3</td>
<td style="text-align: left;">4.0</td>
</tr>
</tbody>
</table>
</div>
<div class="code-copy-outer-scaffold"><div class="sourceCode cell-code" id="cb10" style="background: #f1f3f5;"><pre class="sourceCode r code-with-copy"><code class="sourceCode r"><span id="cb10-1">tiny_port <span class="ot" style="color: #003B4F;
background-color: null;
font-style: inherit;">&lt;-</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">identical</span>(up7<span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">$</span>port, up7<span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">$</span>qgis); tiny_opt <span class="ot" style="color: #003B4F;
background-color: null;
font-style: inherit;">&lt;-</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">identical</span>(up7<span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">$</span>fixed, up7<span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">$</span>jenks)</span>
<span id="cb10-2">two_same  <span class="ot" style="color: #003B4F;
background-color: null;
font-style: inherit;">&lt;-</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">identical</span>(q7_2<span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">$</span>upper, <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">classIntervals</span>(x7, <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">2</span>, <span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">style =</span> <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"jenks"</span>)<span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">$</span>brks[<span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">-</span><span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">1</span>])</span></code></pre></div></div>
</div>
<p>QGIS puts 1 alone in the first class and 2 and 3 in a class with 50. Its first class runs from 1 to 1 and holds 1 value, and its within class sum of squares is 1506.7 against 4.0 for the obvious grouping. The port gives the QGIS answer (TRUE), and without the extra step it gives the <code>classInt</code> answer (TRUE). With two classes, where the step is never used, QGIS and <code>classInt</code> agree: TRUE.</p>
<p>How often does this matter on a layer small enough that QGIS uses every value? The chunk below draws 200 right skewed (lognormal) layers of each of three sizes, classes each into five with the port as it stands and with the extra step removed, and records how often the two disagree and what the QGIS classes lose in goodness of variance fit.</p>
<div class="cell">
<div class="code-copy-outer-scaffold"><div class="sourceCode cell-code" id="cb11" style="background: #f1f3f5;"><pre class="sourceCode r code-with-copy"><code class="sourceCode r"><span id="cb11-1"><span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">set.seed</span>(<span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">20261012</span>)</span>
<span id="cb11-2">cls_up <span class="ot" style="color: #003B4F;
background-color: null;
font-style: inherit;">&lt;-</span> <span class="cf" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">function</span>(x, up) <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">findInterval</span>(x, <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">head</span>(up, <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">-</span><span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">1</span>), <span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">left.open =</span> <span class="cn" style="color: #8f5902;
background-color: null;
font-style: inherit;">TRUE</span>) <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">+</span> <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">1</span></span>
<span id="cb11-3">small <span class="ot" style="color: #003B4F;
background-color: null;
font-style: inherit;">&lt;-</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">do.call</span>(rbind, <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">lapply</span>(<span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">c</span>(<span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">30</span>, <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">100</span>, <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">400</span>), <span class="cf" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">function</span>(n) {</span>
<span id="cb11-4">  r <span class="ot" style="color: #003B4F;
background-color: null;
font-style: inherit;">&lt;-</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">replicate</span>(<span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">200</span>, {</span>
<span id="cb11-5">    x <span class="ot" style="color: #003B4F;
background-color: null;
font-style: inherit;">&lt;-</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">rlnorm</span>(n, <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">0</span>, <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">1</span>); a <span class="ot" style="color: #003B4F;
background-color: null;
font-style: inherit;">&lt;-</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">qgis_jenks</span>(x, <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">5</span>); b <span class="ot" style="color: #003B4F;
background-color: null;
font-style: inherit;">&lt;-</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">qgis_jenks</span>(x, <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">5</span>, <span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">fix =</span> <span class="cn" style="color: #8f5902;
background-color: null;
font-style: inherit;">TRUE</span>)</span>
<span id="cb11-6">    <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">c</span>(<span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">differ =</span> <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">!</span><span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">identical</span>(a, b), <span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">loss =</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">gvf</span>(x, <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">cls_up</span>(x, b)) <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">-</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">gvf</span>(x, <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">cls_up</span>(x, a)))</span>
<span id="cb11-7">  })</span>
<span id="cb11-8">  <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">data.frame</span>(<span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">n =</span> n, <span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">differ =</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">mean</span>(r[<span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"differ"</span>, ]), <span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">med_loss =</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">median</span>(r[<span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"loss"</span>, r[<span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"differ"</span>, ] <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">==</span> <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">1</span>]),</span>
<span id="cb11-9">             <span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">max_loss =</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">max</span>(r[<span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"loss"</span>, ]))</span>
<span id="cb11-10">}))</span>
<span id="cb11-11">knitr<span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">::</span><span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">kable</span>(small, <span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">digits =</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">c</span>(<span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">0</span>, <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">3</span>, <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">4</span>, <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">3</span>),</span>
<span id="cb11-12">             <span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">col.names =</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">c</span>(<span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"values"</span>, <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"share with different classes"</span>, <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"median GVF loss, when different"</span>,</span>
<span id="cb11-13">                           <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"largest GVF loss"</span>),</span>
<span id="cb11-14">             <span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">caption =</span> <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"Five classes on 200 lognormal layers of each size: QGIS against the optimum."</span>)</span></code></pre></div></div>
<div class="cell-output-display">
<table class="caption-top table table-sm table-striped small">
<caption>Five classes on 200 lognormal layers of each size: QGIS against the optimum.</caption>
<colgroup>
<col style="width: 8%">
<col style="width: 34%">
<col style="width: 37%">
<col style="width: 20%">
</colgroup>
<thead>
<tr class="header">
<th style="text-align: right;">values</th>
<th style="text-align: right;">share with different classes</th>
<th style="text-align: right;">median GVF loss, when different</th>
<th style="text-align: right;">largest GVF loss</th>
</tr>
</thead>
<tbody>
<tr class="odd">
<td style="text-align: right;">30</td>
<td style="text-align: right;">0.735</td>
<td style="text-align: right;">0.0038</td>
<td style="text-align: right;">0.183</td>
</tr>
<tr class="even">
<td style="text-align: right;">100</td>
<td style="text-align: right;">0.770</td>
<td style="text-align: right;">0.0009</td>
<td style="text-align: right;">0.090</td>
</tr>
<tr class="odd">
<td style="text-align: right;">400</td>
<td style="text-align: right;">0.810</td>
<td style="text-align: right;">0.0002</td>
<td style="text-align: right;">0.030</td>
</tr>
</tbody>
</table>
</div>
</div>
<p>At every size the QGIS classes differ from the optimum in most layers, in 74 to 81 per cent of them. The loss is usually small: among the layers where the classes differ, the median loss in goodness of variance fit is 0.0038 at 30 values and less on larger layers. The worst cases are not small. On layers of 30 values the largest loss was 0.183, and on layers of 400 it was still 0.030. So the step matters on small layers too, where QGIS uses every value and no sampling can be blamed.</p>
</section>
</section>
<section id="above-3000-cells-qgis-classifies-a-sample" class="level2">
<h2 id="above-3000-cells-qgis-classifies-a-sample-h" class="anchored" data-anchor-id="above-3000-cells-qgis-classifies-a-sample">Above 3000 cells, QGIS classifies a sample</h2>
<p>The algorithm costs time in proportion to the square of the number of values, so QGIS does not run it on a large layer. The header sets <code>mMaximumSize = 3000</code>, and above that the function builds a sample instead. Since QGIS 3.20 the sample is systematic: sort all values, put the minimum and maximum in the first two slots, and step through the sorted values so that 2998 more of them, evenly spaced in rank, fill the next slots. That makes the classes stable from one click to the next, which the earlier random sample was not, and it is also what the port needs to reproduce QGIS on the full grid.</p>
<div class="cell">
<div class="code-copy-outer-scaffold"><div class="sourceCode cell-code" id="cb12" style="background: #f1f3f5;"><pre class="sourceCode r code-with-copy"><code class="sourceCode r"><span id="cb12-1">qgis_sample <span class="ot" style="color: #003B4F;
background-color: null;
font-style: inherit;">&lt;-</span> <span class="cf" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">function</span>(x, <span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">max_size =</span> <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">3000</span>) {</span>
<span id="cb12-2">  n_val <span class="ot" style="color: #003B4F;
background-color: null;
font-style: inherit;">&lt;-</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">length</span>(x); s <span class="ot" style="color: #003B4F;
background-color: null;
font-style: inherit;">&lt;-</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">sort</span>(x)</span>
<span id="cb12-3">  <span class="cf" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">if</span> (n_val <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">&lt;=</span> max_size) <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">return</span>(s)</span>
<span id="cb12-4">  out <span class="ot" style="color: #003B4F;
background-color: null;
font-style: inherit;">&lt;-</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">numeric</span>(<span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">max</span>(max_size, n_val <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">%/%</span> <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">10</span>))    <span class="co" style="color: #5E5E5E;
background-color: null;
font-style: inherit;"># sample.resize(max(3000, n / 10))</span></span>
<span id="cb12-5">  out[<span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">1</span>] <span class="ot" style="color: #003B4F;
background-color: null;
font-style: inherit;">&lt;-</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">min</span>(x); out[<span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">2</span>] <span class="ot" style="color: #003B4F;
background-color: null;
font-style: inherit;">&lt;-</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">max</span>(x)</span>
<span id="cb12-6">  i <span class="ot" style="color: #003B4F;
background-color: null;
font-style: inherit;">&lt;-</span> <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">1</span><span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">:</span>(n_val <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">-</span> <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">3</span>); step <span class="ot" style="color: #003B4F;
background-color: null;
font-style: inherit;">&lt;-</span> (i <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">*</span> (max_size <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">-</span> <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">2</span>)) <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">%/%</span> (n_val <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">-</span> <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">2</span>)</span>
<span id="cb12-7">  pick <span class="ot" style="color: #003B4F;
background-color: null;
font-style: inherit;">&lt;-</span> i[step <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">&gt;</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">c</span>(<span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">-</span><span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">1</span>, <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">head</span>(step, <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">-</span><span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">1</span>))]         <span class="co" style="color: #5E5E5E;
background-color: null;
font-style: inherit;"># j++ whenever the integer ratio moves on</span></span>
<span id="cb12-8">  out[<span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">2</span> <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">+</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">seq_along</span>(pick)] <span class="ot" style="color: #003B4F;
background-color: null;
font-style: inherit;">&lt;-</span> s[pick <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">+</span> <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">1</span>]</span>
<span id="cb12-9">  out</span>
<span id="cb12-10">}</span>
<span id="cb12-11">runs <span class="ot" style="color: #003B4F;
background-color: null;
font-style: inherit;">&lt;-</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">read.csv</span>(<span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"qgis-jenks-runs.csv"</span>)</span>
<span id="cb12-12">run_id <span class="ot" style="color: #003B4F;
background-color: null;
font-style: inherit;">&lt;-</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">unique</span>(runs[, <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">c</span>(<span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"field"</span>, <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"n"</span>, <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"shift"</span>)])</span>
<span id="cb12-13">run_id<span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">$</span>zeros <span class="ot" style="color: #003B4F;
background-color: null;
font-style: inherit;">&lt;-</span> <span class="cn" style="color: #8f5902;
background-color: null;
font-style: inherit;">NA_integer_</span>; run_id<span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">$</span>port_same <span class="ot" style="color: #003B4F;
background-color: null;
font-style: inherit;">&lt;-</span> <span class="cn" style="color: #8f5902;
background-color: null;
font-style: inherit;">NA</span></span>
<span id="cb12-14">run_id<span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">$</span>gvf <span class="ot" style="color: #003B4F;
background-color: null;
font-style: inherit;">&lt;-</span> <span class="cn" style="color: #8f5902;
background-color: null;
font-style: inherit;">NA_real_</span>; run_id<span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">$</span>first_share <span class="ot" style="color: #003B4F;
background-color: null;
font-style: inherit;">&lt;-</span> <span class="cn" style="color: #8f5902;
background-color: null;
font-style: inherit;">NA_real_</span>; run_id<span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">$</span>first_upper <span class="ot" style="color: #003B4F;
background-color: null;
font-style: inherit;">&lt;-</span> <span class="cn" style="color: #8f5902;
background-color: null;
font-style: inherit;">NA_real_</span></span>
<span id="cb12-15"><span class="cf" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">for</span> (r <span class="cf" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">in</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">seq_len</span>(<span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">nrow</span>(run_id))) {</span>
<span id="cb12-16">  sel <span class="ot" style="color: #003B4F;
background-color: null;
font-style: inherit;">&lt;-</span> runs<span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">$</span>field <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">==</span> run_id<span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">$</span>field[r] <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">&amp;</span> runs<span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">$</span>n <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">==</span> run_id<span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">$</span>n[r] <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">&amp;</span> runs<span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">$</span>shift <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">==</span> run_id<span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">$</span>shift[r]</span>
<span id="cb12-17">  x   <span class="ot" style="color: #003B4F;
background-color: null;
font-style: inherit;">&lt;-</span> grid_1km[[run_id<span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">$</span>field[r]]][<span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">seq_len</span>(run_id<span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">$</span>n[r])] <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">+</span> run_id<span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">$</span>shift[r]</span>
<span id="cb12-18">  smp <span class="ot" style="color: #003B4F;
background-color: null;
font-style: inherit;">&lt;-</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">qgis_sample</span>(x)</span>
<span id="cb12-19">  run_id<span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">$</span>zeros[r]     <span class="ot" style="color: #003B4F;
background-color: null;
font-style: inherit;">&lt;-</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">sum</span>(smp <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">==</span> <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">0</span>)          <span class="co" style="color: #5E5E5E;
background-color: null;
font-style: inherit;"># the richness values are all above zero</span></span>
<span id="cb12-20">  run_id<span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">$</span>port_same[r] <span class="ot" style="color: #003B4F;
background-color: null;
font-style: inherit;">&lt;-</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">identical</span>(<span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">qgis_jenks</span>(smp, <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">5</span>), runs<span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">$</span>upper[sel])</span>
<span id="cb12-21">  run_id<span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">$</span>gvf[r]         <span class="ot" style="color: #003B4F;
background-color: null;
font-style: inherit;">&lt;-</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">gvf</span>(x, <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">qgis_class</span>(x, runs<span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">$</span>lower[sel], runs<span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">$</span>upper[sel]))</span>
<span id="cb12-22">  run_id<span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">$</span>first_share[r] <span class="ot" style="color: #003B4F;
background-color: null;
font-style: inherit;">&lt;-</span> runs<span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">$</span>features[sel][<span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">1</span>] <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">/</span> run_id<span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">$</span>n[r]</span>
<span id="cb12-23">  run_id<span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">$</span>first_upper[r] <span class="ot" style="color: #003B4F;
background-color: null;
font-style: inherit;">&lt;-</span> runs<span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">$</span>upper[sel][<span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">1</span>]</span>
<span id="cb12-24">}</span>
<span id="cb12-25">all_port <span class="ot" style="color: #003B4F;
background-color: null;
font-style: inherit;">&lt;-</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">all</span>(run_id<span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">$</span>port_same); n_runs <span class="ot" style="color: #003B4F;
background-color: null;
font-style: inherit;">&lt;-</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">nrow</span>(run_id)</span>
<span id="cb12-26">rich <span class="ot" style="color: #003B4F;
background-color: null;
font-style: inherit;">&lt;-</span> run_id[run_id<span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">$</span>field <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">==</span> <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"richness"</span> <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">&amp;</span> run_id<span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">$</span>shift <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">==</span> <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">0</span>, ]</span>
<span id="cb12-27">opt_gvf <span class="ot" style="color: #003B4F;
background-color: null;
font-style: inherit;">&lt;-</span> <span class="cf" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">function</span>(x, <span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">k =</span> <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">5</span>) {</span>
<span id="cb12-28">  ci <span class="ot" style="color: #003B4F;
background-color: null;
font-style: inherit;">&lt;-</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">classIntervals</span>(x, k, <span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">style =</span> <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"fisher"</span>, <span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">largeN =</span> <span class="cn" style="color: #8f5902;
background-color: null;
font-style: inherit;">Inf</span>, <span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">warnLargeN =</span> <span class="cn" style="color: #8f5902;
background-color: null;
font-style: inherit;">FALSE</span>)</span>
<span id="cb12-29">  <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">gvf</span>(x, <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">findCols</span>(ci))</span>
<span id="cb12-30">}</span>
<span id="cb12-31">n_check <span class="ot" style="color: #003B4F;
background-color: null;
font-style: inherit;">&lt;-</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">c</span>(<span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">5000</span>, <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">20000</span>, <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">30009</span>)</span>
<span id="cb12-32">gvf_gap <span class="ot" style="color: #003B4F;
background-color: null;
font-style: inherit;">&lt;-</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">sapply</span>(n_check, <span class="cf" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">function</span>(n) <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">opt_gvf</span>(grid_1km<span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">$</span>richness[<span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">1</span><span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">:</span>n]) <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">-</span> rich<span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">$</span>gvf[rich<span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">$</span>n <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">==</span> n])</span></code></pre></div></div>
</div>
<p>For every one of the 27 QGIS runs in <code>qgis-jenks-runs.csv</code>, from 1000 to 60000 cells, the R port applied to this reconstructed sample returns exactly the doubles QGIS wrote: that all of them are identical is TRUE. Up to 30009 cells the sample costs very little on this layer. At 5000, 20000 and 30009 cells the QGIS classes fall short of the best possible fit on all cells by <img src="https://latex.codecogs.com/png.latex?4.5%20%5Ctimes%2010%5E%7B-7%7D">, <img src="https://latex.codecogs.com/png.latex?6.8%20%5Ctimes%2010%5E%7B-6%7D"> and <img src="https://latex.codecogs.com/png.latex?7.8%20%5Ctimes%2010%5E%7B-6%7D"> in goodness of variance fit. This smooth richness surface forgives a sample of 3000 ranks. A layer with a longer or sparser upper tail than this one may fare worse, since a rank sample keeps only a few of its extreme cells; that was not tested here.</p>
</section>
<section id="above-30009-cells-the-sample-holds-zeros" class="level2">
<h2 id="above-30009-cells-the-sample-holds-zeros-h" class="anchored" data-anchor-id="above-30009-cells-the-sample-holds-zeros">Above 30009 cells, the sample holds zeros</h2>
<p>The sample array is sized as the larger of 3000 and one tenth of the number of values, but the loop that fills it counts only to 3000. The comment above the resize says the intention: “sample at least maximumSize values or a 10% sample, whichever is larger”. The fill loop still computes its slot counter as <code>i * (mMaximumSize - 2) / (sorted.size() - 2)</code>, which stays below <code>mMaximumSize - 2</code>, so once a tenth of the layer exceeds 3000, the slots beyond the first 3000 are never written, and a resized <code>QVector&lt;double&gt;</code> holds <code>0.0</code> in every slot it has not been given. Those zeros are then sorted in with the real values and classified as data. With integer division, <code>n / 10</code> first exceeds 3000 at <code>n = 30010</code>, and from there the number of zeros is <code>n / 10 - 3000</code>.</p>
<div class="cell">
<div class="code-copy-outer-scaffold"><div class="sourceCode cell-code" id="cb13" style="background: #f1f3f5;"><pre class="sourceCode r code-with-copy"><code class="sourceCode r"><span id="cb13-1">z_pred <span class="ot" style="color: #003B4F;
background-color: null;
font-style: inherit;">&lt;-</span> <span class="cf" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">function</span>(n) <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">pmax</span>(<span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">0</span>, n <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">%/%</span> <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">10</span> <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">-</span> <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">3000</span>)</span>
<span id="cb13-2">z_ok   <span class="ot" style="color: #003B4F;
background-color: null;
font-style: inherit;">&lt;-</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">all</span>(rich<span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">$</span>zeros <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">==</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">z_pred</span>(rich<span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">$</span>n))</span>
<span id="cb13-3">first_z <span class="ot" style="color: #003B4F;
background-color: null;
font-style: inherit;">&lt;-</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">min</span>(rich<span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">$</span>n[rich<span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">$</span>zeros <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">&gt;</span> <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">0</span>]); last_clean <span class="ot" style="color: #003B4F;
background-color: null;
font-style: inherit;">&lt;-</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">max</span>(rich<span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">$</span>n[rich<span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">$</span>zeros <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">==</span> <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">0</span>])</span>
<span id="cb13-4">b_before <span class="ot" style="color: #003B4F;
background-color: null;
font-style: inherit;">&lt;-</span> runs<span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">$</span>upper[runs<span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">$</span>field <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">==</span> <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"richness"</span> <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">&amp;</span> runs<span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">$</span>n <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">==</span> last_clean <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">&amp;</span> runs<span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">$</span>shift <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">==</span> <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">0</span>][<span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">1</span>]</span>
<span id="cb13-5">b_after  <span class="ot" style="color: #003B4F;
background-color: null;
font-style: inherit;">&lt;-</span> runs<span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">$</span>upper[runs<span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">$</span>field <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">==</span> <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"richness"</span> <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">&amp;</span> runs<span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">$</span>n <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">==</span> first_z <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">&amp;</span> runs<span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">$</span>shift <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">==</span> <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">0</span>][<span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">1</span>]</span>
<span id="cb13-6">smp_z <span class="ot" style="color: #003B4F;
background-color: null;
font-style: inherit;">&lt;-</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">qgis_sample</span>(grid_1km<span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">$</span>richness[<span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">seq_len</span>(first_z)])</span>
<span id="cb13-7">b_nozero <span class="ot" style="color: #003B4F;
background-color: null;
font-style: inherit;">&lt;-</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">qgis_jenks</span>(smp_z[smp_z <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">!=</span> <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">0</span>], <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">5</span>)[<span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">1</span>]         <span class="co" style="color: #5E5E5E;
background-color: null;
font-style: inherit;"># the same sample with its one zero taken out</span></span>
<span id="cb13-8">collapse_n <span class="ot" style="color: #003B4F;
background-color: null;
font-style: inherit;">&lt;-</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">min</span>(rich<span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">$</span>n[rich<span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">$</span>first_share <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">&lt;</span> <span class="fl" style="color: #AD0000;
background-color: null;
font-style: inherit;">0.01</span>]); held_n <span class="ot" style="color: #003B4F;
background-color: null;
font-style: inherit;">&lt;-</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">max</span>(rich<span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">$</span>n[rich<span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">$</span>first_share <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">&gt;=</span> <span class="fl" style="color: #AD0000;
background-color: null;
font-style: inherit;">0.01</span>])</span>
<span id="cb13-9">r60 <span class="ot" style="color: #003B4F;
background-color: null;
font-style: inherit;">&lt;-</span> rich[rich<span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">$</span>n <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">==</span> <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">60000</span>, ]</span>
<span id="cb13-10">q60 <span class="ot" style="color: #003B4F;
background-color: null;
font-style: inherit;">&lt;-</span> runs[runs<span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">$</span>field <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">==</span> <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"richness"</span> <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">&amp;</span> runs<span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">$</span>n <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">==</span> <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">60000</span> <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">&amp;</span> runs<span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">$</span>shift <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">==</span> <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">0</span>, ]</span>
<span id="cb13-11">x60 <span class="ot" style="color: #003B4F;
background-color: null;
font-style: inherit;">&lt;-</span> grid_1km<span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">$</span>richness</span>
<span id="cb13-12">t_fisher <span class="ot" style="color: #003B4F;
background-color: null;
font-style: inherit;">&lt;-</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">system.time</span>(ci_opt <span class="ot" style="color: #003B4F;
background-color: null;
font-style: inherit;">&lt;-</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">classIntervals</span>(x60, <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">5</span>, <span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">style =</span> <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"fisher"</span>, <span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">largeN =</span> <span class="cn" style="color: #8f5902;
background-color: null;
font-style: inherit;">Inf</span>))[[<span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"elapsed"</span>]]</span>
<span id="cb13-13">opt60 <span class="ot" style="color: #003B4F;
background-color: null;
font-style: inherit;">&lt;-</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">gvf</span>(x60, <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">findCols</span>(ci_opt)); opt60_4 <span class="ot" style="color: #003B4F;
background-color: null;
font-style: inherit;">&lt;-</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">opt_gvf</span>(x60, <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">4</span>)</span>
<span id="cb13-14">opt_upper <span class="ot" style="color: #003B4F;
background-color: null;
font-style: inherit;">&lt;-</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">sort</span>(<span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">attr</span>(ci_opt, <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"parameters"</span>)[, <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"max"</span>])</span></code></pre></div></div>
</div>
<p>The count of zeros in the reconstructed sample matches <code>n / 10 - 3000</code> at every grid size: TRUE. The first run with any zero is at 30010 cells, and QGIS’s own output moves there: the first break is 20.7751 at 30009 cells and 20.7453 at 30010, a shift that the port reproduces with its single zero. Without that one zero the port returns 20.7750 at 30010 cells, next to the 20.7751 at 30009. A handful of zeros only nudges the lowest class. By 30500 cells (50 zeros) the classes have reorganised: the first class is now the block of zeros plus the lowest few real cells, and at 30200 cells it had not yet. On the full grid of 60000 cells half of the sample, 3000 of 6000 values, is zeros that are not in the layer. The legend’s first class runs from 4.996 to 8.693 and holds 42 cells, 0.07 per cent of the map, while the remaining four classes share everything else from breaks computed on the 3000 real values.</p>
<div class="cell">
<div class="code-copy-outer-scaffold"><div class="sourceCode cell-code" id="cb14" style="background: #f1f3f5;"><pre class="sourceCode r code-with-copy"><code class="sourceCode r"><span id="cb14-1">smp60 <span class="ot" style="color: #003B4F;
background-color: null;
font-style: inherit;">&lt;-</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">sort</span>(<span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">qgis_sample</span>(x60))</span>
<span id="cb14-2"><span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">ggplot</span>(<span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">data.frame</span>(<span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">pos =</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">seq_along</span>(smp60), <span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">val =</span> smp60,</span>
<span id="cb14-3">                  <span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">kind =</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">ifelse</span>(<span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">seq_along</span>(smp60) <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">&lt;=</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">z_pred</span>(<span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">60000</span>), <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"padding zero"</span>, <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"sampled value"</span>)),</span>
<span id="cb14-4">       <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">aes</span>(pos, val, <span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">colour =</span> kind)) <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">+</span></span>
<span id="cb14-5">  <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">geom_hline</span>(<span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">yintercept =</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">min</span>(x60), <span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">linetype =</span> <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"dashed"</span>, <span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">colour =</span> te_body, <span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">linewidth =</span> <span class="fl" style="color: #AD0000;
background-color: null;
font-style: inherit;">0.4</span>) <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">+</span></span>
<span id="cb14-6">  <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">geom_point</span>(<span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">size =</span> <span class="fl" style="color: #AD0000;
background-color: null;
font-style: inherit;">0.4</span>) <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">+</span></span>
<span id="cb14-7">  <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">scale_x_continuous</span>(<span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">breaks =</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">c</span>(<span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">1</span>, <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">1500</span>, <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">3000</span>, <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">4500</span>, <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">6000</span>)) <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">+</span></span>
<span id="cb14-8">  <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">scale_colour_manual</span>(<span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">values =</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">c</span>(<span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"padding zero"</span> <span class="ot" style="color: #003B4F;
background-color: null;
font-style: inherit;">=</span> te_rust, <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"sampled value"</span> <span class="ot" style="color: #003B4F;
background-color: null;
font-style: inherit;">=</span> te_forest), <span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">name =</span> <span class="cn" style="color: #8f5902;
background-color: null;
font-style: inherit;">NULL</span>) <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">+</span></span>
<span id="cb14-9">  <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">labs</span>(<span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">x =</span> <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"position in the sorted sample"</span>, <span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">y =</span> <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"value classified (richness)"</span>,</span>
<span id="cb14-10">       <span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">title =</span> <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"What Natural Breaks classifies at 60000 cells"</span>,</span>
<span id="cb14-11">       <span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">subtitle =</span> <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"dashed line: the smallest richness in the layer"</span>) <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">+</span></span>
<span id="cb14-12">  <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">theme_datasheet</span>() <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">+</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">theme</span>(<span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">legend.position =</span> <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"bottom"</span>) <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">+</span></span>
<span id="cb14-13">  <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">guides</span>(<span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">colour =</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">guide_legend</span>(<span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">override.aes =</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">list</span>(<span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">size =</span> <span class="fl" style="color: #AD0000;
background-color: null;
font-style: inherit;">2.5</span>)))</span></code></pre></div></div>
<div class="cell-output-display">
<div id="fig-sample" class="quarto-float quarto-figure quarto-figure-center anchored" alt="A scatter of 6000 points on warm off-white paper, value classified in richness from 0 to 100 against position in the sorted sample from 1 to 6000. From position 1 to 3000 the points form a flat rust line at zero. From position 3001 a dark green curve starts on a dashed horizontal line at about 5, rises quickly to about 12, climbs slowly through the low twenties to about 30 near position 5500, then turns steeply upward to about 97 at position 6000. A legend at the bottom names rust as padding zero and green as sampled value.">
<figure class="quarto-float quarto-float-fig figure">
<div aria-describedby="fig-sample-caption-0ceaefa1-69ba-4598-a22c-09a6ac19f8ca">
<img src="https://tidyecology.com/posts/natural-breaks-in-qgis-and-r/index_files/figure-html/fig-sample-1.png" class="img-fluid figure-img" alt="A scatter of 6000 points on warm off-white paper, value classified in richness from 0 to 100 against position in the sorted sample from 1 to 6000. From position 1 to 3000 the points form a flat rust line at zero. From position 3001 a dark green curve starts on a dashed horizontal line at about 5, rises quickly to about 12, climbs slowly through the low twenties to about 30 near position 5500, then turns steeply upward to about 97 at position 6000. A legend at the bottom names rust as padding zero and green as sampled value." width="720">
</div>
<figcaption class="quarto-float-caption-bottom quarto-float-caption quarto-float-fig" id="fig-sample-caption-0ceaefa1-69ba-4598-a22c-09a6ac19f8ca">
Figure&nbsp;1: The sorted values QGIS classifies for Natural Breaks on the full grid of 60000 cells. The first 3000 are zeros that the fill loop never overwrites; the next 3000 are the systematic sample of the real values.
</figcaption>
</figure>
</div>
</div>
</div>
<p>The goodness of variance fit tells you what the wasted class costs. On all 60000 cells the QGIS classes reach 0.8942. The best five classes reach 0.9276, and the best four reach 0.8936. The QGIS fit sits a little above the best four classes and far below the best five: on this layer, and on the shifted copies below, Natural Breaks in QGIS gives you, in effect, four classes and a legend entry.</p>
<div class="cell">
<div class="code-copy-outer-scaffold"><div class="sourceCode cell-code" id="cb15" style="background: #f1f3f5;"><pre class="sourceCode r code-with-copy"><code class="sourceCode r"><span id="cb15-1">brk_long <span class="ot" style="color: #003B4F;
background-color: null;
font-style: inherit;">&lt;-</span> runs[runs<span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">$</span>field <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">==</span> <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"richness"</span> <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">&amp;</span> runs<span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">$</span>shift <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">==</span> <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">0</span> <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">&amp;</span> runs<span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">$</span>klass <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">&lt;</span> <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">5</span>, ]</span>
<span id="cb15-2">brk_long<span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">$</span>break_no <span class="ot" style="color: #003B4F;
background-color: null;
font-style: inherit;">&lt;-</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">factor</span>(<span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">paste</span>(<span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"break"</span>, brk_long<span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">$</span>klass))</span>
<span id="cb15-3"><span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">ggplot</span>(brk_long, <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">aes</span>(n, upper, <span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">colour =</span> break_no)) <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">+</span></span>
<span id="cb15-4">  <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">geom_hline</span>(<span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">yintercept =</span> opt_upper[<span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">1</span><span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">:</span><span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">4</span>], <span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">colour =</span> <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"#b9b8a6"</span>, <span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">linewidth =</span> <span class="fl" style="color: #AD0000;
background-color: null;
font-style: inherit;">0.7</span>) <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">+</span></span>
<span id="cb15-5">  <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">geom_vline</span>(<span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">xintercept =</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">c</span>(<span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">3000</span>, <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">30010</span>), <span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">linetype =</span> <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"dashed"</span>, <span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">colour =</span> te_body, <span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">linewidth =</span> <span class="fl" style="color: #AD0000;
background-color: null;
font-style: inherit;">0.4</span>) <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">+</span></span>
<span id="cb15-6">  <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">geom_line</span>(<span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">linewidth =</span> <span class="fl" style="color: #AD0000;
background-color: null;
font-style: inherit;">0.7</span>) <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">+</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">geom_point</span>(<span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">size =</span> <span class="fl" style="color: #AD0000;
background-color: null;
font-style: inherit;">1.8</span>) <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">+</span></span>
<span id="cb15-7">  <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">scale_x_log10</span>(<span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">breaks =</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">c</span>(<span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">1000</span>, <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">3000</span>, <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">10000</span>, <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">30010</span>, <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">60000</span>),</span>
<span id="cb15-8">                <span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">labels =</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">c</span>(<span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"1000"</span>, <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"3000"</span>, <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"10000"</span>, <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"30010"</span>, <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"60000"</span>)) <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">+</span></span>
<span id="cb15-9">  <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">scale_colour_manual</span>(<span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">values =</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">c</span>(te_forest, te_gold, te_rust, <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"#7f8c84"</span>), <span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">name =</span> <span class="cn" style="color: #8f5902;
background-color: null;
font-style: inherit;">NULL</span>) <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">+</span></span>
<span id="cb15-10">  <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">labs</span>(<span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">x =</span> <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"cells classified (log scale)"</span>, <span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">y =</span> <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"upper bound of class (richness)"</span>,</span>
<span id="cb15-11">       <span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">title =</span> <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"Stable until the zeros arrive"</span>,</span>
<span id="cb15-12">       <span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">subtitle =</span> <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"QGIS Natural Breaks, first n cells of the 1 km grid"</span>) <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">+</span></span>
<span id="cb15-13">  <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">theme_datasheet</span>() <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">+</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">theme</span>(<span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">legend.position =</span> <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"bottom"</span>)</span></code></pre></div></div>
<div class="cell-output-display">
<div id="fig-breaks" class="quarto-float quarto-figure quarto-figure-center anchored" alt="A line chart of the four QGIS break positions against cells classified on a logarithmic axis from 1000 to 60000, with dashed vertical lines at 3000 and 30010 and pale horizontal reference lines near 21, 29, 42 and 59 for the optimal breaks. The four lines, dark green, gold, rust and grey from bottom to top, run close to the reference lines from 1000 cells up to the 30010 line, the top one wandering between about 57 and 61. Just right of 30010 all four drop: dark green from about 20 to about 9, gold from about 29 to 22, rust from about 41 to 33 and grey from about 59 to 51, and they stay there out to 60000 cells.">
<figure class="quarto-float quarto-float-fig figure">
<div aria-describedby="fig-breaks-caption-0ceaefa1-69ba-4598-a22c-09a6ac19f8ca">
<img src="https://tidyecology.com/posts/natural-breaks-in-qgis-and-r/index_files/figure-html/fig-breaks-1.png" class="img-fluid figure-img" alt="A line chart of the four QGIS break positions against cells classified on a logarithmic axis from 1000 to 60000, with dashed vertical lines at 3000 and 30010 and pale horizontal reference lines near 21, 29, 42 and 59 for the optimal breaks. The four lines, dark green, gold, rust and grey from bottom to top, run close to the reference lines from 1000 cells up to the 30010 line, the top one wandering between about 57 and 61. Just right of 30010 all four drop: dark green from about 20 to about 9, gold from about 29 to 22, rust from about 41 to 33 and grey from about 59 to 51, and they stay there out to 60000 cells." width="720">
</div>
<figcaption class="quarto-float-caption-bottom quarto-float-caption quarto-float-fig" id="fig-breaks-caption-0ceaefa1-69ba-4598-a22c-09a6ac19f8ca">
Figure&nbsp;2: The four interior breaks QGIS returns for Natural Breaks, against the number of cells classified (log scale). Dashed vertical lines: 3000, where sampling begins, and 30010, where zeros enter the sample. Thin horizontal lines: the optimal breaks on all 60000 cells.
</figcaption>
</figure>
</div>
</div>
</div>
<section id="how-far-the-data-sit-from-zero-decides-what-the-legend-shows" class="level3">
<h3 id="how-far-the-data-sit-from-zero-decides-what-the-legend-shows-h" class="anchored" data-anchor-id="how-far-the-data-sit-from-zero-decides-what-the-legend-shows">How far the data sit from zero decides what the legend shows</h3>
<p>The zeros are always at zero, and what they do depends on where the data are. On this grid the smallest richness is close enough to zero that the zeros take a few real cells with them into the first class. The script also classified the full grid with a constant added to every cell, as if the same map came from a richer region.</p>
<div class="cell">
<div class="code-copy-outer-scaffold"><div class="sourceCode cell-code" id="cb16" style="background: #f1f3f5;"><pre class="sourceCode r code-with-copy"><code class="sourceCode r"><span id="cb16-1">sh <span class="ot" style="color: #003B4F;
background-color: null;
font-style: inherit;">&lt;-</span> run_id[run_id<span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">$</span>field <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">==</span> <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"richness"</span> <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">&amp;</span> run_id<span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">$</span>n <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">==</span> <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">60000</span>, ]</span>
<span id="cb16-2">sh<span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">$</span>min_value <span class="ot" style="color: #003B4F;
background-color: null;
font-style: inherit;">&lt;-</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">min</span>(x60) <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">+</span> sh<span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">$</span>shift</span>
<span id="cb16-3">q_sh <span class="ot" style="color: #003B4F;
background-color: null;
font-style: inherit;">&lt;-</span> runs[runs<span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">$</span>field <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">==</span> <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"richness"</span> <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">&amp;</span> runs<span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">$</span>n <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">==</span> <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">60000</span>, ]</span>
<span id="cb16-4">sh<span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">$</span>first_lower <span class="ot" style="color: #003B4F;
background-color: null;
font-style: inherit;">&lt;-</span> q_sh<span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">$</span>lower[q_sh<span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">$</span>klass <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">==</span> <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">1</span>]</span>
<span id="cb16-5">sh<span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">$</span>first_count <span class="ot" style="color: #003B4F;
background-color: null;
font-style: inherit;">&lt;-</span> q_sh<span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">$</span>features[q_sh<span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">$</span>klass <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">==</span> <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">1</span>]</span>
<span id="cb16-6">knitr<span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">::</span><span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">kable</span>(sh[, <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">c</span>(<span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"shift"</span>, <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"min_value"</span>, <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"first_lower"</span>, <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"first_upper"</span>, <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"first_count"</span>, <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"gvf"</span>)],</span>
<span id="cb16-7">             <span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">row.names =</span> <span class="cn" style="color: #8f5902;
background-color: null;
font-style: inherit;">FALSE</span>, <span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">digits =</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">c</span>(<span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">1</span>, <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">3</span>, <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">3</span>, <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">3</span>, <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">0</span>, <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">4</span>),</span>
<span id="cb16-8">             <span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">col.names =</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">c</span>(<span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"added"</span>, <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"layer minimum"</span>, <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"class 1 from"</span>, <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"class 1 to"</span>,</span>
<span id="cb16-9">                           <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"cells in class 1"</span>, <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"GVF"</span>),</span>
<span id="cb16-10">             <span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">caption =</span> <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"QGIS Natural Breaks on all 60000 cells, with a constant added."</span>)</span></code></pre></div></div>
<div class="cell-output-display">
<table class="caption-top table table-sm table-striped small">
<caption>QGIS Natural Breaks on all 60000 cells, with a constant added.</caption>
<colgroup>
<col style="width: 8%">
<col style="width: 20%">
<col style="width: 19%">
<col style="width: 16%">
<col style="width: 25%">
<col style="width: 10%">
</colgroup>
<thead>
<tr class="header">
<th style="text-align: right;">added</th>
<th style="text-align: right;">layer minimum</th>
<th style="text-align: right;">class 1 from</th>
<th style="text-align: right;">class 1 to</th>
<th style="text-align: right;">cells in class 1</th>
<th style="text-align: right;">GVF</th>
</tr>
</thead>
<tbody>
<tr class="odd">
<td style="text-align: right;">0.0</td>
<td style="text-align: right;">4.996</td>
<td style="text-align: right;">4.996</td>
<td style="text-align: right;">8.693</td>
<td style="text-align: right;">42</td>
<td style="text-align: right;">0.8942</td>
</tr>
<tr class="even">
<td style="text-align: right;">2.5</td>
<td style="text-align: right;">7.496</td>
<td style="text-align: right;">7.496</td>
<td style="text-align: right;">8.005</td>
<td style="text-align: right;">2</td>
<td style="text-align: right;">0.8936</td>
</tr>
<tr class="odd">
<td style="text-align: right;">5.0</td>
<td style="text-align: right;">9.996</td>
<td style="text-align: right;">9.996</td>
<td style="text-align: right;">10.505</td>
<td style="text-align: right;">2</td>
<td style="text-align: right;">0.8936</td>
</tr>
<tr class="even">
<td style="text-align: right;">10.0</td>
<td style="text-align: right;">14.996</td>
<td style="text-align: right;">14.996</td>
<td style="text-align: right;">0.000</td>
<td style="text-align: right;">0</td>
<td style="text-align: right;">0.8936</td>
</tr>
<tr class="odd">
<td style="text-align: right;">20.0</td>
<td style="text-align: right;">24.996</td>
<td style="text-align: right;">24.996</td>
<td style="text-align: right;">0.000</td>
<td style="text-align: right;">0</td>
<td style="text-align: right;">0.8936</td>
</tr>
<tr class="even">
<td style="text-align: right;">40.0</td>
<td style="text-align: right;">44.996</td>
<td style="text-align: right;">44.996</td>
<td style="text-align: right;">0.000</td>
<td style="text-align: right;">0</td>
<td style="text-align: right;">0.8936</td>
</tr>
</tbody>
</table>
</div>
<div class="code-copy-outer-scaffold"><div class="sourceCode cell-code" id="cb17" style="background: #f1f3f5;"><pre class="sourceCode r code-with-copy"><code class="sourceCode r"><span id="cb17-1">inv <span class="ot" style="color: #003B4F;
background-color: null;
font-style: inherit;">&lt;-</span> sh[sh<span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">$</span>first_upper <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">&lt;</span> sh<span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">$</span>first_lower, ]</span></code></pre></div></div>
</div>
<p>With 10.0 or more added, the first class becomes the pure form of the defect: it runs from the layer minimum, 14.996, down to 0.0, an upper bound below its lower bound, and no cell can fall in it. QGIS puts that line in the legend with a colour and draws four colours on the map. The second class then starts at zero, so it silently takes in everything from the layer minimum up to its own upper bound. On a layer that crosses zero, such as the change in richness between two periods, the zeros land inside the range instead.</p>
<div class="cell">
<div class="code-copy-outer-scaffold"><div class="sourceCode cell-code" id="cb18" style="background: #f1f3f5;"><pre class="sourceCode r code-with-copy"><code class="sourceCode r"><span id="cb18-1">xc <span class="ot" style="color: #003B4F;
background-color: null;
font-style: inherit;">&lt;-</span> grid_1km<span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">$</span>change</span>
<span id="cb18-2">qc <span class="ot" style="color: #003B4F;
background-color: null;
font-style: inherit;">&lt;-</span> runs[runs<span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">$</span>field <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">==</span> <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"change"</span> <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">&amp;</span> runs<span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">$</span>n <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">==</span> <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">60000</span>, ]</span>
<span id="cb18-3">gvf_c  <span class="ot" style="color: #003B4F;
background-color: null;
font-style: inherit;">&lt;-</span> run_id<span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">$</span>gvf[run_id<span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">$</span>field <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">==</span> <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"change"</span> <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">&amp;</span> run_id<span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">$</span>n <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">==</span> <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">60000</span>]</span>
<span id="cb18-4">ci_c   <span class="ot" style="color: #003B4F;
background-color: null;
font-style: inherit;">&lt;-</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">classIntervals</span>(xc, <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">5</span>, <span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">style =</span> <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"fisher"</span>, <span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">largeN =</span> <span class="cn" style="color: #8f5902;
background-color: null;
font-style: inherit;">Inf</span>)</span>
<span id="cb18-5">gvf_co <span class="ot" style="color: #003B4F;
background-color: null;
font-style: inherit;">&lt;-</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">gvf</span>(xc, <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">findCols</span>(ci_c)); up_co <span class="ot" style="color: #003B4F;
background-color: null;
font-style: inherit;">&lt;-</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">sort</span>(<span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">attr</span>(ci_c, <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"parameters"</span>)[, <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"max"</span>])</span>
<span id="cb18-6">shift_c <span class="ot" style="color: #003B4F;
background-color: null;
font-style: inherit;">&lt;-</span> qc<span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">$</span>upper[<span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">1</span><span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">:</span><span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">4</span>] <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">-</span> up_co[<span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">1</span><span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">:</span><span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">4</span>]</span>
<span id="cb18-7">neg_share <span class="ot" style="color: #003B4F;
background-color: null;
font-style: inherit;">&lt;-</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">mean</span>(xc <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">&lt;</span> <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">0</span>)</span>
<span id="cb18-8">smp_c <span class="ot" style="color: #003B4F;
background-color: null;
font-style: inherit;">&lt;-</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">qgis_sample</span>(xc); real_c <span class="ot" style="color: #003B4F;
background-color: null;
font-style: inherit;">&lt;-</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">head</span>(smp_c, <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">3000</span>)    <span class="co" style="color: #5E5E5E;
background-color: null;
font-style: inherit;"># the 3000 slots the fill loop writes</span></span>
<span id="cb18-9">dev_c <span class="ot" style="color: #003B4F;
background-color: null;
font-style: inherit;">&lt;-</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">rbind</span>(<span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">qgis_jenks</span>(smp_c, <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">5</span>), <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">qgis_jenks</span>(smp_c, <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">5</span>, <span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">fix =</span> <span class="cn" style="color: #8f5902;
background-color: null;
font-style: inherit;">TRUE</span>),</span>
<span id="cb18-10">               <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">qgis_jenks</span>(real_c, <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">5</span>), <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">qgis_jenks</span>(real_c, <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">5</span>, <span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">fix =</span> <span class="cn" style="color: #8f5902;
background-color: null;
font-style: inherit;">TRUE</span>))[, <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">1</span><span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">:</span><span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">4</span>] <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">-</span></span>
<span id="cb18-11">  <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">matrix</span>(up_co[<span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">1</span><span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">:</span><span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">4</span>], <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">4</span>, <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">4</span>, <span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">byrow =</span> <span class="cn" style="color: #8f5902;
background-color: null;
font-style: inherit;">TRUE</span>)</span>
<span id="cb18-12">knitr<span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">::</span><span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">kable</span>(<span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">data.frame</span>(<span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">sample =</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">c</span>(<span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"with the zeros"</span>, <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"with the zeros"</span>, <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"without the zeros"</span>,</span>
<span id="cb18-13">                                   <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"without the zeros"</span>),</span>
<span id="cb18-14">                        <span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">walk_back =</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">c</span>(<span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"QGIS"</span>, <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"extra step removed"</span>, <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"QGIS"</span>, <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"extra step removed"</span>),</span>
<span id="cb18-15">                        dev_c), <span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">digits =</span> <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">3</span>, <span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">row.names =</span> <span class="cn" style="color: #8f5902;
background-color: null;
font-style: inherit;">FALSE</span>,</span>
<span id="cb18-16">             <span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">col.names =</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">c</span>(<span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"sample"</span>, <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"walk back"</span>, <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"break 1"</span>, <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"break 2"</span>, <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"break 3"</span>, <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"break 4"</span>),</span>
<span id="cb18-17">             <span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">caption =</span> <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"Change layer, 60000 cells: each interior break minus the optimal break on all cells."</span>)</span></code></pre></div></div>
<div class="cell-output-display">
<table class="caption-top table table-sm table-striped small">
<caption>Change layer, 60000 cells: each interior break minus the optimal break on all cells.</caption>
<colgroup>
<col style="width: 26%">
<col style="width: 27%">
<col style="width: 11%">
<col style="width: 11%">
<col style="width: 11%">
<col style="width: 11%">
</colgroup>
<thead>
<tr class="header">
<th style="text-align: left;">sample</th>
<th style="text-align: left;">walk back</th>
<th style="text-align: right;">break 1</th>
<th style="text-align: right;">break 2</th>
<th style="text-align: right;">break 3</th>
<th style="text-align: right;">break 4</th>
</tr>
</thead>
<tbody>
<tr class="odd">
<td style="text-align: left;">with the zeros</td>
<td style="text-align: left;">QGIS</td>
<td style="text-align: right;">0.065</td>
<td style="text-align: right;">0.184</td>
<td style="text-align: right;">0.196</td>
<td style="text-align: right;">0.110</td>
</tr>
<tr class="even">
<td style="text-align: left;">with the zeros</td>
<td style="text-align: left;">extra step removed</td>
<td style="text-align: right;">0.076</td>
<td style="text-align: right;">0.188</td>
<td style="text-align: right;">0.196</td>
<td style="text-align: right;">0.110</td>
</tr>
<tr class="odd">
<td style="text-align: left;">without the zeros</td>
<td style="text-align: left;">QGIS</td>
<td style="text-align: right;">-0.040</td>
<td style="text-align: right;">-0.016</td>
<td style="text-align: right;">-0.008</td>
<td style="text-align: right;">0.005</td>
</tr>
<tr class="even">
<td style="text-align: left;">without the zeros</td>
<td style="text-align: left;">extra step removed</td>
<td style="text-align: right;">-0.032</td>
<td style="text-align: right;">-0.016</td>
<td style="text-align: right;">-0.002</td>
<td style="text-align: right;">0.005</td>
</tr>
</tbody>
</table>
</div>
</div>
<p>51 per cent of the change values are losses, and the middle class straddles zero in both classifications: QGIS puts its breaks at -6.5249, -2.1683, 1.9776, 6.0598, the optimum on all cells at -6.5903, -2.3522, 1.7817, 5.9500. Each QGIS interior break lies between 0.065 and 0.196 above the optimal one. The table takes that shift apart by running the port on the same sample with and without its zeros, with and without the extra step. Almost all of it comes from the zeros. Without them, and with the QGIS walk back kept, every break is within 0.040 of the optimum; with the zeros kept and the extra step removed, the breaks still lie between 0.076 and 0.196 above it. On a spread this wide the fit hardly changes: the goodness of variance fit is 0.94116 against 0.94124. A layer with a narrower spread around zero, or with a real spike of zeros such as a count of individuals, is where padding inside the range would matter more, and it is not measured here.</p>
<p>The same fill loop is in every branch checked on 2026-09-25: 3.20, 3.22, 3.28, 3.34, 3.40, 3.44 and master. Up to 3.18 every slot after the first two, the extra ones included, was filled with a random draw, so there were no zeros, but the classes changed at every click (GitHub issue 31723 reported exactly that); the change to a systematic sample removed the randomness and left the extra slots empty. The Symbology dialog reaches this function directly. <strong>Classify</strong> in the Graduated widget (<code>qgsgraduatedsymbolrendererwidget.cpp</code>) calls the renderer’s <code>updateClasses()</code>, which calls the method’s <code>classes()</code> on the whole layer, which calls <code>calculateBreaks()</code> in <code>qgsclassificationjenks.cpp</code>; the script above goes through the same <code>updateClasses()</code> call. The dialog does have a warning for Natural Breaks on more than 50000 features, but it only appears when the method reports a complexity above 1, and PyQGIS reports 1 for <code>QgsClassificationJenks</code>, so it never appears. We searched the QGIS issue trackers (GitHub and the older Redmine) and found no report of the padding zeros. For the backtracking step there is a possible one: issue 28299 (QGIS 3.4, opened in 2018 and still open) reports a Natural Breaks first class holding a single value and the other classes wrong, which is what the extra step does to the seven values above, and the same two lines were already in the 3.4 code. The issue gives no diagnosis, and we could not download its data to run them again, so the match is in the symptom only. We reported both defects to the QGIS project on 25 September 2026 as <a href="https://github.com/qgis/QGIS/issues/67546">issue 67546</a>, together with a third one in the same function: when a layer has no more features than classes, the function returns the values in feature order, unsorted, so the legend shows overlapping and inverted ranges.</p>
<div class="cell">
<div class="code-copy-outer-scaffold"><div class="sourceCode cell-code" id="cb19" style="background: #f1f3f5;"><pre class="sourceCode r code-with-copy"><code class="sourceCode r"><span id="cb19-1">cl_opt <span class="ot" style="color: #003B4F;
background-color: null;
font-style: inherit;">&lt;-</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">qgis_class</span>(x60, <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">c</span>(<span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">min</span>(x60), <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">head</span>(opt_upper, <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">-</span><span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">1</span>)), opt_upper)</span>
<span id="cb19-2">cl_q60 <span class="ot" style="color: #003B4F;
background-color: null;
font-style: inherit;">&lt;-</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">qgis_class</span>(x60, q60<span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">$</span>lower, q60<span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">$</span>upper)</span>
<span id="cb19-3">class_tab <span class="ot" style="color: #003B4F;
background-color: null;
font-style: inherit;">&lt;-</span> <span class="cf" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">function</span>(lower, upper, cl)</span>
<span id="cb19-4">  <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">data.frame</span>(<span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">range =</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">sprintf</span>(<span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"%.3f to %.3f"</span>, lower, upper), <span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">cells =</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">tabulate</span>(cl, <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">5</span>))</span>
<span id="cb19-5">opt_lower <span class="ot" style="color: #003B4F;
background-color: null;
font-style: inherit;">&lt;-</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">c</span>(<span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">min</span>(x60), <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">head</span>(opt_upper, <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">-</span><span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">1</span>))</span>
<span id="cb19-6">leg_opt <span class="ot" style="color: #003B4F;
background-color: null;
font-style: inherit;">&lt;-</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">class_tab</span>(opt_lower, opt_upper, cl_opt); leg_q <span class="ot" style="color: #003B4F;
background-color: null;
font-style: inherit;">&lt;-</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">class_tab</span>(q60<span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">$</span>lower, q60<span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">$</span>upper, cl_q60)</span>
<span id="cb19-7">knitr<span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">::</span><span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">kable</span>(<span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">data.frame</span>(<span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">class =</span> <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">1</span><span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">:</span><span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">5</span>, leg_opt, leg_q), <span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">row.names =</span> <span class="cn" style="color: #8f5902;
background-color: null;
font-style: inherit;">FALSE</span>,</span>
<span id="cb19-8">             <span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">col.names =</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">c</span>(<span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"class"</span>, <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"optimal, all cells (R)"</span>, <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"cells"</span>, <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"Natural Breaks (QGIS)"</span>, <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"cells"</span>),</span>
<span id="cb19-9">             <span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">caption =</span> <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"The two legends for the full grid, with the number of cells drawn in each class."</span>)</span></code></pre></div></div>
<div class="cell-output-display">
<table class="caption-top table table-sm table-striped small">
<caption>The two legends for the full grid, with the number of cells drawn in each class.</caption>
<thead>
<tr class="header">
<th style="text-align: right;">class</th>
<th style="text-align: left;">optimal, all cells (R)</th>
<th style="text-align: right;">cells</th>
<th style="text-align: left;">Natural Breaks (QGIS)</th>
<th style="text-align: right;">cells</th>
</tr>
</thead>
<tbody>
<tr class="odd">
<td style="text-align: right;">1</td>
<td style="text-align: left;">4.996 to 20.791</td>
<td style="text-align: right;">23060</td>
<td style="text-align: left;">4.996 to 8.693</td>
<td style="text-align: right;">42</td>
</tr>
<tr class="even">
<td style="text-align: right;">2</td>
<td style="text-align: left;">20.791 to 28.995</td>
<td style="text-align: right;">25133</td>
<td style="text-align: left;">8.693 to 21.896</td>
<td style="text-align: right;">28037</td>
</tr>
<tr class="odd">
<td style="text-align: right;">3</td>
<td style="text-align: left;">28.995 to 41.590</td>
<td style="text-align: right;">6714</td>
<td style="text-align: left;">21.896 to 33.127</td>
<td style="text-align: right;">23375</td>
</tr>
<tr class="even">
<td style="text-align: right;">4</td>
<td style="text-align: left;">41.590 to 59.212</td>
<td style="text-align: right;">3814</td>
<td style="text-align: left;">33.127 to 51.341</td>
<td style="text-align: right;">5904</td>
</tr>
<tr class="odd">
<td style="text-align: right;">5</td>
<td style="text-align: left;">59.212 to 97.005</td>
<td style="text-align: right;">1279</td>
<td style="text-align: left;">51.341 to 97.005</td>
<td style="text-align: right;">2642</td>
</tr>
</tbody>
</table>
</div>
</div>
<div class="cell">
<div class="code-copy-outer-scaffold"><div class="sourceCode cell-code" id="cb20" style="background: #f1f3f5;"><pre class="sourceCode r code-with-copy"><code class="sourceCode r"><span id="cb20-1">ramp <span class="ot" style="color: #003B4F;
background-color: null;
font-style: inherit;">&lt;-</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">c</span>(<span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"1"</span> <span class="ot" style="color: #003B4F;
background-color: null;
font-style: inherit;">=</span> <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"#efe7c2"</span>, <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"2"</span> <span class="ot" style="color: #003B4F;
background-color: null;
font-style: inherit;">=</span> <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"#a9c08a"</span>, <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"3"</span> <span class="ot" style="color: #003B4F;
background-color: null;
font-style: inherit;">=</span> <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"#5d8a5e"</span>, <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"4"</span> <span class="ot" style="color: #003B4F;
background-color: null;
font-style: inherit;">=</span> te_forest, <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"5"</span> <span class="ot" style="color: #003B4F;
background-color: null;
font-style: inherit;">=</span> te_ink)</span>
<span id="cb20-2">maps <span class="ot" style="color: #003B4F;
background-color: null;
font-style: inherit;">&lt;-</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">rbind</span>(<span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">data.frame</span>(grid_1km[, <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">c</span>(<span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"col"</span>, <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"row"</span>)], <span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">how =</span> <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"optimal breaks, all cells (R)"</span>,</span>
<span id="cb20-3">                         <span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">cls =</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">factor</span>(cl_opt, <span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">levels =</span> <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">1</span><span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">:</span><span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">5</span>)),</span>
<span id="cb20-4">              <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">data.frame</span>(grid_1km[, <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">c</span>(<span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"col"</span>, <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"row"</span>)], <span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">how =</span> <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"Natural Breaks (QGIS)"</span>,</span>
<span id="cb20-5">                         <span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">cls =</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">factor</span>(cl_q60, <span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">levels =</span> <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">1</span><span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">:</span><span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">5</span>)))</span>
<span id="cb20-6">maps<span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">$</span>how <span class="ot" style="color: #003B4F;
background-color: null;
font-style: inherit;">&lt;-</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">factor</span>(maps<span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">$</span>how, <span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">levels =</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">unique</span>(maps<span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">$</span>how))</span>
<span id="cb20-7"><span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">ggplot</span>(maps, <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">aes</span>(col, row, <span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">fill =</span> cls)) <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">+</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">geom_raster</span>() <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">+</span></span>
<span id="cb20-8">  <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">facet_wrap</span>(<span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">~</span> how, <span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">ncol =</span> <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">2</span>) <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">+</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">coord_fixed</span>(<span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">expand =</span> <span class="cn" style="color: #8f5902;
background-color: null;
font-style: inherit;">FALSE</span>) <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">+</span></span>
<span id="cb20-9">  <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">scale_fill_manual</span>(<span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">values =</span> ramp, <span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">drop =</span> <span class="cn" style="color: #8f5902;
background-color: null;
font-style: inherit;">FALSE</span>, <span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">name =</span> <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"class"</span>) <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">+</span></span>
<span id="cb20-10">  <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">labs</span>(<span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">x =</span> <span class="cn" style="color: #8f5902;
background-color: null;
font-style: inherit;">NULL</span>, <span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">y =</span> <span class="cn" style="color: #8f5902;
background-color: null;
font-style: inherit;">NULL</span>) <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">+</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">theme_datasheet</span>() <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">+</span></span>
<span id="cb20-11">  <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">theme</span>(<span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">axis.text =</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">element_blank</span>(), <span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">panel.grid.major =</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">element_blank</span>(),</span>
<span id="cb20-12">        <span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">strip.text =</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">element_text</span>(<span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">colour =</span> te_ink, <span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">face =</span> <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"bold"</span>, <span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">size =</span> <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">11</span>),</span>
<span id="cb20-13">        <span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">legend.position =</span> <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"bottom"</span>)</span></code></pre></div></div>
<div class="cell-output-display">
<div id="fig-maps" class="quarto-float quarto-figure quarto-figure-center anchored" alt="Two maps of the same 300 by 200 cell grid side by side, each coloured with one five step ramp from pale cream for class 1 through light and mid green to dark green and near black for class 5, with a shared class legend below. Three hotspots, a large one upper left, a small one upper right and a broad one lower centre, show as dark cores inside rings. In the left map, optimal breaks, the background is a speckled mix of cream and light green. In the right map, QGIS Natural Breaks, cream is absent: the background is a speckled mix of light and mid green, and the rings around each hotspot are wider and darker.">
<figure class="quarto-float quarto-float-fig figure">
<div aria-describedby="fig-maps-caption-0ceaefa1-69ba-4598-a22c-09a6ac19f8ca">
<img src="https://tidyecology.com/posts/natural-breaks-in-qgis-and-r/index_files/figure-html/fig-maps-1.png" class="img-fluid figure-img" alt="Two maps of the same 300 by 200 cell grid side by side, each coloured with one five step ramp from pale cream for class 1 through light and mid green to dark green and near black for class 5, with a shared class legend below. Three hotspots, a large one upper left, a small one upper right and a broad one lower centre, show as dark cores inside rings. In the left map, optimal breaks, the background is a speckled mix of cream and light green. In the right map, QGIS Natural Breaks, cream is absent: the background is a speckled mix of light and mid green, and the rings around each hotspot are wider and darker." width="720">
</div>
<figcaption class="quarto-float-caption-bottom quarto-float-caption quarto-float-fig" id="fig-maps-caption-0ceaefa1-69ba-4598-a22c-09a6ac19f8ca">
Figure&nbsp;3: The full one kilometre grid classed twice with the same five colour ramp: optimal breaks computed in R on all 60000 cells, and QGIS Natural Breaks. The class ranges are in the table above.
</figcaption>
</figure>
</div>
</div>
</div>
<p>On the map the missing class is easy to miss. The palest colour is still in the legend, attached to 42 cells that the eye cannot find, so the background that the optimum draws in the two palest colours is drawn one step darker, and the rings round the hotspots widen: the third class holds 23375 cells in QGIS against 6714 in the optimum. Anyone reading the legend sees five classes and has no reason to count them.</p>
</section>
</section>
<section id="r-samples-too-at-random" class="level2">
<h2 id="r-samples-too-at-random-h" class="anchored" data-anchor-id="r-samples-too-at-random">R samples too, at random</h2>
<p><code>classInt</code> has the same problem of cost and solves it differently. For <code>style = "fisher"</code> and <code>style = "jenks"</code> only, and only while <code>warnLargeN = TRUE</code> (the default), when the number of distinct values is above <code>largeN</code> (default 3000), it warns and classifies the minimum and maximum plus a random sample of the values, as many as a tenth of the distinct values, capped at <code>largeN</code>. There is no padding, but without a seed the breaks change from one call to the next.</p>
<div class="cell">
<div class="code-copy-outer-scaffold"><div class="sourceCode cell-code" id="cb21" style="background: #f1f3f5;"><pre class="sourceCode r code-with-copy"><code class="sourceCode r"><span id="cb21-1"><span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">set.seed</span>(<span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">1</span>)</span>
<span id="cb21-2">r_def <span class="ot" style="color: #003B4F;
background-color: null;
font-style: inherit;">&lt;-</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">t</span>(<span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">replicate</span>(<span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">20</span>, <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">suppressWarnings</span>(<span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">classIntervals</span>(x60, <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">5</span>, <span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">style =</span> <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"fisher"</span>))<span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">$</span>brks[<span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">2</span><span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">:</span><span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">5</span>]))</span>
<span id="cb21-3">r_gvf <span class="ot" style="color: #003B4F;
background-color: null;
font-style: inherit;">&lt;-</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">apply</span>(r_def, <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">1</span>, <span class="cf" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">function</span>(b) <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">gvf</span>(x60, <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">findInterval</span>(x60, b) <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">+</span> <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">1</span>))</span>
<span id="cb21-4">n_distinct <span class="ot" style="color: #003B4F;
background-color: null;
font-style: inherit;">&lt;-</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">length</span>(<span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">unique</span>(x60)); n_draw <span class="ot" style="color: #003B4F;
background-color: null;
font-style: inherit;">&lt;-</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">min</span>(<span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">ceiling</span>(<span class="fl" style="color: #AD0000;
background-color: null;
font-style: inherit;">0.1</span> <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">*</span> n_distinct), <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">3000</span>)</span>
<span id="cb21-5">t_j <span class="ot" style="color: #003B4F;
background-color: null;
font-style: inherit;">&lt;-</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">sapply</span>(<span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">c</span>(<span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">600</span>, <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">1500</span>), <span class="cf" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">function</span>(n) <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">system.time</span>(</span>
<span id="cb21-6">  <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">classIntervals</span>(grid_1km<span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">$</span>richness[<span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">1</span><span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">:</span>n], <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">5</span>, <span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">style =</span> <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"jenks"</span>))[[<span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"elapsed"</span>]])</span>
<span id="cb21-7">jenks_60k_min <span class="ot" style="color: #003B4F;
background-color: null;
font-style: inherit;">&lt;-</span> t_j[<span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">2</span>] <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">*</span> (<span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">60000</span> <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">/</span> <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">1500</span>)<span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">^</span><span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">2</span> <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">/</span> <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">60</span></span></code></pre></div></div>
</div>
<p>The grid has 52585 distinct values, so each call draws 3000 of them. Over 20 calls in a row the top break ranged from 55.60 to 63.05 and the lowest from 20.25 to 21.45, around optimal values of 59.21 and 20.79. The fit barely suffers, 0.9261 to 0.9276 against 0.9276, but a figure redrawn tomorrow will have a different legend. Two fixes work. <code>largeN = Inf</code> runs Fisher’s algorithm on every value: it took 6.1 seconds for all 60000 cells on the machine that built this page, which is a price worth paying once. It is not a fix for <code>style = "jenks"</code>, which is written in plain R loops: it took 0.21 seconds for 600 values and 1.30 for 1500, and scaling the second by the square of the size puts the full grid at about 35 minutes. The other fix is to keep the sample and set a seed, which makes the figure reproducible without making it optimal. Silencing the warning is not a third fix: <code>warnLargeN = FALSE</code> also turns the sampling off, so the full computation runs, which for <code>style = "jenks"</code> means the plain R loop on every cell estimated above; use <code>style = "fisher"</code>. Note that R counts distinct values: a richness grid of whole species counts has far fewer than 3000 distinct values, so R never samples it, while QGIS counts features and pads it all the same.</p>
<div class="cell">
<div class="code-copy-outer-scaffold"><div class="sourceCode cell-code" id="cb22" style="background: #f1f3f5;"><pre class="sourceCode r code-with-copy"><code class="sourceCode r"><span id="cb22-1">rows3 <span class="ot" style="color: #003B4F;
background-color: null;
font-style: inherit;">&lt;-</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">rbind</span>(<span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">data.frame</span>(<span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">route =</span> <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"optimal, all cells"</span>, <span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">b =</span> opt_upper[<span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">1</span><span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">:</span><span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">4</span>]),</span>
<span id="cb22-2">               <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">data.frame</span>(<span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">route =</span> <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"R default sampling"</span>, <span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">b =</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">as.vector</span>(r_def)),</span>
<span id="cb22-3">               <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">data.frame</span>(<span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">route =</span> <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"QGIS Natural Breaks"</span>, <span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">b =</span> q60<span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">$</span>upper[<span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">1</span><span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">:</span><span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">4</span>]))</span>
<span id="cb22-4">rows3<span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">$</span>route <span class="ot" style="color: #003B4F;
background-color: null;
font-style: inherit;">&lt;-</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">factor</span>(rows3<span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">$</span>route, <span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">levels =</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">rev</span>(<span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">unique</span>(rows3<span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">$</span>route)))</span>
<span id="cb22-5"><span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">ggplot</span>(rows3, <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">aes</span>(b, route, <span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">colour =</span> route)) <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">+</span></span>
<span id="cb22-6">  <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">geom_point</span>(<span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">data =</span> rows3[rows3<span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">$</span>route <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">!=</span> <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"R default sampling"</span>, ], <span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">size =</span> <span class="fl" style="color: #AD0000;
background-color: null;
font-style: inherit;">2.8</span>) <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">+</span></span>
<span id="cb22-7">  <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">geom_point</span>(<span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">data =</span> rows3[rows3<span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">$</span>route <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">==</span> <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"R default sampling"</span>, ], <span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">size =</span> <span class="fl" style="color: #AD0000;
background-color: null;
font-style: inherit;">2.4</span>, <span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">alpha =</span> <span class="fl" style="color: #AD0000;
background-color: null;
font-style: inherit;">0.75</span>,</span>
<span id="cb22-8">             <span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">position =</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">position_jitter</span>(<span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">height =</span> <span class="fl" style="color: #AD0000;
background-color: null;
font-style: inherit;">0.12</span>, <span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">width =</span> <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">0</span>, <span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">seed =</span> <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">3</span>)) <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">+</span></span>
<span id="cb22-9">  <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">scale_colour_manual</span>(<span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">values =</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">c</span>(<span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"optimal, all cells"</span> <span class="ot" style="color: #003B4F;
background-color: null;
font-style: inherit;">=</span> te_forest, <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"R default sampling"</span> <span class="ot" style="color: #003B4F;
background-color: null;
font-style: inherit;">=</span> te_gold,</span>
<span id="cb22-10">                                 <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"QGIS Natural Breaks"</span> <span class="ot" style="color: #003B4F;
background-color: null;
font-style: inherit;">=</span> te_rust), <span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">guide =</span> <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"none"</span>) <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">+</span></span>
<span id="cb22-11">  <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">scale_y_discrete</span>(<span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">limits =</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">levels</span>(rows3<span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">$</span>route)) <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">+</span></span>
<span id="cb22-12">  <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">labs</span>(<span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">x =</span> <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"interior break (richness)"</span>, <span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">y =</span> <span class="cn" style="color: #8f5902;
background-color: null;
font-style: inherit;">NULL</span>, <span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">title =</span> <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"Three routes to Natural Breaks, 60000 cells"</span>) <span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">+</span></span>
<span id="cb22-13">  <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">theme_datasheet</span>()</span></code></pre></div></div>
<div class="cell-output-display">
<div id="fig-rsample" class="quarto-float quarto-figure quarto-figure-center anchored" alt="A dot chart with interior break in richness on the horizontal axis and three rows. Top row, optimal on all cells: four dark green points near 21, 29, 42 and 59. Middle row, R default sampling: four gold clusters of twenty points each, tight near 20 to 21 and wider higher up, the top one spread from about 56 to 63. Bottom row, QGIS Natural Breaks: four rust points near 9, 22, 33 and 51, each to the left of the matching optimal point.">
<figure class="quarto-float quarto-float-fig figure">
<div aria-describedby="fig-rsample-caption-0ceaefa1-69ba-4598-a22c-09a6ac19f8ca">
<img src="https://tidyecology.com/posts/natural-breaks-in-qgis-and-r/index_files/figure-html/fig-rsample-1.png" class="img-fluid figure-img" alt="A dot chart with interior break in richness on the horizontal axis and three rows. Top row, optimal on all cells: four dark green points near 21, 29, 42 and 59. Middle row, R default sampling: four gold clusters of twenty points each, tight near 20 to 21 and wider higher up, the top one spread from about 56 to 63. Bottom row, QGIS Natural Breaks: four rust points near 9, 22, 33 and 51, each to the left of the matching optimal point." width="720">
</div>
<figcaption class="quarto-float-caption-bottom quarto-float-caption quarto-float-fig" id="fig-rsample-caption-0ceaefa1-69ba-4598-a22c-09a6ac19f8ca">
Figure&nbsp;4: The four interior breaks for the full grid from three routes: optimal on all cells, 20 consecutive calls of classIntervals with its default sampling, and QGIS Natural Breaks.
</figcaption>
</figure>
</div>
</div>
</div>
</section>
<section id="what-to-report-and-what-to-do" class="level2">
<h2 id="what-to-report-and-what-to-do-h" class="anchored" data-anchor-id="what-to-report-and-what-to-do">What to report, and what to do</h2>
<p>For a map in a paper, compute the breaks where you can see them. In R that is <code>classIntervals(x, 5, style = "fisher", largeN = Inf)</code> on every value, or <code>sort(attr(ci, "parameters")[, "max"])</code> on its result <code>ci</code> if you want breaks that are data values rather than midpoints. If the map is finished in QGIS, type those numbers in: in the Classes tab of the Graduated renderer, set the number of classes first, then double click a value range and enter the bounds, so that QGIS never runs its own classification. Changing the number of classes, or the Mode, afterwards recomputes the classes and overwrites the typed values. Equal Interval and Equal Count (Quantile) are safe alternatives on any size of layer, because they do not sample and use the same formulas as R. Natural Breaks in QGIS needs the same care at any size. On layers of up to 3000 features it uses every value, but the backtracking step can still move classes (the seven values above, and most of the small skewed layers in the table), so for a published map compute the breaks in R and type them in whatever the layer size. On a larger layer also look twice at the legend: an upper bound below its lower bound, or a first class holding a handful of features, is the padding, though on a layer that crosses zero, like the change layer above, the padding leaves neither sign. In a methods section, say which algorithm, on how many values, with which software version, and whether the classes were computed on all values or on a sample. “Natural Breaks (Jenks) in QGIS” on 60000 cells means classes from 3000 values and 3000 zeros.</p>
</section>
<section id="honest-limits" class="level2">
<h2 id="honest-limits-h" class="anchored" data-anchor-id="honest-limits">Honest limits</h2>
<p>Everything here is one synthetic layer and one QGIS build, 3.34.4 on Linux. The other branches were checked by reading the source, not by running them; the fill loop and the walk back are unchanged in 3.40, 3.44 and master, but a later release may fix either. The size of each effect depends on the data: the cost of the rank sample was small on this smooth surface, the cost of the backtracking step was small here and on most of the small lognormal layers but large on a few of them, and the padding produced a near empty class here, an inverted empty class once the data sat far enough from zero, and only a small shift in breaks on the change layer. None of those magnitudes transfers to another layer; the mechanism does. The Symbology dialog itself was never clicked, because this QGIS runs headless: the claim that it uses the same code rests on the widget source and on the script calling the same renderer method. Reading the loop further, its index product <code>i * (mMaximumSize - 2)</code> is computed in 32 bit integers and overflows on layers of more than about 716000 features; what the compiled code does on layers that large was not tested. Goodness of variance fit is one criterion for a classification, and a cartographer may prefer classes that fit worse and read better.</p>
</section>
<section id="references" class="level2">
<h2 id="references-h" class="anchored" data-anchor-id="references">References</h2>
<p>Fisher WD 1958 Journal of the American Statistical Association 53(284):789-798 (<a href="https://doi.org/10.1080/01621459.1958.10501479">10.1080/01621459.1958.10501479</a>)</p>
<p>Jenks GF, Caspall FC 1971 Annals of the Association of American Geographers 61(2):217-244 (<a href="https://doi.org/10.1111/j.1467-8306.1971.tb00779.x">10.1111/j.1467-8306.1971.tb00779.x</a>)</p>
<p>Bivand R 2023 classInt: Choose Univariate Class Intervals. R package version 0.4-10 (https://CRAN.R-project.org/package=classInt)</p>
</section>
<section id="related-tutorials" class="level2">
<h2 id="related-tutorials-h" class="anchored" data-anchor-id="related-tutorials">Related tutorials</h2>
<ul>
<li><a href="https://tidyecology.com/posts/richness-mapping-sf/">Richness mapping with sf</a></li>
<li><a href="https://tidyecology.com/posts/running-qgis-from-the-command-line/">Running QGIS from the command line</a></li>
<li><a href="https://tidyecology.com/posts/choosing-colours-for-ecological-data/">Choosing colours for ecological data</a></li>
<li><a href="https://tidyecology.com/posts/qgis-to-r-spatial-join/">QGIS to R spatial join</a></li>
</ul>
<details class="te-repro" data-pagefind-ignore="">
<summary>Reproducibility</summary>
<ul>
<li>Code last run: 2026-10-15</li>
<li>R version 4.5.3 (2026-03-11), aarch64-apple-darwin20</li>
<li>Packages: classInt 0.4-11, ggplot2 4.0.3</li>
</ul>
</details>


<!-- -->

</section>

 ]]></description>
  <category>R</category>
  <category>QGIS</category>
  <category>GIS</category>
  <category>spatial</category>
  <category>classInt</category>
  <category>cartography</category>
  <category>ecology tutorial</category>
  <guid isPermaLink="false">https://tidyecology.com/posts/natural-breaks-in-qgis-and-r/</guid>
  <pubDate>Sat, 26 Sep 2026 06:00:00 GMT</pubDate>
  <media:content url="https://tidyecology.com/posts/natural-breaks-in-qgis-and-r/thumbnail.png" medium="image" type="image/png" height="104" width="144"/>
</item>
</channel>
</rss>
