<?xml version="1.0" encoding="UTF-8"?><rss version="2.0"
	xmlns:content="http://purl.org/rss/1.0/modules/content/"
	xmlns:wfw="http://wellformedweb.org/CommentAPI/"
	xmlns:dc="http://purl.org/dc/elements/1.1/"
	xmlns:atom="http://www.w3.org/2005/Atom"
	xmlns:sy="http://purl.org/rss/1.0/modules/syndication/"
	xmlns:slash="http://purl.org/rss/1.0/modules/slash/"
	>

<channel>
	<title>R-bloggers</title>
	<atom:link href="https://www.r-bloggers.com/feed/" rel="self" type="application/rss+xml" />
	<link>https://www.r-bloggers.com</link>
	<description>R news and tutorials contributed by hundreds of R bloggers</description>
	<lastBuildDate>Mon, 30 Nov 2026 13:20:56 +0000</lastBuildDate>
	<language>en-US</language>
	<sy:updatePeriod>
	hourly	</sy:updatePeriod>
	<sy:updateFrequency>
	1	</sy:updateFrequency>
	<generator>https://wordpress.org/?v=5.5.25</generator>

<image>
	<url>https://i0.wp.com/www.r-bloggers.com/wp-content/uploads/2016/08/cropped-R_single_01-200.png?fit=32%2C32&#038;ssl=1</url>
	<title>R-bloggers</title>
	<link>https://www.r-bloggers.com</link>
	<width>32</width>
	<height>32</height>
</image> 
<site xmlns="com-wordpress:feed-additions:1">11524731</site>	<item>
		<title>From Marginal Tail Risk to Forward Regime Signals: Modeling BTC-ETH Co-Crash Dynamics with Torch</title>
		<link>https://www.r-bloggers.com/2026/11/from-marginal-tail-risk-to-forward-regime-signals-modeling-btc-eth-co-crash-dynamics-with-torch/</link>
		
		<dc:creator><![CDATA[Selcuk Disci]]></dc:creator>
		<pubDate>Mon, 30 Nov 2026 13:20:56 +0000</pubDate>
				<category><![CDATA[R bloggers]]></category>
		<guid isPermaLink="false">http://datageeek.com/?p=13083</guid>

					<description><![CDATA[<div style = "width:60%; display: inline-block; float:left; "> In quantitative cryptocurrency risk management, measuring single-asset downside volatility is rarely enough. During market stress, Bitcoin (BTC) and Ethereum (ETH) exhibit strong lower-tail dependence—meaning extreme drawdowns tend to occur simultaneously rather than independently. Building upon the joint tail risk modeling framework introduced in [arXiv:2611.28524v1], which combines conditional marginal ...</div>
<div style = "width: 40%; display: inline-block; float:right;"></div>
<div style="clear: both;"></div>
<strong>Continue reading</strong>: <a href="https://www.r-bloggers.com/2026/11/from-marginal-tail-risk-to-forward-regime-signals-modeling-btc-eth-co-crash-dynamics-with-torch/">From Marginal Tail Risk to Forward Regime Signals: Modeling BTC-ETH Co-Crash Dynamics with Torch</a>]]></description>
										<content:encoded><![CDATA[<!-- 
<div style="min-height: 30px;">
[social4i size="small" align="align-left"]
</div>
-->

<div style="border: 1px solid; background: none repeat scroll 0 0 #EDEDED; margin: 1px; font-size: 12px;">
[This article was first published on  <strong><a href="https://datageeek.com/2026/11/30/from-marginal-tail-risk-to-forward-regime-signals-modeling-btc-eth-co-crash-dynamics-with-torch/"> DataGeeek</a></strong>, and kindly contributed to <a href="https://www.r-bloggers.com/" rel="nofollow">R-bloggers</a>].  (You can report issue about the content on this page <a href="https://www.r-bloggers.com/contact-us/">here</a>)
<hr>Want to share your content on R-bloggers?<a href="https://www.r-bloggers.com/add-your-blog/" rel="nofollow"> click here</a> if you have a blog, or <a href="http://r-posts.com/" rel="nofollow"> here</a> if you don't.
</div>

<p class="wp-block-paragraph">In quantitative cryptocurrency risk management, measuring single-asset downside volatility is rarely enough. During market stress, Bitcoin (<strong>BTC</strong>) and Ethereum (<strong>ETH</strong>) exhibit strong lower-tail dependence—meaning extreme drawdowns tend to occur simultaneously rather than independently. Building upon the joint tail risk modeling framework introduced in <strong>[</strong><a href="https://arxiv.org/html/2611.28524v1" rel="nofollow" target="_blank"><em><strong>arXiv:2611.28524v1</strong></em></a><strong>]</strong>, which combines conditional marginal tail estimation with dynamic copula dependence, this study translates theoretical tail dependence into an actionable trading signal.</p>



<p class="wp-block-paragraph">Rather than simply estimating today’s static probability of a joint crash (<math><semantics><msub><mi>p</mi><mrow><mtext>joint</mtext><mo separator="true">,</mo><mi>t</mi></mrow></msub><annotation encoding="application/x-tex">p_{\text{joint}, t}</annotation></semantics></math>), our objective is to forecast <strong>whether systemic co-crash risk will escalate over the next 20 trading days</strong>. Specifically, we frame a forward-looking regime signal: will the average joint tail risk over the upcoming 20-day horizon exceed today’s baseline level (<math><semantics><mrow><mfrac><mn>1</mn><mn>20</mn></mfrac><msubsup><mo movablelimits="false">∑</mo><mrow><mi>h</mi><mo>=</mo><mn>1</mn></mrow><mn>20</mn></msubsup><msub><mi>p</mi><mrow><mtext>joint</mtext><mo separator="true">,</mo><mi>t</mi><mo>+</mo><mi>h</mi></mrow></msub><mo>></mo><msub><mi>p</mi><mrow><mtext>joint</mtext><mo separator="true">,</mo><mi>t</mi></mrow></msub></mrow><annotation encoding="application/x-tex">\frac{1}{20}\sum_{h=1}^{20} p_{\text{joint}, t+h} > p_{\text{joint}, t}</annotation></semantics></math>)? </p>



<p class="wp-block-paragraph">When the model detects an elevated probability of rising joint tail dependence, it triggers a defensive posture (<strong>Hedge / Reduce Leverage</strong>); otherwise, it signals <strong>Standard Risk</strong>.</p>



<h2 class="wp-block-heading">System Architecture Overview</h2>



<p class="wp-block-paragraph">The pipeline bridges financial econometrics and deep sequence modeling in native R using <code>torch</code> and <code>tidymodels</code>/<code>yardstick</code>:</p>


<pre>
[BTC-USD & ETH-USD Daily OHLCV (2 Years)]
                   |
                   v
[1. Marginal Tail Model: ES-CAViaR-R (alpha = 0.01)]
   - Recursive conditional VaR (q) & ES (es)
   - Asymmetric Laplace MLE (L-BFGS-B)
   - Standardized tail residuals: z_t = (ret_t - var_1,t) / (var_1,t - es_1,t)
                   |
                   v
[2. Rank Transform & Batched Torch BB1 Copula MLE]
   - Rolling window: win_n = 90 days
   - Uniform pseudo-observations: u_btc, u_eth
   - Batched Adam optimization for BB1 parameters (theta, delta)
   - Joint tail risk probability at alpha = 0.01: p_joint(t)
                   |
                   v
[3. Sequence Framing (lookback = 40, horizon = 20)]
   - Scaled input windows of p_joint (40 days)
   - Target trajectory deltas: (p[t+1:t+20] - p[t])
   - Binary rise signal: mean(p[t+1:t+20]) &gt; p[t] (YES / NO)
                   |
                   v
[4. 2-Layer Torch LSTM + Softplus + Dense Aggregator]
   - 3 input channels: level, first diff, window-centered series
   - 2-layer LSTM (hidden = 64) + nn_softplus() heads
   - Optimizer: AdamW | Max budget: 50 epochs
   - Homoscedastic uncertainty loss via learned log_vars (no fixed weights)
   - Threshold selection via Youden J statistic
                   |
        +----------+----------+
        |                     |
        v                     v
[4 Percentage Metrics]  [20-Day Forecast Plot]
- accuracy (%)          - Daily posture classification
- bal_accuracy (%)      - Hedge vs. Standard Risk
- sens (%)              - ggtext title + ggplotly hover
- spec (%)
</pre>


<h2 class="wp-block-heading">Stage 1: Marginal Tail Dynamics via ES-CAViaR-R</h2>



<p class="wp-block-paragraph">To capture time-varying tail risk and intraday range information before modeling cross-asset dependence, we first filter daily log-returns for both BTC-USD and ETH-USD using an <strong>ES-CAViaR-R</strong> specification at the $\alpha = 0.01$ extreme quantile level:</p>



<ul class="wp-block-list">
<li><strong>Range-Augmented Quantile Recursion:</strong> Conditional Value-at-Risk <math><semantics><mrow><mo form="prefix" stretchy="false">(</mo><msub><mi>q</mi><mi>t</mi></msub><mo form="postfix" stretchy="false">)</mo></mrow><annotation encoding="application/x-tex">(q_t)</annotation></semantics></math> evolves autoregressively using lagged VaR and the Garman-Klass intraday volatility estimator (<math><semantics><mrow><mi>G</mi><msub><mi>K</mi><mrow><mi>t</mi><mo>−</mo><mn>1</mn></mrow></msub></mrow><annotation encoding="application/x-tex">GK_{t-1}</annotation></semantics></math>).</li>



<li><strong>Conditional Expected Shortfall (<math><semantics><mrow><mi>E</mi><msub><mi>S</mi><mi>t</mi></msub></mrow><annotation encoding="application/x-tex">ES_t</annotation></semantics></math>):</strong> Whenever a return breaches <math><semantics><msub><mi>q</mi><mrow><mi>t</mi><mo>−</mo><mn>1</mn></mrow></msub><annotation encoding="application/x-tex">q_{t-1}</annotation></semantics></math>, the tail spread <math><semantics><mrow><msub><mi>w</mi><mi>t</mi></msub><mo>=</mo><msub><mi>q</mi><mi>t</mi></msub><mo>−</mo><mi>E</mi><msub><mi>S</mi><mi>t</mi></msub></mrow><annotation encoding="application/x-tex">w_t = q_t – ES_t</annotation></semantics></math> updates dynamically based on standardized exceedance magnitude.</li>



<li><strong>Asymmetric Laplace MLE:</strong> Parameters are estimated via <code>L-BFGS-B</code> optimization under the Asymmetric Laplace density, yielding standardized tail residuals <math><semantics><mrow><msub><mi>z</mi><mi>t</mi></msub><mo>=</mo><mo form="prefix" stretchy="false">(</mo><msub><mi>r</mi><mi>t</mi></msub><mo>−</mo><msub><mtext>VaR</mtext><mrow><mn>1</mn><mo separator="true">,</mo><mi>t</mi></mrow></msub><mo form="postfix" stretchy="false">)</mo><mi>/</mi><mo form="prefix" stretchy="false">(</mo><msub><mtext>VaR</mtext><mrow><mn>1</mn><mo separator="true">,</mo><mi>t</mi></mrow></msub><mo>−</mo><msub><mtext>ES</mtext><mrow><mn>1</mn><mo separator="true">,</mo><mi>t</mi></mrow></msub><mo form="postfix" stretchy="false">)</mo></mrow><annotation encoding="application/x-tex">z_t = (r_t – \text{VaR}_{1,t}) / (\text{VaR}_{1,t} – \text{ES}_{1,t})</annotation></semantics></math>.</li>
</ul>



<h2 class="wp-block-heading">Stage 2: Batched Torch BB1 Copula &#038; Joint Crash Probability</h2>



<p class="wp-block-paragraph">Standardized residuals from Stage 1 are mapped into uniform pseudo-observations <math><semantics><mrow><mo form="prefix" stretchy="false">(</mo><msub><mi>u</mi><mtext>BTC</mtext></msub><mo separator="true">,</mo><msub><mi>u</mi><mtext>ETH</mtext></msub><mo form="postfix" stretchy="false">)</mo></mrow><annotation encoding="application/x-tex">(u_{\text{BTC}}, u_{\text{ETH}}) </annotation></semantics></math>over rolling 90-day windows (<code>win_n = 90</code>). Because linear correlation fails to capture asymmetric crash clustering, we model the joint distribution using the two-parameter <strong>BB1 (Clayton-Gumbel) copula</strong>, which simultaneously accommodates lower-tail (<math><semantics><mrow><mi>θ</mi><mo>></mo><mn>0</mn></mrow><annotation encoding="application/x-tex">\theta > 0</annotation></semantics></math>) and upper-tail (<math><semantics><mrow><mi>δ</mi><mo>≥</mo><mn>1</mn></mrow><annotation encoding="application/x-tex">\delta \ge 1</annotation></semantics></math>) dependence.</p>



<p class="wp-block-paragraph">Rather than looping sequentially over hundreds of rolling windows on the CPU, we vectorize the entire rolling estimation as a single tensor batch in <code>torch</code>. Using <code>optim_adam</code>, all rolling windows are optimized simultaneously via exact analytical BB1 log-likelihood gradients. From the estimated parameters <math><semantics><mrow><mo form="prefix" stretchy="false">(</mo><msub><mover><mi>θ</mi><mo stretchy="false">^</mo></mover><mi>t</mi></msub><mo separator="true">,</mo><msub><mover><mi>δ</mi><mo stretchy="false">^</mo></mover><mi>t</mi></msub><mo form="postfix" stretchy="false">)</mo></mrow><annotation encoding="application/x-tex">(\hat{\theta}_t, \hat{\delta}_t)</annotation></semantics></math>, we extract the daily joint lower-tail exceedance probability at <strong><math><semantics><mrow><mi>α</mi><mo>=</mo><mn>0.01</mn></mrow><annotation encoding="application/x-tex">\alpha = 0.01</annotation></semantics></math></strong>:</p>



<p class="has-text-align-center wp-block-paragraph"><math><semantics><mrow><msub><mi>p</mi><mtext>joint</mtext></msub><mo form="prefix" stretchy="false">(</mo><mi>t</mi><mo form="postfix" stretchy="false">)</mo><mo>=</mo><msub><mi>C</mi><mtext>BB1</mtext></msub><mo form="prefix" stretchy="false">(</mo><mi>α</mi><mo separator="true">,</mo><mi>α</mi><mo separator="true">;</mo><msub><mover><mi>θ</mi><mo stretchy="false">^</mo></mover><mi>t</mi></msub><mo separator="true">,</mo><msub><mover><mi>δ</mi><mo stretchy="false">^</mo></mover><mi>t</mi></msub><mo form="postfix" stretchy="false">)</mo><mo>=</mo><msup><mrow><mo fence="true" form="prefix">(</mo><mn>1</mn><mo>+</mo><msup><mrow><mo fence="true" form="prefix">[</mo><mn>2</mn><mo form="prefix" stretchy="false">(</mo><msup><mi>α</mi><mrow><mo lspace="0em" rspace="0em">−</mo><msub><mover><mi>θ</mi><mo stretchy="false">^</mo></mover><mi>t</mi></msub></mrow></msup><mo>−</mo><mn>1</mn><msup><mo form="postfix" stretchy="false">)</mo><msub><mover><mi>δ</mi><mo stretchy="false">^</mo></mover><mi>t</mi></msub></msup><mo fence="true" form="postfix">]</mo></mrow><mrow><mn>1</mn><mi>/</mi><msub><mover><mi>δ</mi><mo stretchy="false">^</mo></mover><mi>t</mi></msub></mrow></msup><mo fence="true" form="postfix">)</mo></mrow><mrow><mo lspace="0em" rspace="0em">−</mo><mn>1</mn><mi>/</mi><msub><mover><mi>θ</mi><mo stretchy="false">^</mo></mover><mi>t</mi></msub></mrow></msup></mrow><annotation encoding="application/x-tex">p_{\text{joint}}(t) = C_{\text{BB1}}(\alpha, \alpha; \hat{\theta}_t, \hat{\delta}_t) = \left(1 + \left[2(\alpha^{-\hat{\theta}_t} – 1)^{\hat{\delta}_t}\right]^{1/\hat{\delta}_t}\right)^{-1/\hat{\theta}_t}</annotation></semantics></math></p>



<h2 class="wp-block-heading">Stage 3: Multi-Task 2-Layer LSTM &#038; Homoscedastic Loss Balancing</h2>



<p class="wp-block-paragraph">To forecast how <math><semantics><mrow><msub><mi>p</mi><mtext>joint</mtext></msub><mo form="prefix" stretchy="false">(</mo><mi>t</mi><mo form="postfix" stretchy="false">)</mo></mrow><annotation encoding="application/x-tex">p_{\text{joint}}(t)</annotation></semantics></math> will evolve over the next 20 trading days, we construct 40-day lookback sequences enriched with three feature channels:</p>



<ol start="1" class="wp-block-list">
<li><strong>Scaled Level:</strong> Standardized <math><semantics><msub><mi>p</mi><mtext>joint</mtext></msub><annotation encoding="application/x-tex">p_{\text{joint}}</annotation></semantics></math> values.</li>



<li><strong>First Difference </strong><math><semantics><mrow><mo form="prefix" stretchy="false">(</mo><mrow><mi mathvariant="normal">Δ</mi></mrow><msub><mi>x</mi><mi>t</mi></msub><mo form="postfix" stretchy="false">)</mo></mrow><annotation encoding="application/x-tex">(\Delta x_t)</annotation></semantics></math><strong>:</strong> Daily momentum in tail dependence.</li>



<li><strong>Window-Centered Series </strong><math><semantics><mrow><mo form="prefix" stretchy="false">(</mo><msub><mi>x</mi><mi>t</mi></msub><mo>−</mo><mover><mi>x</mi><mo stretchy="false">‾</mo></mover><mo form="postfix" stretchy="false">)</mo></mrow><annotation encoding="application/x-tex">(x_t – \bar{x})</annotation></semantics></math><strong>:</strong> Local regime deviation relative to the 40-day mean.</li>
</ol>



<p class="wp-block-paragraph">These three channels feed into a <strong>2-layer Torch LSTM</strong> (<code>hidden_size = 64</code>) paired with <code>nn_softplus()</code> projection heads and a dense trajectory aggregator. The network jointly predicts the 20-step trajectory deltas <math><semantics><mrow><mo form="prefix" stretchy="false">(</mo><msub><mi>ℒ</mi><mtext>MSE</mtext></msub><mo form="postfix" stretchy="false">)</mo></mrow><annotation encoding="application/x-tex">(\mathcal{L}_{\text{MSE}})</annotation></semantics></math> and the binary probability that average future tail risk will exceed today’s level <math><semantics><mrow><mo form="prefix" stretchy="false">(</mo><msub><mi>ℒ</mi><mtext>BCE</mtext></msub><mo form="postfix" stretchy="false">)</mo></mrow><annotation encoding="application/x-tex">(\mathcal{L}_{\text{BCE}})</annotation></semantics></math>.</p>



<p class="wp-block-paragraph">Instead of introducing arbitrary manual weighting constants between classification and trajectory regression, the model learns task weights end-to-end via <strong>homoscedastic uncertainty weighting</strong> (<code>log_vars</code>) under the <code>AdamW</code> optimizer with a strict budget of <strong>50 epochs</strong>. Finally, the optimal decision threshold is calibrated via Youden’s <math><semantics><mi>J</mi><annotation encoding="application/x-tex">J</annotation></semantics></math> statistic <math><semantics><mrow><mo form="prefix" stretchy="false">(</mo><mtext>Sensitivity</mtext><mo>+</mo><mtext>Specificity</mtext><mo>−</mo><mn>1</mn><mo form="postfix" stretchy="false">)</mo></mrow><annotation encoding="application/x-tex">(\text{Sensitivity} + \text{Specificity} – 1)</annotation></semantics></math>.</p>



<h2 class="wp-block-heading">Model Evaluation &#038; Decision Signal Interpretation</h2>



<p class="wp-block-paragraph">To keep performance diagnostics transparent and directly interpretable for portfolio risk management, evaluation is distilled into four percentage-based <code>yardstick</code> metrics:</p>



<figure class="wp-block-table"><table class="has-fixed-layout"><thead><tr><td><strong>Metric</strong></td><td><strong>Score (%)</strong></td><td><strong>Operational Meaning</strong></td></tr></thead><tbody><tr><td><strong>Accuracy</strong></td><td><strong>62.2%</strong></td><td>Overall proportion of days where the 20-day risk regime direction is classified correctly.</td></tr><tr><td><strong>Balanced Accuracy</strong></td><td><strong>62.2%</strong></td><td>Equal-weighted accuracy across rising-risk (<code>YES</code>) and easing-risk (<code>NO</code>) regimes, confirming no majority-class bias.</td></tr><tr><td><strong>Sensitivity (Recall)</strong></td><td><strong>64.1%</strong></td><td>Proportion of actual joint tail-risk escalations successfully flagged in advance.</td></tr><tr><td><strong>Specificity</strong></td><td><strong>60.4%</strong></td><td>Proportion of calm/easing periods correctly identified without triggering false hedge alarms.</td></tr></tbody></table></figure>



<p class="wp-block-paragraph">Predicting the 20-day forward direction of a rolling copula tail probability is inherently noisy, yet within a compact 50-epoch training budget, the model achieves a well-balanced ~62.2% classification profile without overfitting to either regime.</p>



<p class="wp-block-paragraph"><strong>In the final</strong> interactive <code>ggplotly</code> forecast visualization, daily projected probabilities are plotted against the Youden-optimal threshold: regions breaching the threshold are shaded in red (<strong>Hedge / Reduce Leverage</strong>), while periods remaining below are shaded in green (<strong>Standard Risk</strong>), translating complex copula-LSTM dynamics into an immediate, human-readable risk posture.</p>



<figure data-wp-context="{"imageId":"6b0d79521d3d0"}" data-wp-interactive="core/image" data-wp-key="6b0d79521d3d0" class="wp-block-image size-large wp-lightbox-container"><img loading="lazy" data-attachment-id="13088" data-permalink="https://datageeek.com/2026/11/30/from-marginal-tail-risk-to-forward-regime-signals-modeling-btc-eth-co-crash-dynamics-with-torch/cavier/" data-orig-file="https://datageeek.com/wp-content/uploads/2026/11/cavier.png" data-orig-size="1852,782" data-comments-opened="1" data-image-title="cavier" data-image-description="" data-image-caption="" data-large-file="https://i1.wp.com/datageeek.com/wp-content/uploads/2026/11/cavier.png?w=450&#038;ssl=1" data-wp-class--hide="state.isContentHidden" data-wp-class--show="state.isContentVisible" data-wp-init="callbacks.setButtonStyles" data-wp-on--click="actions.showLightbox" data-wp-on--load="callbacks.setButtonStyles" data-wp-on--pointerdown="actions.preloadImage" data-wp-on--pointerenter="actions.preloadImageWithDelay" data-wp-on--pointerleave="actions.cancelPreload" data-wp-on-window--resize="callbacks.setButtonStyles" src="https://i1.wp.com/datageeek.com/wp-content/uploads/2026/11/cavier.png?w=450&#038;ssl=1" alt="BTC-ETH 20-day joint crash risk chart showing fluctuating risk percentages, with red areas indicating hedge or reduced leverage and green areas indicating standard risk." class="wp-image-13088" srcset_temp="https://i1.wp.com/datageeek.com/wp-content/uploads/2026/11/cavier.png?w=450&#038;ssl=1 1024w, https://datageeek.com/wp-content/uploads/2026/11/cavier.png?w=150 150w, https://datageeek.com/wp-content/uploads/2026/11/cavier.png?w=300 300w, https://datageeek.com/wp-content/uploads/2026/11/cavier.png?w=768 768w, https://datageeek.com/wp-content/uploads/2026/11/cavier.png?w=1440 1440w, https://datageeek.com/wp-content/uploads/2026/11/cavier.png 1852w" sizes="(max-width: 1024px) 100vw, 1024px" data-recalc-dims="1" /><button
			class="lightbox-trigger"
			type="button"
			aria-haspopup="dialog"
			data-wp-bind--aria-label="state.thisImage.triggerButtonAriaLabel"
			data-wp-init="callbacks.initTriggerButton"
			data-wp-on--click="actions.showLightbox"
			data-wp-style--right="state.thisImage.buttonRight"
			data-wp-style--top="state.thisImage.buttonTop"
		>
			<svg xmlns="http://www.w3.org/2000/svg" width="12" height="12" fill="none" viewBox="0 0 12 12">
				<path fill="#fff" d="M2 0a2 2 0 0 0-2 2v2h1.5V2a.5.5 0 0 1 .5-.5h2V0H2Zm2 10.5H2a.5.5 0 0 1-.5-.5V8H0v2a2 2 0 0 0 2 2h2v-1.5ZM8 12v-1.5h2a.5.5 0 0 0 .5-.5V8H12v2a2 2 0 0 1-2 2H8Zm2-12a2 2 0 0 1 2 2v2h-1.5V2a.5.5 0 0 0-.5-.5H8V0h2Z" />
			</svg>
		</button></figure>



<p class="wp-block-paragraph"><strong><em>Here is the full code:</em></strong></p>


<pre>
library(torch)
library(plotly)
library(tidyquant)
library(yardstick)
library(ggtext)
library(tidyverse)

set.seed(42)
torch_manual_seed(42)

# ============================================================
# 1. DATA & ES-CAViaR-R MARGINAL TAIL ESTIMATION
# ============================================================

# Estimate ES-CAViaR-R conditional VaR, ES, and standardized residuals for one asset
fit_escaviar_r &lt;- function(df, alpha = 0.01) {
  r &lt;- df$ret
  gk &lt;- df$gk
  sig &lt;- df$sigma
  n &lt;- length(r)

  # Recursively compute conditional VaR (q) and conditional ES (es) series
  recurse &lt;- function(p) {
    q &lt;- w &lt;- es &lt;- numeric(n)
    q[1] &lt;- min(quantile(r, alpha, na.rm = TRUE), -1)
    w[1] &lt;- max(abs(q[1]), 1e-4)
    es[1] &lt;- q[1] - w[1]

    # Step through time to update VaR and tail shortfall recursively
    for (t in 2:n) {
      q[t] &lt;- p[1] + p[2] * q[t - 1] + p[3] * gk[t - 1]
      w[t] &lt;- if (r[t - 1] &lt;= q[t - 1]) {
        p[4] + p[5] * ((q[t - 1] - r[t - 1]) / max(sig[t - 1], 1e-6)) + p[6] * w[t - 1]
      } else {
        w[t - 1]
      }
      w[t] &lt;- max(w[t], 1e-6)
      es[t] &lt;- q[t] - w[t]
    }

    list(q = q, es = es)
  }

  # Evaluate Asymmetric Laplace negative log-likelihood for ES-CAViaR-R parameters
  nll &lt;- function(p) {
    out &lt;- recurse(p)
    ok &lt;- is.finite(out$q) &#038; is.finite(out$es) &#038; (out$es &lt; -1e-6)
    if (sum(ok) &lt; 10) return(1e12)

    u &lt;- r[ok] - out$q[ok]
    rho &lt;- u * (alpha - (u &lt;= 0))
    val &lt;- sum(-log((1 - alpha) / (-out$es[ok])) + rho / (alpha * out$es[ok]))
    if (is.finite(val)) val else 1e12
  }

  # Optimize ES-CAViaR-R parameters and append conditional VaR, ES, and residuals
  par_hat &lt;- optim(
    c(-0.5, 0.85, -0.5, 0.2, 0.2, 0.2), nll,
    method = &quot;L-BFGS-B&quot;,
    lower = c(-5, 0, -10, 1e-5, 1e-5, 0),
    upper = c(-1e-4, 0.995, -1e-5, 5, 5, 0.995)
  )$par

  tail_out &lt;- recurse(par_hat)

  df %&gt;% mutate(
    var_1 = tail_out$q,
    es_1  = tail_out$es,
    z     = (ret - var_1) / pmax(var_1 - es_1, 1e-6)
  )
}

# Fetch 2-year OHLCV data, compute returns, Garman-Klass volatility, and fit marginal tail models
tails &lt;- tq_get(c(&quot;BTC-USD&quot;, &quot;ETH-USD&quot;), from = Sys.Date() - lubridate::years(2)) %&gt;%
  group_by(symbol) %&gt;%
  arrange(date, .by_group = TRUE) %&gt;%
  mutate(
    ret   = 100 * log(close / dplyr::lag(close)),
    gk    = 0.511 * log(high / low)^2 - 0.383 * log(close / open)^2 -
              0.019 * (log(close / open) * log((high * low) / open^2) -
                         2 * log(high / open) * log(low / open)),
    sigma = sqrt(pmax(accumulate(replace_na(ret^2, 0), ~ 0.94 * .x + 0.06 * .y,
                                 .init = var(ret, na.rm = TRUE))[-1], 1e-8))
  ) %&gt;%
  filter(!is.na(ret), is.finite(gk)) %&gt;%
  group_split() %&gt;%
  map(fit_escaviar_r) %&gt;%
  bind_rows()

# ============================================================
# 2. RANK TRANSFORM & BATCHED TORCH BB1 COPULA MLE -&gt; p(t)
# ============================================================

# Fit rolling BB1 copula parameters across all windows simultaneously via Torch MLE
fit_bb1_batched_torch &lt;- function(u1_all, u2_all, win_n = 90L, alpha = 0.01, steps = 120, lr = 0.05) {
  n_total &lt;- length(u1_all)
  valid_i &lt;- win_n:n_total
  n_win &lt;- length(valid_i)

  u1_mat &lt;- matrix(0, nrow = n_win, ncol = win_n)
  u2_mat &lt;- matrix(0, nrow = n_win, ncol = win_n)

  # Populate rolling window rank-normalized pseudo-observations for both assets
  for (k in seq_len(n_win)) {
    idx &lt;- (valid_i[k] - win_n + 1):valid_i[k]
    u1_mat[k, ] &lt;- rank(u1_all[idx], ties.method = &quot;average&quot;) / (win_n + 1)
    u2_mat[k, ] &lt;- rank(u2_all[idx], ties.method = &quot;average&quot;) / (win_n + 1)
  }

  u1 &lt;- torch_tensor(u1_mat, dtype = torch_float())
  u2 &lt;- torch_tensor(u2_mat, dtype = torch_float())
  phi &lt;- torch_zeros(c(n_win, 2), requires_grad = TRUE)
  opt &lt;- optim_adam(list(phi), lr = lr)

  # Optimize batched BB1 copula negative log-likelihood across all rolling windows
  for (s in seq_len(steps)) {
    opt$zero_grad()
    theta &lt;- torch_exp(phi[, 1, drop = FALSE]) + 1e-4
    delta &lt;- 1.0 + torch_exp(phi[, 2, drop = FALSE])

    A     &lt;- torch_pow(u1, -theta) - 1.0
    B     &lt;- torch_pow(u2, -theta) - 1.0
    Ad_Bd &lt;- torch_pow(A, delta) + torch_pow(B, delta)
    S     &lt;- torch_pow(Ad_Bd, 1.0 / delta)

    log_c &lt;- -(theta + 1.0) * (torch_log(u1) + torch_log(u2)) +
      (delta - 1.0) * (torch_log(A) + torch_log(B)) +
      (1.0 / delta - 2.0) * torch_log(Ad_Bd) +
      (-1.0 / theta - 2.0) * torch_log1p(S) +
      torch_log(S * (delta * theta + 1.0) + theta * (delta - 1.0))

    nll &lt;- -torch_mean(log_c)
    nll$backward()
    opt$step()
  }

  # Extract fitted BB1 parameters and evaluate joint lower-tail risk at alpha
  with_no_grad({
    theta_hat &lt;- as.numeric((torch_exp(phi[, 1]) + 1e-4)$squeeze())
    delta_hat &lt;- as.numeric((1.0 + torch_exp(phi[, 2]))$squeeze())
    a_term    &lt;- (alpha^(-theta_hat) - 1)^delta_hat
    s_alpha   &lt;- (2 * a_term)^(1 / delta_hat)
    p_vals    &lt;- (1 + s_alpha)^(-1 / theta_hat)
  })

  out &lt;- rep(NA_real_, n_total)
  out[valid_i] &lt;- p_vals
  out
}

win_n &lt;- 90L  # Rolling window length in trading days for BB1 copula estimation
alpha &lt;- 0.01 # Lower tail probability level for joint crash risk evaluation

# Align standardized tail residuals and compute rolling joint tail risk probabilities
joint &lt;- tails %&gt;%
  select(date, symbol, z) %&gt;%
  pivot_wider(names_from = symbol, values_from = z) %&gt;%
  drop_na() %&gt;%
  arrange(date) %&gt;%
  mutate(
    u_btc   = rank(`BTC-USD`, ties.method = &quot;average&quot;) / (n() + 1),
    u_eth   = rank(`ETH-USD`, ties.method = &quot;average&quot;) / (n() + 1),
    p_joint = fit_bb1_batched_torch(u_btc, u_eth, win_n = win_n, alpha = alpha, steps = 120)
  ) %&gt;%
  drop_na()

# ============================================================
# 3. TORCH LSTM + DENSE AGGREGATION & 4-METRIC EVALUATION
# ============================================================

# Select optimal probability threshold on training set by maximizing Youden J statistic
select_best_threshold &lt;- function(probs, y_bin) {
  grid &lt;- seq(0.20, 0.80, by = 0.01)
  scores &lt;- map_dbl(grid, function(th) {
    pred &lt;- as.integer(probs &gt; th)
    tp &lt;- sum(pred == 1L &#038; y_bin == 1L)
    tn &lt;- sum(pred == 0L &#038; y_bin == 0L)
    fp &lt;- sum(pred == 1L &#038; y_bin == 0L)
    fn &lt;- sum(pred == 0L &#038; y_bin == 1L)
    sens &lt;- if ((tp + fn) &gt; 0) tp / (tp + fn) else 0
    spec &lt;- if ((tn + fp) &gt; 0) tn / (tn + fp) else 0
    sens + spec - 1
  })
  grid[which.max(scores)]
}

# Classify daily forecast posture into human-readable status, action, and color
classify_trader_posture &lt;- function(prob_inc, thresh) {
  tibble(
    status = if_else(prob_inc &gt; thresh, &quot;Elevated Crash Risk&quot;, &quot;Easing Crash Risk&quot;),
    action = if_else(prob_inc &gt; thresh, &quot;Hedge / Reduce Leverage&quot;, &quot;Maintain Standard Risk&quot;),
    color  = if_else(prob_inc &gt; thresh, &quot;#b22222&quot;, &quot;#2e7d32&quot;)
  )
}

lookback &lt;- 40L                       # Input sequence window length in trading days
horizon  &lt;- 20L                       # Forward forecast horizon in trading days
p &lt;- joint$p_joint                    # Joint lower-tail crash probability time series
idx &lt;- lookback:(length(p) - horizon) # Valid sample anchor indices for supervised windows

# Build standardized lookback input array from joint tail probability windows
x_raw &lt;- map(idx, ~ p[(.x - lookback + 1):.x]) |&gt; unlist() * 1000
x_mu  &lt;- mean(x_raw, na.rm = TRUE)
x_sd  &lt;- max(sd(x_raw, na.rm = TRUE), 1e-6)
x_arr &lt;- array((x_raw - x_mu) / x_sd, dim = c(length(idx), lookback, 1))

# Construct scaled 20-day trajectory delta targets and binary rise labels
y_dlt_raw &lt;- map(idx, ~ (p[.x + 1:horizon] - p[.x]) * 1000) |&gt; do.call(what = rbind)
d_sd      &lt;- max(sd(y_dlt_raw, na.rm = TRUE), 1e-6)
y_dlt     &lt;- y_dlt_raw / d_sd
y_rise    &lt;- map_dbl(idx, ~ as.numeric(mean(p[.x + 1:horizon]) &gt; p[.x]))

# Define 2-layer Torch LSTM with Softplus activation and direct + delta-aggregated classification logit
crash_net &lt;- nn_module(
  # Initialize 3-channel LSTM, Softplus trajectory head, dense aggregator, and classification head
  initialize = function() {
    self$lstm     &lt;- nn_lstm(3, 64, num_layers = 2, dropout = 0.1, batch_first = TRUE)
    self$head     &lt;- nn_sequential(nn_linear(64, 32), nn_softplus(), nn_linear(32, horizon))
    self$cls_head &lt;- nn_sequential(nn_linear(64 + horizon, 32), nn_softplus(), nn_linear(32, 1))
    self$agg      &lt;- nn_linear(horizon, 1)
    self$log_vars &lt;- nn_parameter(torch_zeros(2))
  },
  # Extract level, diff, and window-centered channels to predict 20-day deltas and rise logit
  forward = function(x) {
    dx     &lt;- torch_cat(list(torch_zeros(c(x$size(1), 1L, x$size(3)), dtype = x$dtype),
                           x[, 2:lookback, , drop = FALSE] - x[, 1:(lookback - 1L), , drop = FALSE]), dim = 2L)
    x_rel  &lt;- x - x$mean(dim = 2L, keepdim = TRUE)
    x_in   &lt;- torch_cat(list(x, dx, x_rel), dim = 3L)
    h_last &lt;- self$lstm(x_in)[[1]][, lookback, ]
    delta  &lt;- self$head(h_last)
    logit  &lt;- self$cls_head(torch_cat(list(h_last, delta), dim = 2L)) + 0.25 * self$agg(delta)
    list(delta = delta, logit = logit)
  }
)

# Train network with AdamW using learned homoscedastic uncertainty weights
train_crash_net &lt;- function(net, x_tensor, d_tensor, b_tensor, y_target, epochs = 50L) {
  opt &lt;- optim_adamw(net$parameters, lr = 0.008, weight_decay = 1e-4)
  y_fac &lt;- factor(y_target, levels = c(0, 1), labels = c(&quot;NO&quot;, &quot;YES&quot;))
  best_score &lt;- -1
  best_state &lt;- NULL

  # Run training epochs with uncertainty-weighted loss and checkpoint best balanced accuracy
  for (ep in seq_len(epochs)) {
    net$train()
    opt$zero_grad()

    out   &lt;- net(x_tensor)
    l_bce &lt;- nnf_binary_cross_entropy_with_logits(out$logit, b_tensor)
    l_mse &lt;- nnf_mse_loss(out$delta, d_tensor)

    loss &lt;- torch_exp(-net$log_vars[1]) * l_bce + net$log_vars[1] +
            torch_exp(-net$log_vars[2]) * l_mse + net$log_vars[2]

    loss$backward()
    opt$step()

    net$eval()
    with_no_grad({
      pr &lt;- as.numeric(torch_sigmoid(net(x_tensor)$logit)$squeeze())
    })
    th &lt;- select_best_threshold(pr, y_target)
    pred_fac &lt;- factor(if_else(pr &gt; th, &quot;YES&quot;, &quot;NO&quot;), levels = c(&quot;NO&quot;, &quot;YES&quot;))
    cur_bal &lt;- yardstick::bal_accuracy_vec(y_fac, pred_fac)
    if (is.finite(cur_bal) &#038;&#038; cur_bal &gt; best_score) {
      best_score &lt;- cur_bal
      best_state &lt;- map(net$state_dict(), ~ .x$clone())
    }
  }

  if (!is.null(best_state)) net$load_state_dict(best_state)
  best_score
}

# Build training tensors, fit the 50-epoch LSTM model, and scale the latest window
net &lt;- crash_net()
x_tr &lt;- torch_tensor(x_arr, dtype = torch_float())
d_tr &lt;- torch_tensor(y_dlt, dtype = torch_float())
b_tr &lt;- torch_tensor(matrix(y_rise, ncol = 1), dtype = torch_float())

best_bal_acc &lt;- train_crash_net(net, x_tr, d_tr, b_tr, y_rise, epochs = 50L)
net$eval()

latest_scaled &lt;- (tail(p, lookback) * 1000 - x_mu) / x_sd

# Generate training probabilities and latest 20-day forward delta/probability forecasts
with_no_grad({
  train_out   &lt;- net(x_tr)
  prob_train  &lt;- as.numeric(torch_sigmoid(train_out$logit)$squeeze())
  latest_in   &lt;- torch_tensor(array(latest_scaled, c(1, lookback, 1)), dtype = torch_float())
  latest_out  &lt;- net(latest_in)
  latest_dlt  &lt;- (as.numeric(latest_out$delta$squeeze()) * d_sd) / 1000
  latest_prob &lt;- as.numeric(torch_sigmoid(latest_out$logit)$item())
})

best_thresh &lt;- select_best_threshold(prob_train, y_rise)

# Assemble training predictions and ground-truth labels for metric evaluation
train_tbl &lt;- tibble(
  truth         = factor(y_rise, levels = c(0, 1), labels = c(&quot;NO&quot;, &quot;YES&quot;)),
  prob_increase = prob_train,
  pred_class    = factor(if_else(prob_increase &gt; best_thresh, &quot;YES&quot;, &quot;NO&quot;), levels = c(&quot;NO&quot;, &quot;YES&quot;))
)

# Define four percentage-based yardstick classification metrics
tail_rise_metrics &lt;- yardstick::metric_set(
  yardstick::accuracy,
  yardstick::bal_accuracy,
  yardstick::sens,
  yardstick::spec
)

options(yardstick.event_first = FALSE)
# Compute percentage metrics on the training set and print confusion matrix and summary table
train_metrics &lt;- train_tbl %&gt;%
  tail_rise_metrics(truth = truth, estimate = pred_class) %&gt;%
  mutate(.estimate = round(.estimate * 100, 1))

print(table(truth = train_tbl$truth, pred = train_tbl$pred_class))
print(train_metrics)

# ============================================================
# 4. 20-DAY FORECAST PLOT (GGTEXT COLORIZED TITLE; CLEAN HOVER)
# ============================================================

# Compute dynamic y-axis bounds around forecast probabilities and threshold
compute_band_limits &lt;- function(probs, thresh) {
  vals &lt;- c(probs, thresh)
  rng &lt;- max(vals, na.rm = TRUE) - min(vals, na.rm = TRUE)
  pad &lt;- max(rng * 0.25, 0.02)
  c(max(0, min(vals, na.rm = TRUE) - pad), min(1, max(vals, na.rm = TRUE) + pad))
}

# Project daily probabilities across the 20-day horizon from aggregated delta weights
with_no_grad({
  w_agg &lt;- as.numeric(net$agg$weight$squeeze())
  b_agg &lt;- as.numeric(net$agg$bias$item())
  daily_logits &lt;- b_agg + horizon * w_agg * ((latest_dlt * 1000) / d_sd)
  daily_probs  &lt;- as.numeric(torch_sigmoid(torch_tensor(daily_logits)))
})

# Build forecast tibble with trader posture labels and HTML hover tooltips
forecast_tbl &lt;- tibble(
  step          = seq_len(horizon),
  date          = max(joint$date) + seq_len(horizon),
  delta_pct     = latest_dlt * 100,
  prob_increase = daily_probs
) %&gt;%
  bind_cols(classify_trader_posture(.$prob_increase, best_thresh)) %&gt;%
  mutate(
    hover_txt = sprintf(
      &quot;&lt;b&gt;Date:&lt;/b&gt; %s (Day +%d)&lt;br&gt;&lt;b&gt;Risk Outlook:&lt;/b&gt; %s&lt;br&gt;&lt;b&gt;20-Day Crash Risk Change:&lt;/b&gt; %+.2f%%&lt;br&gt;&lt;b&gt;Recommended Action:&lt;/b&gt; %s&quot;,
      as.character(date),
      step,
      status,
      delta_pct,
      action
    )
  )

y_lims &lt;- compute_band_limits(forecast_tbl$prob_increase, best_thresh)

ggtext_title &lt;- paste0(
  &quot;BTC-ETH 20-Day Joint Crash Risk: &quot;,
  &quot;&lt;span style=&#039;color:#b22222;&#039;&gt;&lt;b&gt;Red = Hedge / Reduce Leverage&lt;/b&gt;&lt;/span&gt; | &quot;,
  &quot;&lt;span style=&#039;color:#2e7d32;&#039;&gt;&lt;b&gt;Green = Standard Risk&lt;/b&gt;&lt;/span&gt;&quot;
)

# Build shaded ggplot2 forecast trajectory with colored threshold crossing points
g &lt;- ggplot(forecast_tbl, aes(x = date, y = prob_increase)) +
  geom_hline(yintercept = best_thresh, linetype = 2, color = &quot;gray45&quot;) +
  geom_ribbon(aes(ymin = best_thresh, ymax = pmax(prob_increase, best_thresh)), fill = &quot;#b22222&quot;, alpha = 0.22) +
  geom_ribbon(aes(ymin = pmin(prob_increase, best_thresh), ymax = best_thresh), fill = &quot;#2e7d32&quot;, alpha = 0.22) +
  geom_line(aes(group = 1), color = &quot;gray30&quot;, linewidth = 0.7) +
  geom_point(aes(color = color, text = hover_txt), size = 2.6) +
  scale_color_identity() +
  scale_y_continuous(labels = scales::percent_format(accuracy = 0.1), limits = y_lims) +
  theme_minimal() +
  theme(plot.title = element_markdown(size = 12)) +
  labs(
    title = ggtext_title,
    x = NULL,
    y = NULL
  )

# Render interactive plotly chart with custom hover text and clean axes
ggplotly(g, tooltip = &quot;text&quot;) %&gt;%
  layout(
    showlegend = FALSE,
    xaxis = list(title = &quot;&quot;),
    yaxis = list(title = &quot;&quot;)
  )
</pre>
<div style="border: 1px solid; background: none repeat scroll 0 0 #EDEDED; margin: 1px; font-size: 13px;">
<div style="text-align: center;">To <strong>leave a comment</strong> for the author, please follow the link and comment on their blog: <strong><a href="https://datageeek.com/2026/11/30/from-marginal-tail-risk-to-forward-regime-signals-modeling-btc-eth-co-crash-dynamics-with-torch/"> DataGeeek</a></strong>.</div>
<hr />
<a href="https://www.r-bloggers.com/" rel="nofollow">R-bloggers.com</a> offers <strong><a href="https://feedburner.google.com/fb/a/mailverify?uri=RBloggers" rel="nofollow">daily e-mail updates</a></strong> about <a title="The R Project for Statistical Computing" href="https://www.r-project.org/" rel="nofollow">R</a> news and tutorials about <a title="R tutorials" href="https://www.r-bloggers.com/how-to-learn-r-2/" rel="nofollow">learning R</a> and many other topics. <a title="Data science jobs" href="https://www.r-users.com/" rel="nofollow">Click here if you're looking to post or find an R/data-science job</a>.

<hr>Want to share your content on R-bloggers?<a href="https://www.r-bloggers.com/add-your-blog/" rel="nofollow"> click here</a> if you have a blog, or <a href="http://r-posts.com/" rel="nofollow"> here</a> if you don't.
</div><strong>Continue reading</strong>: <a href="https://www.r-bloggers.com/2026/11/from-marginal-tail-risk-to-forward-regime-signals-modeling-btc-eth-co-crash-dynamics-with-torch/">From Marginal Tail Risk to Forward Regime Signals: Modeling BTC-ETH Co-Crash Dynamics with Torch</a>]]></content:encoded>
					
		
		<enclosure url="https://datageeek.com/wp-content/uploads/2026/11/btc-eth-co-crash-dynamics-and-forward-regime-signals-6b0d75e74e748.png" length="0" type="" />
<enclosure url="https://1.gravatar.com/avatar/db5e3f9ef188ea98fe38ab05c5a3fad9fb52fe3472715a8fc02f7ea41731f77c?s=96&#038;d=identicon&#038;r=G" length="0" type="" />
<enclosure url="https://datageeek.com/wp-content/uploads/2026/11/cavier.png?w=1024" length="0" type="" />

		<post-id xmlns="com-wordpress:feed-additions:1">405192</post-id>	</item>
		<item>
		<title>October 2026 Top 40 New CRAN Packages</title>
		<link>https://www.r-bloggers.com/2026/11/october-2026-top-40-new-cran-packages/</link>
		
		<dc:creator><![CDATA[Joseph Rickert]]></dc:creator>
		<pubDate>Sun, 29 Nov 2026 00:00:00 +0000</pubDate>
				<category><![CDATA[R bloggers]]></category>
		<guid isPermaLink="false">https://rworks.dev/posts/oct-2026-top40/</guid>

					<description><![CDATA[<div style = "width:60%; display: inline-block; float:left; ">
<p>Agriculture<br />
fieldopt v0.1.0: Facilitates the design of agricultural and other area-frame and dual-frame (area plus list) sample surveys that go to the field, with the real cost of field work including travel between sampling units plus interv...</p></div>
<div style = "width: 40%; display: inline-block; float:right;"></div>
<div style="clear: both;"></div>
<strong>Continue reading</strong>: <a href="https://www.r-bloggers.com/2026/11/october-2026-top-40-new-cran-packages/">October 2026 Top 40 New CRAN Packages</a>]]></description>
										<content:encoded><![CDATA[<!-- 
<div style="min-height: 30px;">
[social4i size="small" align="align-left"]
</div>
-->

<div style="border: 1px solid; background: none repeat scroll 0 0 #EDEDED; margin: 1px; font-size: 12px;">
[This article was first published on  <strong><a href="https://rworks.dev/posts/oct-2026-top40/"> R Works</a></strong>, and kindly contributed to <a href="https://www.r-bloggers.com/" rel="nofollow">R-bloggers</a>].  (You can report issue about the content on this page <a href="https://www.r-bloggers.com/contact-us/">here</a>)
<hr>Want to share your content on R-bloggers?<a href="https://www.r-bloggers.com/add-your-blog/" rel="nofollow"> click here</a> if you have a blog, or <a href="http://r-posts.com/" rel="nofollow"> here</a> if you don't.
</div>
 





<div class="columns">
<div class="column" style="width:45%;">
<section id="agriculture" class="level3">
<h3 class="anchored" data-anchor-id="agriculture">Agriculture</h3>
<p><a href="https://cran.r-project.org/package=fieldopt" rel="nofollow" target="_blank">fieldopt</a> v0.1.0: Facilitates the design of agricultural and other area-frame and dual-frame (area plus list) sample surveys that go to the field, with the real cost of field work including travel between sampling units plus interviews, next to the variance of the design-based estimator. Includes travel matrices from coordinates or a road network, stratified spatially balanced or spatially ordered systematic selection of segments with interpenetrating replicates, Horvitz-Thompson estimation with local-mean or replicate variances, cost-aware allocation across strata and more. The computational engine is the <code>Rust</code> crate <code>fieldopt-core</code>. There are seven vignettes including <a href="https://cran.r-project.org/web/packages/fieldopt/vignettes/fieldopt.html" rel="nofollow" target="_blank">Get started</a> and <a href="https://cran.r-project.org/web/packages/fieldopt/vignettes/routing-teams.html" rel="nofollow" target="_blank">Routing for one or several teams</a>.</p>
<p><a href="https://i0.wp.com/rworks.dev/posts/oct-2026-top40/fieldopt.png?ssl=1" class="lightbox" data-gallery="quarto-lightbox-gallery-1" rel="nofollow" target="_blank"><img src="https://i0.wp.com/rworks.dev/posts/oct-2026-top40/fieldopt.png?w=578&#038;ssl=1" class="img-fluid" alt="Plot showing routes for two teams" data-recalc-dims="1"></a></p>
</section>
<section id="control-charts" class="level3">
<h3 class="anchored" data-anchor-id="control-charts">Control Charts</h3>
<p><a href="https://cran.r-project.org/package=edetect" rel="nofollow" target="_blank">edetect</a> v0.1.0: Implements sequential change detection for process monitoring with e-detectors <a href="doi:10.51387/23-NEJSDS51" rel="nofollow" target="_blank">Shin, Ramdas and Rinaldo (2024)</a>: nonparametric, anytime-valid analogues of the <a href="https://www.mdpi.com/2075-1680/14/9/713" rel="nofollow" target="_blank">CUSUM and Shiryaev-Roberts</a> charts whose average run length to a false alarm is guaranteed for every distribution in a declared pre-change class (bounded, sub-Gaussian, Bernoulli or Poisson observations). Phase I/Phase II workflow, individual, p, c, u and regression charts, run-length simulation and auditable alarm reports. There are four vignettes including <a href="https://cran.r-project.org/web/packages/edetect/vignettes/edetect.html" rel="nofollow" target="_blank">Get started</a> and <a href="https://cran.r-project.org/web/packages/edetect/vignettes/regression-chart.html" rel="nofollow" target="_blank">Regression chart for non-stationary processes</a>.</p>
<p><a href="https://i0.wp.com/rworks.dev/posts/oct-2026-top40/edetect.png?ssl=1" class="lightbox" data-gallery="quarto-lightbox-gallery-2" rel="nofollow" target="_blank"><img src="https://i0.wp.com/rworks.dev/posts/oct-2026-top40/edetect.png?w=578&#038;ssl=1" class="img-fluid" alt="Plot of control charts with change points" data-recalc-dims="1"></a></p>
</section>
<section id="decision-theory" class="level3">
<h3 class="anchored" data-anchor-id="decision-theory">Decision Theory</h3>
<p><a href="https://cran.r-project.org/package=paretoinfer" rel="nofollow" target="_blank">paretoinfer</a> v0.1.0: Sequential identification of epsilon-Pareto-optimal alternatives among a finite set with noisy, possibly correlated objectives. Simultaneous anytime-valid confidence sequences for every objective of every alternative <a href="doi:10.1093/jrsssb/qkad009" rel="nofollow" target="_blank">Waudby-Smith and Ramdas (2024)</a> certify, at any time, which alternatives are epsilon-dominated and which are not, report the estimated frontier, the plausible Pareto set and the certified-dominated set, propose the next alternative to evaluate, and record an auditable result contract. There are four vignettes including <a href="https://cran.r-project.org/web/packages/paretoinfer/vignettes/paretoinfer.html" rel="nofollow" target="_blank">Get started</a> and <a href="https://cran.r-project.org/web/packages/paretoinfer/vignettes/cost-and-budget.html" rel="nofollow" target="_blank">Heterogeneous cost and budgets</a>.</p>
<p><a href="https://i1.wp.com/rworks.dev/posts/oct-2026-top40/pareto.png?ssl=1" class="lightbox" data-gallery="quarto-lightbox-gallery-3" rel="nofollow" target="_blank"><img src="https://i1.wp.com/rworks.dev/posts/oct-2026-top40/pareto.png?w=578&#038;ssl=1" class="img-fluid" alt="Plot showing most plausible alternatives" data-recalc-dims="1"></a></p>
</section>
<section id="environmental-studies" class="level3">
<h3 class="anchored" data-anchor-id="environmental-studies">Environmental Studies</h3>
<p><a href="https://cran.r-project.org/package=EnvRtype" rel="nofollow" target="_blank">EnvRtype</a> 0.1.3: Provides an enviromics toolkit for genotype-by-environment analysis and envirotype-informed genomic prediction. Collects worldwide daily and hourly weather data, soil profiles, elevation and bioclimatic layers data, agro-ecological zone data, and downscaled climate scenarios, with checkpointed retrieval that can resume after an interrupted run. Derives agro-meteorological parameters and maps daily weather onto crop developmental stages. Fits Bayesian reaction-norm kernel models and predicts trained genotypes at untested locations and planting dates, with coverage diagnostics, spatial mapping and planting-window optimization. Methods are described in <a href="doi:10.1093/g3journal/jkab040" rel="nofollow" target="_blank">Costa-Neto et al. (2021)</a>, and build on the Bayesian genotype-by-environment kernel sampler of <a href="doi:10.1534/g3.118.200435" rel="nofollow" target="_blank">Granato et al(2018)</a>. See the <a href="https://cran.r-project.org/web/packages/EnvRtype/vignettes/EnvRtype.html" rel="nofollow" target="_blank">vignette</a>.</p>
<p><a href="https://i1.wp.com/rworks.dev/posts/oct-2026-top40/EnvRtype.png?ssl=1" class="lightbox" data-gallery="quarto-lightbox-gallery-4" rel="nofollow" target="_blank"><img src="https://i1.wp.com/rworks.dev/posts/oct-2026-top40/EnvRtype.png?w=578&#038;ssl=1" class="img-fluid" alt="Heat map of correlation among environmental incdices" data-recalc-dims="1"></a></p>
<p><a href="https://cran.r-project.org/package=ET0MassModels" rel="nofollow" target="_blank">ET0MassModels</a> v1.0.0: Provides functions to estimate daily reference evapotranspiration using 10 mass transfer-based empirical models, with the <a href="https://en.wikipedia.org/wiki/Penman%E2%80%93Monteith_equation" rel="nofollow" target="_blank">Food and Agriculture Organization Penman-Monteith</a> method included as the standard reference for model comparison. Includes statistical evaluation metrics, such as Nash-Sutcliffe efficiency, root mean square error, mean absolute error, and mean bias error, and visualization tools. Based on <a href="doi:10.1016/j.ejrh.2026.103925" rel="nofollow" target="_blank">Singh et al. (2026)</a>. See the <a href="https://cran.r-project.org/web/packages/ET0MassModels/vignettes/introduction.html" rel="nofollow" target="_blank">vignette</a>.</p>
<p><a href="https://i2.wp.com/rworks.dev/posts/oct-2026-top40/ET0.png?ssl=1" class="lightbox" data-gallery="quarto-lightbox-gallery-5" rel="nofollow" target="_blank"><img src="https://i2.wp.com/rworks.dev/posts/oct-2026-top40/ET0.png?w=578&#038;ssl=1" class="img-fluid" alt="Taylor diagram - Mass Transfer-Based Models" data-recalc-dims="1"></a></p>
</section>
<section id="ecology" class="level3">
<h3 class="anchored" data-anchor-id="ecology">Ecology</h3>
<p><a href="https://cran.r-project.org/package=aquats" rel="nofollow" target="_blank">aquats</a> v1.2.2: Implements a comprehensive statistical and visualization toolkit tailored for observational data in fisheries science and aquatic ecology. Provides ANOVA, ANCOVA, MANOVA, permutational multivariate analysis of variance, similarity percentages, generalized linear models, non-linear morphometric regressions, two-group hypothesis testing, and chi-square tests. Methodological formulations for multivariate permutation tests follow <a href="oi:10.1111/j.1442-9993.2001.01070.pp.x" rel="nofollow" target="_blank">Anderson (2001)</a>. Ecological community dissimilarity transformations follow <a href="doi:10.1007/s004420100716" rel="nofollow" target="_blank">Legendre and Gallagher (2001)</a>, and ecotoxicological contamination index models follow <a href="doi:10.1007/BF02414780" rel="nofollow" target="_blank">Tomlinson et al. (1980)</a>. See the <a href="https://cran.r-project.org/web/packages/aquats/vignettes/aquats-tutorial.html" rel="nofollow" target="_blank">vignette</a> for examples.</p>
<p><a href="https://i1.wp.com/rworks.dev/posts/oct-2026-top40/aquats.png?ssl=1" class="lightbox" data-gallery="quarto-lightbox-gallery-6" rel="nofollow" target="_blank"><img src="https://i1.wp.com/rworks.dev/posts/oct-2026-top40/aquats.png?w=578&#038;ssl=1" class="img-fluid" alt="ANOVA plots" data-recalc-dims="1"></a></p>
<p><a href="https://cran.r-project.org/package=b3gbi" rel="nofollow" target="_blank">b3gbi</a> v1.1.3: Calculate general biodiversity indicators from species occurrence cubes, such as those produced by the Global Biodiversity Information Facility <a href="https://techdocs.gbif.org/en/data-use/data-cubes" rel="nofollow" target="_blank">occurrence cube service</a>. Indicators include observed and coverage-based rarefied species richness and Hill numbers, evenness, rarity, taxonomic distinctness, occupancy, turnover and sample completeness, and can be calculated over time or space, with bootstrap confidence intervals. For details see <a href="doi:10.21105/joss.10963" rel="nofollow" target="_blank">Dove (2026)</a>. See the vignettes <a href="https://cran.r-project.org/web/packages/b3gbi/vignettes/b3gbi.html" rel="nofollow" target="_blank">A Gentle Introduction</a> and <a href="https://cran.r-project.org/web/packages/b3gbi/vignettes/uncertainty.html" rel="nofollow" target="_blank">Uncertainty in Biodiversity Indicators</a>.</p>
<p><a href="https://i0.wp.com/rworks.dev/posts/oct-2026-top40/b3gbi.png?ssl=1" class="lightbox" data-gallery="quarto-lightbox-gallery-7" rel="nofollow" target="_blank"><img src="https://i0.wp.com/rworks.dev/posts/oct-2026-top40/b3gbi.png?w=578&#038;ssl=1" class="img-fluid" alt="Map of observed mammal richness" data-recalc-dims="1"></a></p>
<p><a href="https://cran.r-project.org/package=flexsdm" rel="nofollow" target="_blank">flexsdm</a> v1.4.2: Provides a flexible and comprehensive workflow for species distribution modeling, from data preparation to model fitting, tuning, evaluation, prediction, ensemble modeling, and post-processing. The package is described in <a href="doi:10.1111/2041-210X.1387" rel="nofollow" target="_blank">Velazco et al. (2022)</a>. Implemented methods include the Shape metric to measure model extrapolation of <a href="doi:10.1111/ecog.06992" rel="nofollow" target="_blank">Velazco et al. (2023)</a>, ensembles of small models of <a href="doi:10.1111/2041-210X.12403" rel="nofollow" target="_blank">Breiner et al. (2015)</a>, Gaussian process models of <a href="doi:10.1111/2041-210X.12523" rel="nofollow" target="_blank">Golding and Purse (2016)</a>, and occurrence-based constraints for post-processing predictions of <a href="doi:10.1016/j.ecolmodel.2020.109180" rel="nofollow" target="_blank">Mendes et al. (2020)</a>. There are eight vignettes including <a href="https://cran.r-project.org/web/packages/flexsdm/vignettes/v02_modeling.html" rel="nofollow" target="_blank">Overview of Modeling functions</a> and <a href="https://cran.r-project.org/web/packages/flexsdm/vignettes/v04_Red_fir_example.html" rel="nofollow" target="_blank">Red Fir example</a>.</p>
<p><a href="https://i2.wp.com/rworks.dev/posts/oct-2026-top40/flexsdm.png?ssl=1" class="lightbox" data-gallery="quarto-lightbox-gallery-8" rel="nofollow" target="_blank"><img src="https://i2.wp.com/rworks.dev/posts/oct-2026-top40/flexsdm.png?w=578&#038;ssl=1" class="img-fluid" alt="Map with pseudo-absence background points" data-recalc-dims="1"></a></p>
<p><a href="https://cran.r-project.org/package=soilcnn" rel="nofollow" target="_blank">soilcnn</a> v0.1.0: Implements a framework, built on <code>torch</code>, for mapping a soil property from point observations and a stack of aligned rasters with a convolutional network that reads the neighborhood of each point. It extracts the patches; resamples by spatial blocks or by k-fold nearest neighbor distance matching, after <a href="doi:10.5194/gmd-17-5897-2024" rel="nofollow" target="_blank">Linnenbrink et al. (2024)</a>; tunes and selects under a noise floor and the one-standard-error rule; refits the selected configuration under several seeds; and predicts median, mean and interval maps over rasters of any extent. The map’s center is the ensemble median over seeds; the mean corrects its back-transformation by smearing, after <a href="doi:10.1080/01621459.1983.10478017" rel="nofollow" target="_blank">Duan (1983)</a>. See the <a href="https://cran.r-project.org/web/packages/soilcnn/vignettes/soilcnn.html" rel="nofollow" target="_blank">vignette</a> to get started.</p>
<p><a href="https://i1.wp.com/rworks.dev/posts/oct-2026-top40/soilcnn.png?ssl=1" class="lightbox" data-gallery="quarto-lightbox-gallery-9" rel="nofollow" target="_blank"><img src="https://i1.wp.com/rworks.dev/posts/oct-2026-top40/soilcnn.png?w=578&#038;ssl=1" class="img-fluid" alt="Plot illustrating validation geometry" data-recalc-dims="1"></a></p>
</section>
<section id="epidemiology" class="level3">
<h3 class="anchored" data-anchor-id="epidemiology">Epidemiology</h3>
<p><a href="https://cran.r-project.org/package=epidist" rel="nofollow" target="_blank">epidist</a> v1.0.0: Provides methods to address the key challenges in estimating epidemiological delay distributions which influence epidemic situational awareness, control strategies, and resource allocation. Includes truncation, interval censoring, and dynamical biases, following <a href="doi:10.1101/2024.01.12.24301247" rel="nofollow" target="_blank">Park et al. (2024)</a> and <a href="doi:10.1371/journal.pcbi.1012520" rel="nofollow" target="_blank">Charniga et al. (2024)</a>. Built on top of <code>brms</code>, functions allow for flexible modelling including time-varying and spatial effects and partially pooled estimates of demographic characteristics. There are nine vignettes including <a href="https://cran.r-project.org/web/packages/epidist/vignettes/epidist.html" rel="nofollow" target="_blank">Getting started</a> and <a href="https://cran.r-project.org/web/packages/epidist/vignettes/model.html" rel="nofollow" target="_blank">Model Guide</a>.</p>
<p><a href="https://i2.wp.com/rworks.dev/posts/oct-2026-top40/epidist.png?ssl=1" class="lightbox" data-gallery="quarto-lightbox-gallery-10" rel="nofollow" target="_blank"><img src="https://i2.wp.com/rworks.dev/posts/oct-2026-top40/epidist.png?w=578&#038;ssl=1" class="img-fluid" alt="Plots of true value and estimates distributions" data-recalc-dims="1"></a></p>
</section>
<section id="finance" class="level3">
<h3 class="anchored" data-anchor-id="finance">Finance</h3>
<p><a href="https://cran.r-project.org/package=qdfauction" rel="nofollow" target="_blank">qdfauction</a> v0.3.0: Provides nonparametric estimators of the quantile density function: kernel, boundary-corrected kernel, Poisson-weight and Bernstein-polynomial smoothers, indirect estimators, and linear, hard-thresholded and block-thresholded wavelet estimators with smoothing parameters chosen by biased, robust likelihood or least-squares cross-validation. The estimators are applied to the structural analysis of first-price sealed-bid auctions: recovery of private values for independent or affiliated values and risk-neutral or risk-averse bidders. See <a href="https://www.ism.ac.jp/editsec/aism/pdf/044_4_0721.pdf" rel="nofollow" target="_blank">Jones (1992)</a>, <a href="doi:10.1016/j.csda.2012.04.014" rel="nofollow" target="_blank">Soni, Dewan and Jain (2012)</a>, and <a href="doi:10.1080/03610926.2023.2222922" rel="nofollow" target="_blank">Chaubey, Dewan and Li (2024)</a> for background and the <a href="https://cran.r-project.org/web/packages/qdfauction/vignettes/timber.html" rel="nofollow" target="_blank">vignette</a> for examples.</p>
<p><a href="https://i1.wp.com/rworks.dev/posts/oct-2026-top40/qdfauction.png?ssl=1" class="lightbox" data-gallery="quarto-lightbox-gallery-11" rel="nofollow" target="_blank"><img src="https://i1.wp.com/rworks.dev/posts/oct-2026-top40/qdfauction.png?w=578&#038;ssl=1" class="img-fluid" alt="Plot of quantile estimates of bids" data-recalc-dims="1"></a></p>
<p><a href="https://cran.r-project.org/package=scorecraft" rel="nofollow" target="_blank">OptimalBinningWoE</a> v0.3.2: Builds points scorecards for binary targets (credit risk, fraud, propensity) based on an optimal binning and weight of evidence engine. Variables are selected through optimal binning, eight admission rules, hold-out re-validation with frozen bins and a consensus of <code>glmnet</code>, <code>xgboost</code>, <code>lightgbm</code> and <code>ranger</code> models. The scorecard is fitted with an explicit, auditable scale alignment. Population and characteristic stability indices are monitored with both the fixed and the sample-size-adjusted threshold. Functions compute expected loss, risk weights, regulatory capital and expected credit loss from parameter tables selected by framework preset. The heavy numeric kernels are compiled with <code>RcppArmadillo</code>. The scorecard methodology follows <a href="doi:10.1002/9781119282396" rel="nofollow" target="_blank">Siddiqi (2017)</a> and <a href="doi:10.1137/1.9781611974560" rel="nofollow" target="_blank">Thomas et al. (2017)</a>. There are four vignettes including <a href="https://cran.r-project.org/web/packages/scorecraft/vignettes/score-studies.html" rel="nofollow" target="_blank">Score studies</a> and <a href="https://cran.r-project.org/web/packages/scorecraft/vignettes/alignment-and-portfolio.html" rel="nofollow" target="_blank">Scaling, alignment and challengers</a>.</p>
</section>
<section id="genomics" class="level3">
<h3 class="anchored" data-anchor-id="genomics">Genomics</h3>
<p><a href="https://cran.r-project.org/package=shaman" rel="nofollow" target="_blank">shaman</a> v2.1.1: Generate expected Hi-C (genome-wide chromosome conformation capture) data maintaining marginal coverage, and the decay in contact probability with increasing genomic distance. Expected Hi-C data is used for normalization and graphical presentation of statistical significance of observed Hi-C contact enrichments. The method is described in <a href="doi:10.1101/187203" rel="nofollow" target="_blank">Mendelson Cohen et al. (2017)</a>. See the vignettes <a href="https://cran.r-project.org/web/packages/shaman/vignettes/shaman-package.html" rel="nofollow" target="_blank">Sampling HiC contAct Matrices for Aparametric Normalization</a>] and <a href="https://rworks.dev/posts/oct-2026-top40/" rel="nofollow" target="_blank">Import</a>.</p>
<p><a href="https://i1.wp.com/rworks.dev/posts/oct-2026-top40/shaman.png?ssl=1" class="lightbox" data-gallery="quarto-lightbox-gallery-12" rel="nofollow" target="_blank"><img src="https://i1.wp.com/rworks.dev/posts/oct-2026-top40/shaman.png?w=578&#038;ssl=1" class="img-fluid" alt="visualization of region with scores" data-recalc-dims="1"></a></p>
</section>
<section id="machine-learning" class="level3">
<h3 class="anchored" data-anchor-id="machine-learning">Machine Learning</h3>
<p><a href="https://cran.r-project.org/package=fullmetaphone" rel="nofollow" target="_blank">fullmetaphone</a> v0.1.0: Encodes names and words as phonetic codes, so that names which sound alike but are spelled differently can be matched. Implements the Metaphone algorithm published by Lawrence Philips in a 1990 issue of Computer Language magazine and the Double Metaphone algorithm of <a href="https://web.archive.org/web/20250702064845/https://drdobbs.com/the-double-metaphone-search-algorithm/184401251" rel="nofollow" target="_blank">Philips (2000)</a>, which gives a primary and an alternate code for names of many language origins. Unlike most implementations, including <code>PGRdup</code>, the codes are not cut to four characters, which keeps long and multi-part names apart. Provides functions for record linkage, deduplication and name search, and includes a data set of common United States surnames. See the <a href="https://cran.r-project.org/web/packages/fullmetaphone/vignettes/fullmetaphone.html" rel="nofollow" target="_blank">vignette</a>.</p>
<p><a href="https://cran.r-project.org/package=gaussianprocesses" rel="nofollow" target="_blank">gaussianprocesses</a> v1.0.0: Gaussian process regression, classification, and count models with explicit covariance kernels, exact Gaussian inference, Laplace approximations for non-Gaussian likelihoods, sparse approximations, marginal-likelihood optimization, derivatives, posterior sampling, calibration diagnostics, and time-series workflows. The implementation follows the core methodology of <a href="doi:10.7551/mitpress/3206.001.0001" rel="nofollow" target="_blank">Rasmussen and Williams (2006)</a> and emphasizes numerical stability, transparent assumptions, and reproducible statistical workflows. There are seven vignettes including <a href="https://cran.r-project.org/web/packages/gaussianprocesses/vignettes/v01-gp-regression.html" rel="nofollow" target="_blank">Gaussian-Process Regression from First Principles</a> and <a href="https://cran.r-project.org/web/packages/gaussianprocesses/vignettes/v06-time-series.html" rel="nofollow" target="_blank">Gaussian Processes for Time Series</a>.</p>
<p><a href="https://i2.wp.com/rworks.dev/posts/oct-2026-top40/gaussianprocesses.png?ssl=1" class="lightbox" data-gallery="quarto-lightbox-gallery-13" rel="nofollow" target="_blank"><img src="https://i2.wp.com/rworks.dev/posts/oct-2026-top40/gaussianprocesses.png?w=578&#038;ssl=1" class="img-fluid" alt="Prior and posterior draws for GP regression" data-recalc-dims="1"></a></p>
<p><a href="https://cran.r-project.org/package=sbert" rel="nofollow" target="_blank">sbert</a> v0.6.0: Builds semantic topic models from <code>Sentence-BERT</code> embeddings <a href="doi:10.18653/v1/D19-1410" rel="nofollow" target="_blank">Reimers and Gurevych, (2019)</a>. Sentence embeddings are computed in several modes with models run on the Open Neural Network Exchange Run time, including multilingual and long-context encoders and a fast static model. Topics are labeled with class-based term weighting that can be retuned without refitting. Candidate topic counts and document granularities (whole documents, sentences, clauses, or phrases) can be compared side by side, and fitted models assign topics to new documents, give soft memberships and per-document topic mixtures. The package offers coherence and diversity metrics and visualizations. see the vignettes <a href="https://cran.r-project.org/web/packages/sbert/vignettes/embeddings.html" rel="nofollow" target="_blank">Sentence embeddings without Python</a> and <a href="https://cran.r-project.org/web/packages/sbert/vignettes/sbert.html" rel="nofollow" target="_blank">Semantic topic modeling with Sentence-BERT</a>.</p>
<p><a href="https://i2.wp.com/rworks.dev/posts/oct-2026-top40/sbert.png?ssl=1" class="lightbox" data-gallery="quarto-lightbox-gallery-14" rel="nofollow" target="_blank"><img src="https://i2.wp.com/rworks.dev/posts/oct-2026-top40/sbert.png?w=578&#038;ssl=1" class="img-fluid" alt="Topic-count comparison plots" data-recalc-dims="1"></a></p>
<p><a href="https://cran.r-project.org/package=SWORD" rel="nofollow" target="_blank">SWORD</a> v0.1.0: Implements SWORD (Support vector machine Weighted Oblique Random Decision forests), a random forest method for regression based on TORS (Tree Oblique for Regression with weighted SVM) oblique regression trees. At each internal node a Weighted-SVM classifier with a linear kernel defines the oblique splitting hyperplane as a sparse linear combination of predictors. The <code>C++</code> coordinate-descent solver provides fast training. The TORS algorithm is described in <a href="doi:10.1007/s00180-025-01647-w" rel="nofollow" target="_blank">Carta and Frigau (2025)</a>. The weighted SVM is based on <a href="doi:10.1109/IJCNN.2005.1555965" rel="nofollow" target="_blank">Yang, Song and Cao (2005)</a> and the <code>WeightSVM</code> package. See the <a href="https://cran.r-project.org/web/packages/SWORD/vignettes/intro-sword.html" rel="nofollow" target="_blank">vignette</a></p>
<p><a href="https://i2.wp.com/rworks.dev/posts/oct-2026-top40/SWORD.png?ssl=1" class="lightbox" data-gallery="quarto-lightbox-gallery-15" rel="nofollow" target="_blank"><img src="https://i2.wp.com/rworks.dev/posts/oct-2026-top40/SWORD.png?w=578&#038;ssl=1" class="img-fluid" alt="SWORD decision forest" data-recalc-dims="1"></a></p>
</section>
<section id="mathematics" class="level3">
<h3 class="anchored" data-anchor-id="mathematics">Mathematics</h3>
<p><a href="https://cran.r-project.org/package=DistributionalDDA" rel="nofollow" target="_blank">DistributionalDDA</a> v0.1.1: Enables statistical analysis of data sets whose observations are whole probability distributions, using Bayes space calculus. Distributions (provided as samples, histograms or density functions) are treated as elements of a Hilbert space, so that operations such as mean, variance, distance, principal component analysis and clustering carry over to densities. Reference measures defining the geometry of the space can be chosen and combined. The methodology was first published with peer review by van den <a href="doi:10.1111/anzs.12074" rel="nofollow" target="_blank">Boogaart, Egozcue and Pawlowsky-Glahn (2014)</a>. See the vignettes <a href="https://cran.r-project.org/web/packages/DistributionalDDA/vignettes/DistributionalDDA.html" rel="nofollow" target="_blank">How to</a> and <a href="https://cran.r-project.org/web/packages/DistributionalDDA/vignettes/PCA_distributional_data.html" rel="nofollow" target="_blank">PCA for Distributional Data</a>.</p>
<p><a href="https://i2.wp.com/rworks.dev/posts/oct-2026-top40/DDA.png?ssl=1" class="lightbox" data-gallery="quarto-lightbox-gallery-16" rel="nofollow" target="_blank"><img src="https://i2.wp.com/rworks.dev/posts/oct-2026-top40/DDA.png?w=578&#038;ssl=1" class="img-fluid" alt="Plot of Distributions by Sex" data-recalc-dims="1"></a></p>
<p><a href="https://cran.r-project.org/package=sundials" rel="nofollow" target="_blank">sundials</a> v7.9.0-1: Bundles the pure-C part of the <code>SUNDIALS</code> suite (CVODE, CVODES, ARKODE, IDA, IDAS and KINSOL with the serial vector and the dense, band and iterative linear solvers) and builds it into a static library. <code>SUNDIALS</code> is described in <a href="doi:10.1145/1089014.1089020" rel="nofollow" target="_blank">Hindmarsh et al. (2005)</a>. Look <a href="https://computing.llnl.gov/projects/sundials" rel="nofollow" target="_blank">here</a> for documentation.</p>
</section>
</div><div class="column" style="width:10%;">

</div><div class="column" style="width:45%;">
<section id="medical-statistics" class="level3">
<h3 class="anchored" data-anchor-id="medical-statistics">Medical Statistics</h3>
<p><a href="https://cran.r-project.org/package=mirrorslope" rel="nofollow" target="_blank">mirrorslope</a> 0.2.1: Creates mirrored slope plots comparing two treatment arms over a single observation interval. Both arms share a common x-axis and converge at a central endpoint, making the between-arm gap the primary visual quantity. Returns standard <code>ggplot2</code> objects for full extensibility. The display was designed by Kati Maharry and was first used in the supplementary appendix of <a href="doi:10.1016/S0140-6736(26)01385-1" rel="nofollow" target="_blank">McDonald and colleagues (2026)</a>. There are three vignettes including <a href="https://cran.r-project.org/web/packages/mirrorslope/vignettes/introduction.html" rel="nofollow" target="_blank">Introduction</a> and <a href="https://cran.r-project.org/web/packages/mirrorslope/vignettes/clinical-workflow.html" rel="nofollow" target="_blank">Clinical workflow with ADaM data</a>.</p>
<p><a href="https://i2.wp.com/rworks.dev/posts/oct-2026-top40/mirrorslope.png?ssl=1" class="lightbox" data-gallery="quarto-lightbox-gallery-17" rel="nofollow" target="_blank"><img src="https://i2.wp.com/rworks.dev/posts/oct-2026-top40/mirrorslope.png?w=578&#038;ssl=1" class="img-fluid" alt="Example of a mirrorslope plot" data-recalc-dims="1"></a></p>
<p><a href="https://cran.r-project.org/package=PDRobust" rel="nofollow" target="_blank">PDRobust</a> v0.3.8: Implements principal-stratification methods for estimating time-specific and pooled heterogeneous treatment effects in longitudinal studies where outcomes may be truncated by death. Supports continuous and binary outcomes, explicit data validation and standardization, and covariate-dependent treatment effects. Fits propensity-score, principal-score, and outcome models and provides subject-level bootstrap inference, covariate-balance diagnostics, principal-stratum summaries, treatment-group-specific survival odds ratios, and outcome-noise sensitivity analysis. Methodological background is provided in <a href="doi:10.48550/arXiv.2608.06654" rel="nofollow" target="_blank">Zhang et al. (2006)</a>. There are seven vignettes including <a href="https://cran.r-project.org/web/packages/PDRobust/vignettes/diagnostics-profiling-sensitivity.html" rel="nofollow" target="_blank">Diagnostics, profiling, and sensitivity analysis</a> and <a href="https://cran.r-project.org/web/packages/PDRobust/vignettes/method-and-coding.html" rel="nofollow" target="_blank">Treatment coding and interpretation</a>.</p>
<p><a href="https://i2.wp.com/rworks.dev/posts/oct-2026-top40/PDRobust.png?ssl=1" class="lightbox" data-gallery="quarto-lightbox-gallery-18" rel="nofollow" target="_blank"><img src="https://i2.wp.com/rworks.dev/posts/oct-2026-top40/PDRobust.png?w=578&#038;ssl=1" class="img-fluid" alt="Sensitivity cuves" data-recalc-dims="1"></a></p>
<p><a href="https://cran.r-project.org/package=PheValuator" rel="nofollow" target="_blank">PheValuator</a> v2.2.19: Evaluates phenotype algorithms by developing a diagnostic prediction model using a set of noisy positives and noisy negatives. It can then apply the model to a large cohort to create a set of subjects each with a predicted probability for the health outcome of interest. This cohort can then be used to evaluate phenotype algorithms through the calculation of the necessary performance characteristics: sensitivity, specificity, and positive and negative predictive value. Based on work by <a href="doi:10.1016/j.jbi.2022.104177" rel="nofollow" target="_blank">Swerdel (2022)</a> and <a href="doi:10.1016/j.jbi.2019.103258" rel="nofollow" target="_blank">Swerdel (2019)</a>. See the <a href="https://cran.r-project.org/web/packages/PheValuator/vignettes/EvaluatingPhenotypeAlgorithms.pdf" rel="nofollow" target="_blank">vignette</a>.</p>
</section>
<section id="probability" class="level3">
<h3 class="anchored" data-anchor-id="probability">Probability</h3>
<p><a href="https://cran.r-project.org/package=BiasedMatch" rel="nofollow" target="_blank">BiasedMatch</a> v0.1.0: Provides tools for the two-urn biased sampling problems of <a href="doi:10.1080/03610926.2017.1300282" rel="nofollow" target="_blank">Puza and Bonfrer (2018)</a>. Two overlapping sets of items are sampled without replacement, with items common to both sets given a selection weight favoring their inclusion. Functions compute the probability mass function, mean and variance of the number of matching items using the univariate and bivariate Wallenius’ non-central hypergeometric distributions, perform maximum likelihood and Bayesian inference for the bias parameter, and provide Metropolis-Hastings algorithms for hierarchical extensions. See the <a href="https://cran.r-project.org/web/packages/BiasedMatch/vignettes/biasedmatch.html" rel="nofollow" target="_blank">vignette</a>.</p>
</section>
<section id="public-health" class="level3">
<h3 class="anchored" data-anchor-id="public-health">Public Health</h3>
<p><a href="https://cran.r-project.org/package=mudnester" rel="nofollow" target="_blank">mudnester</a> v0.7.8: Clean, prepare, and aggregate surveillance data for public health analysis. Provides structural data cleaning and standardization, age categorization against ~50 published schemes with publication-ready labeling, time-unit aggregation with zero-filling and seasonal awareness, joint aggregation of several linked event dates into one table of comparable rate columns, under-ascertainment correction via a stratified, time-varying multiplier factor supplied directly, comorbidity detection from ICD-10-AM clinical coding, vaccine coverage data construction, hash-based de-identification, and relinking of previously de-identified data. Built for Australian public health surveillance practice but not specific to it. There are eleven vignettes including <a href="https://cran.r-project.org/web/packages/mudnester/vignettes/mudnester-getting-started.html" rel="nofollow" target="_blank">Getting starte</a> and <a href="https://cran.r-project.org/web/packages/mudnester/vignettes/brood.html" rel="nofollow" target="_blank">Vaccine Coverage Data Structures</a>.</p>
</section>
<section id="statistics" class="level3">
<h3 class="anchored" data-anchor-id="statistics">Statistics</h3>
<p><a href="https://cran.r-project.org/package=ballast" rel="nofollow" target="_blank">ballast</a> v0.7.4: Refits one pre-specified mixed model for repeated measures under families of data and analytic perturbations and judges every refit against the pre-specified estimate, confidence interval and p-value. Classifies the result as robust, sensitive or fragile, with a separate flag for marginal significance, and estimates by simulating the probability that a planned design gives a significant and robust result. Fitting uses <code>mmrm</code> with <code>SAS</code> <code>PROC MIXED</code> conventions for the least-squares-mean contrast, Kenward-Roger adjustment and the corrected Akaike criterion. Reference-based multiple imputation follows <a href="doi:10.1080/10543406.2013.8349110" rel="nofollow" target="_blank">Carpenter, Roger and Kenward (2013)</a> and was checked against <code>rbmi</code> <a href="doi:10.21105/joss.04251" rel="nofollow" target="_blank">Gower-Page, Noci and Wolbers (2022)</a>. There are six vignettes including <a href="https://cran.r-project.org/web/packages/ballast/vignettes/quickstart.html" rel="nofollow" target="_blank">Quickstart</a> and <a href="https://cran.r-project.org/web/packages/ballast/vignettes/interpreting.html" rel="nofollow" target="_blank">Interpreting the verdict</a>.</p>
<p><a href="https://cran.r-project.org/package=bartisan" rel="nofollow" target="_blank">bartisan</a> v0.1.0: Fits Bayesian additive regression trees (BART) models for likelihoods outside the conditionally conjugate Gaussian case using the Laplace-approximation reversible-jump sampler of <a href="doi:10.1080/01621459.2024.2337156" rel="nofollow" target="_blank">Linero (2025)</a>. Supported response families include Gaussian, binomial, Poisson, negative binomial, gamma, beta, ordered beta, ordinal, multinomial, zero-inflated counts, a Tweedie compound Poisson for a non-negative response with a point mass at zero, accelerated failure time and proportional hazards models for right-censored survival data, location-scale regression, and a Dirichlet process mixture for the error distribution. Decision rules may be hard, as in standard BART, or soft, as in the SoftBart model of <a href="doi:10.1111/rssb.12293" rel="nofollow" target="_blank">Linero and Yang (2018)</a>, which yields smoother fits. There are eleven vignettes including <a href="https://cran.r-project.org/web/packages/bartisan/vignettes/bartisan.html" rel="nofollow" target="_blank">Getting Started</a> and <a href="https://cran.r-project.org/web/packages/bartisan/vignettes/implementation.html" rel="nofollow" target="_blank">Generalized BART</a>.</p>
<p><a href="https://i2.wp.com/rworks.dev/posts/oct-2026-top40/bartisan.png?ssl=1" class="lightbox" data-gallery="quarto-lightbox-gallery-19" rel="nofollow" target="_blank"><img src="https://i2.wp.com/rworks.dev/posts/oct-2026-top40/bartisan.png?w=578&#038;ssl=1" class="img-fluid" alt="Plot P(death) vs Mean arterial BP" data-recalc-dims="1"></a></p>
<p><a href="https://cran.r-project.org/package=INLAcircular" rel="nofollow" target="_blank">INLAcircular</a> v1.0.0: Provides a Bayesian regression framework for joint models with circular responses and covariates using integrated nested Laplace approximations, following <a href="doi:10.48550/arXiv.2602.08413" rel="nofollow" target="_blank">Ye, Van Niekerk and Rue (2026)</a>. The package supports link-adjusted von Mises likelihoods, shared latent predictors, structured latent effects, and optional LKJ-based multivariate covariance models. It also provides compiled circular densities and d/p/q/r penalized-complexity priors for von Mises, cardioid, and wrapped Cauchy concentration parameters as developed by <a href="doi:10.1177/1471082X261453677" rel="nofollow" target="_blank">Ye, Van Niekerk and Rue (2026)</a>. See the <a href="https://cran.r-project.org/web/packages/INLAcircular/vignettes/INLAcircular-guide.html" rel="nofollow" target="_blank">vignette</a>.</p>
<p><a href="https://i0.wp.com/rworks.dev/posts/oct-2026-top40/INLAc.png?ssl=1" class="lightbox" data-gallery="quarto-lightbox-gallery-20" rel="nofollow" target="_blank"><img src="https://i0.wp.com/rworks.dev/posts/oct-2026-top40/INLAc.png?w=578&#038;ssl=1" class="img-fluid" alt="Plot of 3 circular density families with mean direction 0" data-recalc-dims="1"></a></p>
<p><a href="https://cran.r-project.org/package=lande" rel="nofollow" target="_blank">lande</a> v0.1.0: Estimates selection differentials and linear, quadratic and correlational selection gradients on relative fitness following <a href="doi:10.1111/j.1558-5646.1983.tb00236.x" rel="nofollow" target="_blank">Lande and Arnold (1983)</a>, with p-values from the logistic model for survival and from a Poisson or negative binomial model for counts. Fits cubic spline fitness functions as in <a href="doi:10.1111/j.1558-5646.1988.tb02507.x" rel="nofollow" target="_blank">Schluter (1988)</a> and two-trait fitness surfaces drawn only where there are data, and computes adaptive landscapes of mean fitness against the population mean for one or two traits, by period and for several groups on one surface. Includes bootstrap intervals, a combined results table and a <code>Shiny</code> app. See the <a href="https://cran.r-project.org/web/packages/lande/vignettes/evolutionary-selection-analysis.html" rel="nofollow" target="_blank">vignette</a>.</p>
<p><a href="https://i2.wp.com/rworks.dev/posts/oct-2026-top40/lande.png?ssl=1" class="lightbox" data-gallery="quarto-lightbox-gallery-21" rel="nofollow" target="_blank"><img src="https://i2.wp.com/rworks.dev/posts/oct-2026-top40/lande.png?w=578&#038;ssl=1" class="img-fluid" alt="Plot of a correlated fitness surface" data-recalc-dims="1"></a></p>
<p><a href="https://cran.r-project.org/package=lassoinf" rel="nofollow" target="_blank">lassoinf</a> v0.1.0: Provides confidence intervals and p-values for parameters chosen by the randomized lasso. Implements the polyhedral approach of <a href="doi:10.1214/15-AOS1371" rel="nofollow" target="_blank">Lee et al. (2016)</a>, the randomized response of <a href="doi:10.1214/17-AOS1564" rel="nofollow" target="_blank">Tian and Taylor (2018)</a> and the exact randomized inference of <a href="doi:10.1093/biomet/asae019" rel="nofollow" target="_blank">Panigrahi, Fry and Taylor (2024)</a>, with the truncated bivariate normal computations of <a href="doi:10.48550/arXiv.2308.10346" rel="nofollow" target="_blank">Liu (2023)</a>. Includes inference for user-specified estimands, screening of inactive variables and problems fitted by <code>glmnet</code>. Computations use a <code>C++</code> backend with matrix-free linear operators for wide designs. There are five vignettes including <a href="https://cran.r-project.org/web/packages/lassoinf/vignettes/gaussian_lasso.html" rel="nofollow" target="_blank">Randomized LASSO</a> and <a href="https://cran.r-project.org/web/packages/lassoinf/vignettes/glmnet_logistic.html" rel="nofollow" target="_blank">Inference after a glmnet fit</a>.</p>
<p><a href="https://cran.r-project.org/package=latents" rel="nofollow" target="_blank">latents</a> v1.1.9: Fits single-level and multilevel latent profile and class models, latent transition models, and mixture regression and growth models for studying unobserved heterogeneity. Accommodates continuous, categorical, ordinal, count and mixed indicators. Provides model comparison, parameter inference, classification diagnostics and graphical summaries. Observed-data likelihood methods are available for incomplete indicators, and supported transition models can be represented as networks using the <code>tna</code> package. The multilevel latent class formulation follows <a href="doi:10.1111/j.0081-1750.2003.t01-1-00131.x" rel="nofollow" target="_blank">Vermunt (2003)</a>. See the vignettes <a href="https://cran.r-project.org/web/packages/latents/vignettes/lca.html" rel="nofollow" target="_blank">Two-level latent class analysis</a> and <a href="https://cran.r-project.org/web/packages/latents/vignettes/lpa.html" rel="nofollow" target="_blank">Multilevel latent profile analysis</a>.</p>
<p><a href="https://i1.wp.com/rworks.dev/posts/oct-2026-top40/latents.png?ssl=1" class="lightbox" data-gallery="quarto-lightbox-gallery-22" rel="nofollow" target="_blank"><img src="https://i1.wp.com/rworks.dev/posts/oct-2026-top40/latents.png?w=578&#038;ssl=1" class="img-fluid" alt="Plot of profile means across 5 indicators" data-recalc-dims="1"></a></p>
<p><a href="https://cran.r-project.org/package=metamixr" rel="nofollow" target="_blank">metamixr</a> v0.1.0: Fits Bayesian random-effects meta-analytic mixture models in which the true study effects are drawn from a mixture of normal components with component-specific means and between-study heterogeneity. The mixture model can be combined with step-function selection models as in <a href="doi:10.1007/BF02294384" rel="nofollow" target="_blank">Vevea and Hedges (1995)</a> to adjust for publication bias. Models are estimated by Hamiltonian Monte Carlo using <code>rstan</code>. Posterior summaries, posterior predictive checks and marginal likelihoods for model comparison are returned as <code>stanfit</code> objects. Also includes a data simulator and the nudging meta-analysis data of <a href="doi:10.1073/pnas.2107346118" rel="nofollow" target="_blank">Mertens et al. (2022)</a>. There are four vignettes including <a href="https://cran.r-project.org/web/packages/metamixr/vignettes/metamix.html" rel="nofollow" target="_blank">Getting started</a> and <a href="https://cran.r-project.org/web/packages/metamixr/vignettes/nudging.html" rel="nofollow" target="_blank">Application to Nudging</a>.</p>
<p><a href="https://i0.wp.com/rworks.dev/posts/oct-2026-top40/metamixr.png?ssl=1" class="lightbox" data-gallery="quarto-lightbox-gallery-23" rel="nofollow" target="_blank"><img src="https://i0.wp.com/rworks.dev/posts/oct-2026-top40/metamixr.png?w=578&#038;ssl=1" class="img-fluid" alt="Comparison of posterior predictive and observed distributions" data-recalc-dims="1"></a></p>
<p><a href="https://cran.r-project.org/package=proxymix" rel="nofollow" target="_blank">proxymix</a> v0.17.0: Fits multivariate Gaussian-mixture proxies to target distributions on real Euclidean space, given by a density, by samples, or by a characteristic function. Four fitting regimes are unified: (i) closed-form moment matching for a single component, (ii) classical expectation-maximisation when independent samples are available, (iii) importance-sampled expectation-maximisation that minimizes the Kullback-Leibler divergence and (iv) a least-squares fit to the characteristic function. Provides numerical bounds on the Kolmogorov distance along one-dimensional projections. Implements the regime hierarchy of <a href="doi:10.1080/07362994.2024.2372605" rel="nofollow" target="_blank">van der Hoek and Elliott (2024)</a>. There are thirteen vignettes including <a href="https://cran.r-project.org/web/packages/proxymix/vignettes/operator_calculus.html" rel="nofollow" target="_blank">The closed-form operator calculus on a mixture</a> and <a href="https://cran.r-project.org/web/packages/proxymix/vignettes/density_shapes.html" rel="nofollow" target="_blank">How well a mixture proxies four awkward shapes</a>.</p>
<p><a href="https://i1.wp.com/rworks.dev/posts/oct-2026-top40/proxymix.png?ssl=1" class="lightbox" data-gallery="quarto-lightbox-gallery-24" rel="nofollow" target="_blank"><img src="https://i1.wp.com/rworks.dev/posts/oct-2026-top40/proxymix.png?w=578&#038;ssl=1" class="img-fluid" alt="Plots of target shapes with fitted proxy contours" data-recalc-dims="1"></a></p>
<p><a href="https://cran.r-project.org/package=radiatR" rel="nofollow" target="_blank">radiatR</a> v0.1.3: Implements a complete pipeline for analyzing directional data, headings and trajectories on the unit disk. Supply a table of angles directly, or reconstruct headings from movement trajectories imported from tracking tools via a unified dialect-based loader system, including multi-bodypart pose estimation with likelihood-weighted centroid. Computes circular statistics including mean direction, resultant length, von Mises and wrapped Cauchy parametric fits, circular correlation, circular-linear regression. See <a href="doi:10.2307/2532334" rel="nofollow" target="_blank">Fisher and Lee (1992)</a>, <a href="doi:10.1242/jeb.167056" rel="nofollow" target="_blank">Fitak and Johnsen (2017)</a>, and <a href="doi:10.1186/s12898-019-0246-8" rel="nofollow" target="_blank">Landler et al.(2019)</a> for background. There are five vignettes including <a href="https://cran.r-project.org/web/packages/radiatR/vignettes/circular-statistics.html" rel="nofollow" target="_blank">Circular Statistics and Distribution Overlays</a> and <a href="https://cran.r-project.org/web/packages/radiatR/vignettes/agent-guide.html" rel="nofollow" target="_blank">Guide for AI agents</a> and the <code>Shiny</code> app.</p>
<p><a href="https://i1.wp.com/rworks.dev/posts/oct-2026-top40/radiatR.png?ssl=1" class="lightbox" data-gallery="quarto-lightbox-gallery-25" rel="nofollow" target="_blank"><img src="https://i1.wp.com/rworks.dev/posts/oct-2026-top40/radiatR.png?w=578&#038;ssl=1" class="img-fluid" alt="Circular statistics plot" data-recalc-dims="1"></a></p>
<p><a href="https://cran.r-project.org/package=spifa" rel="nofollow" target="_blank">spifa</a> v0.1.0: Fits spatial item factor analysis models for binary responses, following <a href="doi:10.1214/25-AOAS2072" rel="nofollow" target="_blank">Chacón-Montalván et al. (2025)</a>, using full Bayesian inference via adaptive Metropolis-Hastings within Gibbs sampling and auxiliary variables with a probit link function. Latent factors are modeled as the sum of a predictor effect, a multivariate Gaussian process capturing spatial dependence, and a multivariate non-spatial term. Standard exploratory and confirmatory item factor analysis are supported as particular cases. There are five vignettes including <a href="https://cran.r-project.org/web/packages/spifa/vignettes/spifa.html" rel="nofollow" target="_blank">Introduction</a> and <a href="https://cran.r-project.org/web/packages/spifa/vignettes/vg03-advanced-features.html" rel="nofollow" target="_blank">Advanced Features</a>.</p>
<p><a href="https://i2.wp.com/rworks.dev/posts/oct-2026-top40/spifa.png?ssl=1" class="lightbox" data-gallery="quarto-lightbox-gallery-26" rel="nofollow" target="_blank"><img src="https://i2.wp.com/rworks.dev/posts/oct-2026-top40/spifa.png?w=578&#038;ssl=1" class="img-fluid" alt="Plot of traces and factor distributions" data-recalc-dims="1"></a></p>
</section>
<section id="time-series" class="level3">
<h3 class="anchored" data-anchor-id="time-series">Time Series</h3>
<p><a href="https://cran.r-project.org/package=foresightr" rel="nofollow" target="_blank">foresightr</a> v0.1.1: Implements time series forecasting via a rolling-origin backtest in <a href="doi:10.1016/S0169-2070(00)00065-0" rel="nofollow" target="_blank">Tashman (2000)</a> which refits every candidate at each origin using out-of-sample error. Prediction intervals are quantiles of the errors actually observed, for each horizon and for totals of the next periods. Models include seasonal ARIMA by exact maximum likelihood with automatic orders, <a href="doi:10.18637/jss.v027.i03" rel="nofollow" target="_blank">Hyndman and Khandakar (2008)</a>; exponential smoothing in state space form, <a href="doi:10.1016/S0169-2070(01)00110-8" rel="nofollow" target="_blank">Hyndman, Koehler, Snyder and Grose (2002)</a>; the Theta method, <a href="doi:10.1016/S0169-2070(00)00066-2" rel="nofollow" target="_blank">Assimakopoulos and Nikolopoulos (2000)</a> and more. The computations are done by the <code>Rust</code> crate <code>foresight</code>, bundled with the package. There are five vignettes including <a href="https://cran.r-project.org/web/packages/foresightr/vignettes/foresightr.html" rel="nofollow" target="_blank">Get started</a> and <a href="https://cran.r-project.org/web/packages/foresightr/vignettes/backtest.html" rel="nofollow" target="_blank">The Backtest and its intervals</a>.</p>
<p><a href="https://rworks.dev/posts/oct-2026-top40/foresightr.svg" class="lightbox" data-gallery="quarto-lightbox-gallery-27" rel="nofollow" target="_blank"><img src="https://rworks.dev/posts/oct-2026-top40/foresightr.svg" class="img-fluid" alt="Diagram illustrating how a model is chosen"></a></p>
<p><a href="https://cran.r-project.org/package=rjd3highfreq" rel="nofollow" target="_blank">rjd3highfreq</a> v3.0.1: Implements an <code>R</code> interface to <a href="https://github.com/jdemetra" rel="nofollow" target="_blank">JDemetra+ 3.x</a>, the time series analysis software which provides functions for seasonal adjustment of higher-frequency data, including those with multiple or non-integer periodicities. It includes pre-adjustment via the extended airline model and several seasonal decomposition methods: extended airline model based decomposition, extended X-11, and augmented STL. See the <a href="https://cran.r-project.org/web/packages/rjd3highfreq/vignettes/X11.html" rel="nofollow" target="_blank">vignette</a>.</p>
<p><a href="https://i0.wp.com/rworks.dev/posts/oct-2026-top40/rjd3highfreq.png?ssl=1" class="lightbox" data-gallery="quarto-lightbox-gallery-28" rel="nofollow" target="_blank"><img src="https://i0.wp.com/rworks.dev/posts/oct-2026-top40/rjd3highfreq.png?w=578&#038;ssl=1" class="img-fluid" alt="Seasonal decomposition" data-recalc-dims="1"></a></p>
</section>
<section id="utilities" class="level3">
<h3 class="anchored" data-anchor-id="utilities">Utilities</h3>
<p><a href="https://cran.r-project.org/package=controlledburn" rel="nofollow" target="_blank">controlledburn</a> v0.3.2: Rasterize polygon, line, and point geometry without materializing any pixel values. For polygons compute exact coverage fractions for polygon-grid intersections, returning sparse tables: run-length encoded interior cells and individually weighted boundary cells. The scanline algorithm is O(perimeter) in both time and memory using the scan line fill attributed to <a href="doi:10.1145/1465611.1465619" rel="nofollow" target="_blank">Wylie et al. (1967)</a>. Exact coverage fractions use the exactextract algorithm from the <code>exactextractr</code> <code>fasterize</code> packages. See the vignettes <a href="https://cran.r-project.org/web/packages/controlledburn/vignettes/algorithms.html" rel="nofollow" target="_blank">Algorithms</a> and <a href="https://cran.r-project.org/web/packages/controlledburn/vignettes/architecture.html" rel="nofollow" target="_blank">Architecture</a>.</p>
<p><a href="https://i2.wp.com/rworks.dev/posts/oct-2026-top40/controlledburn.png?ssl=1" class="lightbox" data-gallery="quarto-lightbox-gallery-29" rel="nofollow" target="_blank"><img src="https://i2.wp.com/rworks.dev/posts/oct-2026-top40/controlledburn.png?w=578&#038;ssl=1" class="img-fluid" alt="Polygon under teo different classification schemes" data-recalc-dims="1"></a></p>
<p><a href="https://cran.r-project.org/package=irelink" rel="nofollow" target="_blank">irelink</a> v0.0.2: Performs fast, scalable probabilistic record linkage and deduplication using the <a href="https://en.wikipedia.org/wiki/Record_linkage" rel="nofollow" target="_blank">Fellegi-Sunter model</a>. Records lacking a shared unique identifier are compared across configurable dimensions using exact, fuzzy, and distance-based comparisons, with model parameters estimated via unsupervised Expectation-Maximization. Multiple <code>SQL</code> backends are supported through <code>DBI</code>, including execution via <code>DuckDB</code>. This package is a translation of the <code>Python</code> <code>splink</code> library by <a href="doi:10.23889/ijpds.v7i3.1794" rel="nofollow" target="_blank">Linacre et al. (2022)</a> into idiomatic <code>R</code>. There are six vignettes including <a href="https://cran.r-project.org/web/packages/irelink/vignettes/irelink.html" rel="nofollow" target="_blank">Getting Started</a> and <a href="https://cran.r-project.org/web/packages/irelink/vignettes/record-linkage.html" rel="nofollow" target="_blank">Record Linkage Across Datasets</a>.</p>
<p><a href="https://i2.wp.com/rworks.dev/posts/oct-2026-top40/irelink.png?ssl=1" class="lightbox" data-gallery="quarto-lightbox-gallery-30" rel="nofollow" target="_blank"><img src="https://i2.wp.com/rworks.dev/posts/oct-2026-top40/irelink.png?w=578&#038;ssl=1" class="img-fluid" alt="Plot of match weights for a link-type model" data-recalc-dims="1"></a></p>
<p><a href="https://cran.r-project.org/package=seqbench" rel="nofollow" target="_blank">seqbench</a> v0.1.0: Provides sequential, anytime-valid comparison of algorithms on paired losses with a practical-equivalence margin, confidence sequences for the mean paired difference, superiority/equivalence/continue decisions, cost accounting and auditable trajectories. See the <a href="https://cran.r-project.org/web/packages/seqbench/vignettes/getting-started.html" rel="nofollow" target="_blank">vignette</a> .</p>
</section>
<section id="visualization" class="level3">
<h3 class="anchored" data-anchor-id="visualization">Visualization</h3>
<p><a href="https://cran.r-project.org/package=ggfourfold" rel="nofollow" target="_blank">ggfourfold</a> v0.1.0: Draws fourfold displays of 2 x 2 (x k) contingency tables as a <code>ggplot2</code> layer, following <a href="https://datavis.ca/papers/4fold/4fold.pdf" rel="nofollow" target="_blank">Friendly (1994)</a> and <a href="doi:10.1201/9781315374413" rel="nofollow" target="_blank">Friendly and Meyer (2016)</a>. Cell frequencies are shown as quarter-circles or squares of proportional area, with confidence rings for the odds ratio and shading for the direction and strength of association. See the <a href="https://cran.r-project.org/web/packages/ggfourfold/vignettes/ggfourfold.html" rel="nofollow" target="_blank">vignette</a>.</p>
<p><a href="https://i2.wp.com/rworks.dev/posts/oct-2026-top40/ggfourfold.png?ssl=1" class="lightbox" data-gallery="quarto-lightbox-gallery-31" rel="nofollow" target="_blank"><img src="https://i2.wp.com/rworks.dev/posts/oct-2026-top40/ggfourfold.png?w=578&#038;ssl=1" class="img-fluid" alt="Examples of four-fold plots" data-recalc-dims="1"></a></p>
</section>
</div>
</div>



 
<div style="border: 1px solid; background: none repeat scroll 0 0 #EDEDED; margin: 1px; font-size: 13px;">
<div style="text-align: center;">To <strong>leave a comment</strong> for the author, please follow the link and comment on their blog: <strong><a href="https://rworks.dev/posts/oct-2026-top40/"> R Works</a></strong>.</div>
<hr />
<a href="https://www.r-bloggers.com/" rel="nofollow">R-bloggers.com</a> offers <strong><a href="https://feedburner.google.com/fb/a/mailverify?uri=RBloggers" rel="nofollow">daily e-mail updates</a></strong> about <a title="The R Project for Statistical Computing" href="https://www.r-project.org/" rel="nofollow">R</a> news and tutorials about <a title="R tutorials" href="https://www.r-bloggers.com/how-to-learn-r-2/" rel="nofollow">learning R</a> and many other topics. <a title="Data science jobs" href="https://www.r-users.com/" rel="nofollow">Click here if you're looking to post or find an R/data-science job</a>.

<hr>Want to share your content on R-bloggers?<a href="https://www.r-bloggers.com/add-your-blog/" rel="nofollow"> click here</a> if you have a blog, or <a href="http://r-posts.com/" rel="nofollow"> here</a> if you don't.
</div><strong>Continue reading</strong>: <a href="https://www.r-bloggers.com/2026/11/october-2026-top-40-new-cran-packages/">October 2026 Top 40 New CRAN Packages</a>]]></content:encoded>
					
		
		<enclosure url="https://rworks.dev/posts/oct-2026-top40/shaman.png" length="0" type="image/png" />

		<post-id xmlns="com-wordpress:feed-additions:1">405176</post-id>	</item>
		<item>
		<title>You probably don’t care about Unix File Mode &#038; octmode bitwise comparison but let’s talk about it anyway</title>
		<link>https://www.r-bloggers.com/2026/11/you-probably-dont-care-about-unix-file-mode-octmode-bitwise-comparison-but-lets-talk-about-it-anyway/</link>
		
		<dc:creator><![CDATA[Colin Fay]]></dc:creator>
		<pubDate>Sun, 29 Nov 2026 00:00:00 +0000</pubDate>
				<category><![CDATA[R bloggers]]></category>
		<guid isPermaLink="false">https://delicate-pegasus-aac583.netlify.app/posts/octmode.html</guid>

					<description><![CDATA[<p>For some reason during the summer holidays I was browsing the R source code and stumbled upon this piece of code in check_permissions.<br />
## Phase A.  Directories at least 700, files at least 400.<br />
if (length(allfiles)) {<br />
  mode</p>
<strong>Continue reading</strong>: <a href="https://www.r-bloggers.com/2026/11/you-probably-dont-care-about-unix-file-mode-octmode-bitwise-comparison-but-lets-talk-about-it-anyway/">You probably don’t care about Unix File Mode & octmode bitwise comparison but let’s talk about it anyway</a>]]></description>
										<content:encoded><![CDATA[<!-- 
<div style="min-height: 30px;">
[social4i size="small" align="align-left"]
</div>
-->

<div style="border: 1px solid; background: none repeat scroll 0 0 #EDEDED; margin: 1px; font-size: 12px;">
[This article was first published on  <strong><a href="https://delicate-pegasus-aac583.netlify.app/posts/octmode.html"> Colin Fay</a></strong>, and kindly contributed to <a href="https://www.r-bloggers.com/" rel="nofollow">R-bloggers</a>].  (You can report issue about the content on this page <a href="https://www.r-bloggers.com/contact-us/">here</a>)
<hr>Want to share your content on R-bloggers?<a href="https://www.r-bloggers.com/add-your-blog/" rel="nofollow"> click here</a> if you have a blog, or <a href="http://r-posts.com/" rel="nofollow"> here</a> if you don't.
</div>
 




<p>For some reason during the summer holidays I was browsing the R source code and stumbled upon this piece of code in <a href="https://github.com/wch/r-source/blob/trunk/src/library/tools/R/check.R#L926" rel="nofollow" target="_blank">check_permissions</a>.</p>
<pre>## Phase A.  Directories at least 700, files at least 400.
if (length(allfiles)) {
  mode &lt;- file.mode(allfiles)
  bad_files &lt;- allfiles[(mode &#038; &quot;400&quot;) &lt; as.octmode(&quot;400&quot;)]
}</pre>
<p>And at that exact moment, <code>(mode & &quot;400&quot;) &lt; as.octmode(&quot;400&quot;)</code> became a mystery I needed to understand. (And yes, I ended up going to bed later than expected because of that).</p>
<section id="file-mode" class="level2">
<h2 class="anchored" data-anchor-id="file-mode">File mode</h2>
<p>If you’re unfamiliar with Unix file mode, it’s a way to describe what a user can do with a file (read, write, or execute), depending on its identity: does he own the file and is he a member of the same group as the file owner.</p>
<p>It’s usually represented either with a series of characters, for example <code>rwxrw-r--</code>, where:</p>
<ul>
<li>The first three characters represent what the file owner can do (here <code>r</code>ead, <code>w</code>rite, and e<code>x</code>ecute).</li>
<li>The next three what the users of the same group as the owner can do (here only read and write).</li>
<li>The last three what everybody on the machine can do with the file (here, only read).</li>
</ul>
<p>It can also be represented as <code>764</code>, which is an <strong>octal notation</strong> of the permission, where read is 4, write is 2 and execute is 1. The number represented is the sum of the permissions (7 is rwx, so 4 + 2 + 1, 6 read and write, 5 read and execute… you get the point).</p>
<p>I’ve always wondered why these numbers (4, 2 and 1). So let’s dive into that rabbit hole.</p>
</section>
<section id="what-is-the-octal-notation" class="level2">
<h2 class="anchored" data-anchor-id="what-is-the-octal-notation">What is the octal notation?</h2>
<p>We live in a world that counts in base 10. That is to say, we go from 1 to 10, then 11 to 20, etc. I’m pretty sure I don’t need to develop on that.</p>
<p>But there are other ways to count. For example, binary, which is a base 2 system, i.e. you only have 2 symbols to represent numbers, 0 and 1. So you start with the first number, which is 0. Then use the next available sign, 1. Then you’re out of available signs, so move to 10. Then 11. Then you’re again out of available signs, so 100. And 101, 110, 111…</p>
<p>Anyway, octal is a base 8 system that uses the numbers 0 to 7 to count, and can be represented as triplets of 0 and 1 in binary:</p>
<ul>
<li>000 is 0</li>
<li>001 is 1</li>
<li>010 is 2</li>
<li>011 is 3</li>
<li>100 is 4</li>
<li>101 is 5</li>
<li>110 is 6</li>
<li>111 is 7</li>
</ul>
<p>Meaning that our file mode can be expressed as a triplet of bits: <code>764</code> being <code>111 110 100</code>, a bit attached to the file that describes the permission.</p>
<p>And here is the answer to our “why 4, 2 and 1” question: each permission is one bit of the triplet. Read is the first bit, so <code>100</code>, which is 4. Write is the second one, <code>010</code>, which is 2. And execute is the last one, <code>001</code>, which is 1.</p>
<p>So when you “sum” the permissions, what you’re really doing is switching bits on. <code>rw-</code> is <code>100</code> + <code>010</code>, so <code>110</code>, so 6. <code>r-x</code> is <code>100</code> + <code>001</code>, so <code>101</code>, so 5. You get the point.</p>
</section>
<section id="back-to-our-mode-400-as.octmode400" class="level2">
<h2 class="anchored" data-anchor-id="back-to-our-mode-400-as.octmode400">Back to our <code>(mode & &quot;400&quot;) &lt; as.octmode(&quot;400&quot;)</code></h2>
<p>This piece of code was very weird to me. The comment says <code>files at least 400</code>.</p>
<p>But this broke my brain <code>(mode & &quot;400&quot;)</code>. Why the <code>&</code>? Why the “400”?</p>
<p>Well, turns out it’s because this code is doing <strong>bitwise comparison</strong>. You never knew you needed it, me neither, but here it is: <code>&</code> on octmode object will compare elements bit by bit, and return another series of bits.</p>
<p>Bitwise comparison is quite simple to understand: if 1 & 1 => 1, otherwise 0.</p>
<p>And it turns out that all permissions < 400 will return 0 if &#038; with 400.</p>
<pre>400 = 100 000 000</pre>
<p>So every permission that doesn’t start with something more than 100 (4), will be zero.</p>
<p>For example:</p>
<pre>400 = 100 000 000
 &
377 = 011 111 111
-------------------
000 = 000 000 000</pre>
<p>On the other hand, every permission >= 400 will start with 1xx xxx xxx so will always be != 0 because</p>
<pre>400 = 100 000 000
??? = 1xx xxx xxx
-------------------
400 = 100 000 000</pre>
<p>So basically <code>(mode & &quot;400&quot;)</code> is a way to do some triage, so that every perm below 400 will be converted to 0, and the others to 400.</p>
</section>
<section id="as.octmode400" class="level2">
<h2 class="anchored" data-anchor-id="as.octmode400"><code>&lt; as.octmode(&quot;400&quot;)</code></h2>
<p>Now that we know what <code>(mode & &quot;400&quot;)</code> does, the end of the expression is pretty straightforward.</p>
<p>After the <code>&</code>, we only have two possible values: <code>000</code> or <code>400</code>. And <code>&lt; as.octmode(&quot;400&quot;)</code> is <code>TRUE</code> only for <code>000</code>, i.e. for the files the owner can’t read.</p>
<pre>modes &lt;- as.octmode(c(&quot;764&quot;, &quot;400&quot;, &quot;377&quot;, &quot;644&quot;))
modes &#038; &quot;400&quot;
## [1] &quot;400&quot; &quot;400&quot; &quot;000&quot; &quot;400&quot;
(modes &#038; &quot;400&quot;) &lt; as.octmode(&quot;400&quot;)
## [1] FALSE FALSE  TRUE FALSE</pre>
<p>These are the files that end up in <code>bad_files</code>, and if there are any, <code>R CMD check</code> throws an error: “Found the following files with insufficient permissions”.</p>
</section>
<section id="why-not-just-mode-400" class="level2">
<h2 class="anchored" data-anchor-id="why-not-just-mode-400">Why not just <code>mode &lt; 400</code>?</h2>
<p>At this point you might wonder (I did): why bother with the <code>&</code>? Why not just do <code>mode &lt; as.octmode(&quot;400&quot;)</code>?</p>
<p>Well, because the <code>&</code> isolates one bit (the “owner can read” one), and ignores all the others. On the other hand, <code>mode &lt; as.octmode(&quot;400&quot;)</code> compares the whole number, including bits that have nothing to do with reading the file.</p>
<p>Let’s take <code>1377</code>. That’s our <code>377</code> from before, plus a leading <code>1</code>: the sticky bit, one of the “special” permissions that can be put in front of the three triplets. The owner still can’t read the file, but as a number, it’s bigger than <code>400</code>:</p>
<pre>mode &lt;- as.octmode(&quot;1377&quot;)
(mode &#038; &quot;400&quot;) &lt; as.octmode(&quot;400&quot;)
## [1] TRUE
mode &lt; as.octmode(&quot;400&quot;)
## [1] FALSE</pre>
<p>So the direct comparison would have missed this file.</p>
</section>
<section id="directories-at-least-700" class="level2">
<h2 class="anchored" data-anchor-id="directories-at-least-700">Directories: at least 700</h2>
<p>Remember the comment at the top of the code: “Directories at least 700, files at least 400”. And yes, a few lines below in <code>check.R</code>, the very same trick is used for directories, this time with <code>&quot;700&quot;</code>:</p>
<pre>if (length(alldirs &lt;- unique(dirname(allfiles)))) {
  mode &lt;- file.mode(alldirs)
  bad_files &lt;- c(bad_files,
                 alldirs[(mode &#038; &quot;700&quot;) &lt; as.octmode(&quot;700&quot;)])
}</pre>
<p><code>700</code> is <code>111 000 000</code>, so the <code>&</code> keeps the three bits of the owner, and drops the rest. This time, the result can be anything between <code>000</code> and <code>700</code>, and the only way to get <code>700</code> is to have the three bits on. So <code>&lt; as.octmode(&quot;700&quot;)</code> is <code>TRUE</code> as soon as the owner misses at least one of read, write or execute:</p>
<pre>x &lt;- as.octmode(c(&quot;000&quot;, &quot;100&quot;, &quot;200&quot;, &quot;300&quot;, &quot;400&quot;, &quot;500&quot;, &quot;600&quot;, &quot;700&quot;))
(x &#038; &quot;700&quot;) &lt; as.octmode(&quot;700&quot;)
## [1]  TRUE  TRUE  TRUE  TRUE  TRUE  TRUE  TRUE FALSE</pre>
<p>That’s the general idea behind <code>(mode & x) &lt; x</code>: <code>mode & x</code> can never be bigger than <code>x</code>, so this comparison is a way to say “not all the bits from <code>x</code> are on”. (And you’ll find it a third time a bit further down, with <code>&quot;500&quot;</code> for the <code>configure</code> and <code>cleanup</code> scripts.)</p>
</section>
<section id="trying-it-in-r" class="level2">
<h2 class="anchored" data-anchor-id="trying-it-in-r">Trying it in R</h2>
<p>Let’s play with this on a real file. <code>tempfile()</code> only gives us a path, so we need to create the file first:</p>
<pre>tmp &lt;- tempfile()
file.create(tmp)
## [1] TRUE
file.mode(tmp)
## [1] &quot;644&quot;</pre>
<p>(The default mode depends on your system, here it’s <code>644</code>.)</p>
<p>The owner can read it, so our file is fine:</p>
<pre>(file.mode(tmp) & &quot;400&quot;) &lt; as.octmode(&quot;400&quot;)
## [1] FALSE</pre>
<p>Now let’s change the mode with <code>Sys.chmod()</code>, and only keep the write permission for the owner:</p>
<pre>Sys.chmod(tmp, &quot;200&quot;)
file.mode(tmp)
## [1] &quot;200&quot;
(file.mode(tmp) & &quot;400&quot;) &lt; as.octmode(&quot;400&quot;)
## [1] TRUE</pre>
<p>And voilà, this file would now end up in <code>bad_files</code>.</p>
</section>
<section id="conclusion" class="level2">
<h2 class="anchored" data-anchor-id="conclusion">Conclusion</h2>
<p>To sum up:</p>
<ul>
<li>I’m definitely a big nerd.</li>
<li>You probably still don’t care about bitwise comparison.</li>
</ul>
<p>But hey, next time you stumble upon a <code>&</code> between two file modes, you’ll know what’s going on <img src="https://s.w.org/images/core/emoji/13.0.0/72x72/1f918.png" alt="🤘" class="wp-smiley" style="height: 1em; max-height: 1em;" /></p>
<div id="disqus_thread"></div>
<script>
var disqus_config = function () {
  this.page.url = "https://colinfay.me/octmode/";
  this.page.identifier = "/octmode";
};
(function() {
  var d = document, s = d.createElement('script');
  s.src = 'https://http-colinfay-me.disqus.com/embed.js';
  s.setAttribute('data-timestamp', +new Date());
  (d.head || d.body).appendChild(s);
})();
</script>
<noscript>Please enable JavaScript to view the comments powered by Disqus.</noscript>


</section>

<a onclick="window.scrollTo(0, 0); return false;" id="quarto-back-to-top"><i class="bi bi-arrow-up"></i> Back to top</a> 
<div style="border: 1px solid; background: none repeat scroll 0 0 #EDEDED; margin: 1px; font-size: 13px;">
<div style="text-align: center;">To <strong>leave a comment</strong> for the author, please follow the link and comment on their blog: <strong><a href="https://delicate-pegasus-aac583.netlify.app/posts/octmode.html"> Colin Fay</a></strong>.</div>
<hr />
<a href="https://www.r-bloggers.com/" rel="nofollow">R-bloggers.com</a> offers <strong><a href="https://feedburner.google.com/fb/a/mailverify?uri=RBloggers" rel="nofollow">daily e-mail updates</a></strong> about <a title="The R Project for Statistical Computing" href="https://www.r-project.org/" rel="nofollow">R</a> news and tutorials about <a title="R tutorials" href="https://www.r-bloggers.com/how-to-learn-r-2/" rel="nofollow">learning R</a> and many other topics. <a title="Data science jobs" href="https://www.r-users.com/" rel="nofollow">Click here if you're looking to post or find an R/data-science job</a>.

<hr>Want to share your content on R-bloggers?<a href="https://www.r-bloggers.com/add-your-blog/" rel="nofollow"> click here</a> if you have a blog, or <a href="http://r-posts.com/" rel="nofollow"> here</a> if you don't.
</div><strong>Continue reading</strong>: <a href="https://www.r-bloggers.com/2026/11/you-probably-dont-care-about-unix-file-mode-octmode-bitwise-comparison-but-lets-talk-about-it-anyway/">You probably don’t care about Unix File Mode & octmode bitwise comparison but let’s talk about it anyway</a>]]></content:encoded>
					
		
		<enclosure url="" length="0" type="" />

		<post-id xmlns="com-wordpress:feed-additions:1">405174</post-id>	</item>
		<item>
		<title>rbin 0.3.0</title>
		<link>https://www.r-bloggers.com/2026/11/rbin-0-3-0/</link>
		
		<dc:creator><![CDATA[Aravind Hebbali]]></dc:creator>
		<pubDate>Sat, 28 Nov 2026 00:00:00 +0000</pubDate>
				<category><![CDATA[R bloggers]]></category>
		<guid isPermaLink="false">https://blog.rsquaredacademy.com/posts/rbin-0-3-0/</guid>

					<description><![CDATA[<div style = "width:60%; display: inline-block; float:left; "> rbin 0.3.0</p>
<p>rbin bins predictors for scorecards and reports the weight of evidence and information value of every bin.<br />
It works on numeric and categorical predictors, offers equal-frequency, quantile, equal-length, winsorized and manual cuts, and builds dummy variables from the bins.<br />
The examples use mbank, the package’s bank marketing data; ...</p></div>
<div style = "width: 40%; display: inline-block; float:right;"></div>
<div style="clear: both;"></div>
<strong>Continue reading</strong>: <a href="https://www.r-bloggers.com/2026/11/rbin-0-3-0/">rbin 0.3.0</a>]]></description>
										<content:encoded><![CDATA[<!-- 
<div style="min-height: 30px;">
[social4i size="small" align="align-left"]
</div>
-->

<div style="border: 1px solid; background: none repeat scroll 0 0 #EDEDED; margin: 1px; font-size: 12px;">
[This article was first published on  <strong><a href="https://blog.rsquaredacademy.com/posts/rbin-0-3-0/"> Rsquared Academy Blog</a></strong>, and kindly contributed to <a href="https://www.r-bloggers.com/" rel="nofollow">R-bloggers</a>].  (You can report issue about the content on this page <a href="https://www.r-bloggers.com/contact-us/">here</a>)
<hr>Want to share your content on R-bloggers?<a href="https://www.r-bloggers.com/add-your-blog/" rel="nofollow"> click here</a> if you have a blog, or <a href="http://r-posts.com/" rel="nofollow"> here</a> if you don't.
</div>
 





<p>rbin 0.3.0</p>
<p><img src="https://i2.wp.com/blog.rsquaredacademy.com/img/rbin-0-3-0.png?w=578&#038;ssl=1" class="img-fluid" style="width:100.0%" alt="rbin hex logo next to the tagline Binning for credit scoring in R, the line 0.3.0, reliable bins for scorecards, the package name rbin and rbin.rsquaredacademy.com" data-recalc-dims="1"></p>
<style>
.ba-note{font-size:.88rem;color:#57606a;border-left:3px solid #d0d7de;padding-left:.75rem;margin:.5rem 0 1.25rem}
</style>
<p>rbin bins predictors for scorecards and reports the weight of evidence and information value of every bin.</p>
<p>It works on numeric and categorical predictors, offers equal-frequency, quantile, equal-length, winsorized and manual cuts, and builds dummy variables from the bins.</p>
<p>The examples use <code>mbank</code>, the package’s bank marketing data; treat <code>y</code> as the good/bad outcome you would model.</p>
<section id="binning-a-predictor" class="level2">
<h2 class="anchored" data-anchor-id="binning-a-predictor">Binning a predictor</h2>
<p>A common starting point: <code>rbin_quantiles()</code> cuts one numeric predictor into groups of equal frequency and reports what each group holds. <code>balance</code>, the customer’s average yearly account balance, is known before any contact, so it goes into five bins:</p>
<div class="cell">
<details open="" class="code-fold">
<summary>Code</summary>
<pre>bins_balance &lt;- rbin_quantiles(mbank[, c(&quot;balance&quot;, &quot;y&quot;)], y, balance, bins = 5)
bins_balance</pre>
</details>
<div class="cell-output cell-output-stdout">
<pre>Binning Summary
-----------------------------
Method               Quantile 
Response             y 
Predictor            balance 
Bins                 5 
Count                4521 
Goods                517 
Bads                 4004 
Entropy              0.51 
Information Value    0.1 


  cut_point bin_count good bad          woe           iv   entropy
1      &lt; 25       901   61 840  0.575521762 5.283394e-02 0.3572909
2     &lt; 283       904   94 810  0.106733199 2.185845e-03 0.4814936
3     &lt; 715       907  104 803 -0.003042451 1.859215e-06 0.5138248
4    &lt; 1804       904  111 793 -0.080713246 1.343734e-03 0.5373210
5   &gt;= 1804       905  147 758 -0.406755467 3.865072e-02 0.6400935</pre>
</div>
</div>
<p>The cuts fall at 25, 283, 715 and 1,804, and subscriptions rise with balance: 61 of the 901 customers in the lowest bin subscribed, against 147 of the 905 in the highest. The weight of evidence falls from 0.58 to -0.41 (here a positive weight means a bin with fewer subscribers than average), and the information value for <code>balance</code> is 0.1 (rounded; about 0.095), a modest predictor to weigh against the others.</p>
<p><code>plot()</code> draws those weights in bin order:</p>
<div class="cell">
<details open="" class="code-fold">
<summary>Code</summary>
<pre>plot(bins_balance)</pre>
</details>
<div class="cell-output-display">
<div id="fig-quantile-bins" class="quarto-float quarto-figure quarto-figure-center anchored" alt="Weight of evidence by account-balance bin for 4,521 bank customers, falling steadily across the five bins: 0.58 for balances under 25, 0.11 for 25 to 283, 0.00 for 283 to 715, -0.08 for 715 to 1,804, and -0.41 for 1,804 and over." width="450">
<figure class="quarto-float quarto-float-fig figure">
<div aria-describedby="fig-quantile-bins-caption-0ceaefa1-69ba-4598-a22c-09a6ac19f8ca">
<img src="https://i0.wp.com/blog.rsquaredacademy.com/posts/rbin-0-3-0/index_files/figure-html/fig-quantile-bins-1.png?w=450&#038;ssl=1" id="fig-quantile-bins" class="img-fluid figure-img" alt="Weight of evidence by account-balance bin for 4,521 bank customers, falling steadily across the five bins: 0.58 for balances under 25, 0.11 for 25 to 283, 0.00 for 283 to 715, -0.08 for 715 to 1,804, and -0.41 for 1,804 and over."  data-recalc-dims="1">
</div>
<figcaption class="quarto-float-caption-bottom quarto-float-caption quarto-float-fig quarto-uncaptioned" id="fig-quantile-bins-caption-0ceaefa1-69ba-4598-a22c-09a6ac19f8ca">
Figure 1
</figcaption>
</figure>
</div>
</div>
</div>
<p>The appeal is the single call: a count and a weight for each bin, and one information value to set <code>balance</code> beside the other predictors you are considering.</p>
</section>
<section id="what-0.3.0-adds" class="level2">
<h2 class="anchored" data-anchor-id="what-0.3.0-adds">What 0.3.0 adds</h2>
<p>rbin 0.3.0 keeps every record in a scorecard in a bin you can explain: missing predictors, repeated values, extreme values and missing responses are each handled, and the package tells you what it did. It also brings in the 0.2.2 and 0.2.3 work, which never reached CRAN. If you saved binning results from 0.2.1, refit before you score; the Behaviour changes block lists what moves.</p>
</section>
<section id="every-customer-lands-in-a-bin" class="level2">
<h2 class="anchored" data-anchor-id="every-customer-lands-in-a-bin">Every customer lands in a bin</h2>
<p>Where does a customer with no age go? <code>mbank</code> records the outcome of a bank’s term-deposit campaign for 4,521 customers, with the age of each. The data has no missing values, so four ages are blanked to mimic incomplete records before <code>age</code> is binned into four groups:</p>
<div class="cell">
<details open="" class="code-fold">
<summary>Code</summary>
<pre>d &lt;- mbank[, c(&quot;age&quot;, &quot;y&quot;)]
missing_rows &lt;- c(which(d$y == &quot;0&quot;)[c(2, 5, 9)], which(d$y == &quot;1&quot;)[4])
d$age[missing_rows] &lt;- NA
bins_age &lt;- rbin_equal_freq(d, y, age, bins = 4)
bins_age</pre>
</details>
<div class="cell-output cell-output-stdout">
<pre>Binning Summary
------------------------------------
Method               Equal Frequency 
Response             y 
Predictor            age 
Bins                 5 
Count                4521 
Goods                517 
Bads                 4004 
Entropy              0.51 
Information Value    0.04 


  lower_cut upper_cut bin_count good  bad  good_rate        woe          iv
1      -Inf        34      1289  167 1122 0.12955780 -0.1421320 0.006082912
2        34        40      1070  102  968 0.09532710  0.2032530 0.009037883
3        40        49      1055   95  960 0.09004739  0.2660501 0.014900888
4        49       Inf      1103  152  951 0.13780598 -0.2133727 0.012053720
5        NA        NA         4    1    3 0.25000000 -0.9483940 0.001123833
    entropy
1 0.5562242
2 0.4540054
3 0.4366280
4 0.5784639
5 0.8112781</pre>
</div>
</div>
<p>The summary has five bins: four intervals cut from the 4,517 customers who have an age (34, 40 and 49), and a final group of 4 rows marked <code>NA</code> in both cut columns (<a href="https://github.com/rsquaredacademy/rbin/issues/69" rel="nofollow" target="_blank">#69</a>). The top interval holds 1,103 rows, and the total information value reads 0.04. The plot shows the weight of evidence for each bin, with the group of rows without an age at the end:</p>
<div class="cell">
<details open="" class="code-fold">
<summary>Code</summary>
<pre>plot(bins_age)</pre>
</details>
<div class="cell-output-display">
<div id="fig-missing-bin" class="quarto-float quarto-figure quarto-figure-center anchored" alt="Weight of evidence by age bin for 4,521 bank customers, with the four rows without an age as a separate fifth point: -0.14 for up to 34, 0.20 for 34 to 40, 0.27 for 40 to 49, -0.21 for 49 and over, and -0.95 for the rows with no age." width="450">
<figure class="quarto-float quarto-float-fig figure">
<div aria-describedby="fig-missing-bin-caption-0ceaefa1-69ba-4598-a22c-09a6ac19f8ca">
<img src="https://i1.wp.com/blog.rsquaredacademy.com/posts/rbin-0-3-0/index_files/figure-html/fig-missing-bin-1.png?w=450&#038;ssl=1" id="fig-missing-bin" class="img-fluid figure-img" alt="Weight of evidence by age bin for 4,521 bank customers, with the four rows without an age as a separate fifth point: -0.14 for up to 34, 0.20 for 34 to 40, 0.27 for 40 to 49, -0.21 for 49 and over, and -0.95 for the rows with no age."  data-recalc-dims="1">
</div>
<figcaption class="quarto-float-caption-bottom quarto-float-caption quarto-float-fig quarto-uncaptioned" id="fig-missing-bin-caption-0ceaefa1-69ba-4598-a22c-09a6ac19f8ca">
Figure 2
</figcaption>
</figure>
</div>
</div>
</div>
<p>In 0.2.1 those four rows sat inside the top interval, whose upper cut printed <code>NA</code>; the cuts were 33, 39 and 48, and the total information value read 0.06.</p>
</section>
<section id="bins-that-match-your-data" class="level2">
<h2 class="anchored" data-anchor-id="bins-that-match-your-data">Bins that match your data</h2>
<p>Can a predictor with mostly one value fill five bins? Most customers in <code>mbank</code> had no earlier contact: <code>previous</code> is zero for 3,686 of them. Ask for five equal-frequency bins:</p>
<div class="cell">
<details open="" class="code-fold">
<summary>Code</summary>
<pre>rbin_equal_freq(mbank[, c(&quot;previous&quot;, &quot;y&quot;)], y, previous, bins = 5)</pre>
</details>
<div class="cell-output cell-output-stderr">
<pre>Requested 5 equal-frequency bins; returning 2 non-missing bin(s) because tied values are kept together.</pre>
</div>
<div class="cell-output cell-output-stdout">
<pre>Binning Summary
------------------------------------
Method               Equal Frequency 
Response             y 
Predictor            previous 
Bins                 2 
Count                4521 
Goods                517 
Bads                 4004 
Entropy              0.5 
Information Value    0.2 


  lower_cut upper_cut bin_count good  bad  good_rate        woe         iv
1      -Inf         1      3686  334 3352 0.09061313  0.2591652 0.04953373
2         1       Inf       835  183  652 0.21916168 -0.7764479 0.14840094
    entropy
1 0.4385131
2 0.7586338</pre>
</div>
</div>
<p>Two bins come back, and the message says why. A run of identical values cannot be split across a boundary, so the first bin holds the 3,686 customers with <code>previous</code> of 0 and the second holds the rest.</p>
<p>In 0.2.1 the cuts went through the ties: five bins, four of them labelled <code>0</code> to <code>0</code>, and <code>rbin_create()</code> stopped with an error on that summary.</p>
</section>
<section id="score-new-customers-safely" class="level2">
<h2 class="anchored" data-anchor-id="score-new-customers-safely">Score new customers safely</h2>
<p>Can a saved set of bins score a customer outside the training range? Credit teams cap a long tail so a handful of extreme values do not set the cuts. <code>balance</code> runs from -1,941 to 57,435 and is known before contact, so cap it at 0 and 5,000 and ask for four bins:</p>
<div class="cell">
<details open="" class="code-fold">
<summary>Code</summary>
<pre>bins &lt;- rbin_winsorize(
  mbank[, c(&quot;balance&quot;, &quot;y&quot;)], y, balance,
  bins = 4, min_val = 0, max_val = 5000
)
bins</pre>
</details>
<div class="cell-output cell-output-stdout">
<pre>Binning Summary
------------------------------
Method               Winsorize 
Response             y 
Predictor            balance 
Bins                 4 
Count                4521 
Goods                517 
Bads                 4004 
Entropy              0.51 
Information Value    0.06 


  cut_point bin_count good  bad        woe          iv   entropy
1    &lt; 1250      3262  326 2936  0.1508997 0.015498279 0.4688012
2    &lt; 2500       577   75  502 -0.1458943 0.002873106 0.5573907
3    &lt; 3750       283   53  230 -0.5792189 0.026106524 0.6957448
4   &gt;= 3750       399   63  336 -0.3730298 0.014153044 0.6292492</pre>
</div>
</div>
<p>The cuts are 1,250, 2,500 and 3,750, inside the clamps; the first bin holds 3,262 customers, and the top bin holds 399 with a weight of evidence of -0.37, for an information value of 0.06. The clamps are stored with the bins, so scoring new records uses the same ones:</p>
<div class="cell">
<details open="" class="code-fold">
<summary>Code</summary>
<pre>rbin_create(data.frame(balance = c(-500, 0, 400, 5000, 9000)), balance, bins)</pre>
</details>
<div class="cell-output cell-output-stdout">
<pre>  balance balance_&lt;_1250 balance_&lt;_2500 balance_&lt;_3750 balance_&gt;=_3750
1    -500              1              0              0               0
2       0              1              0              0               0
3     400              1              0              0               0
4    5000              0              0              0               1
5    9000              0              0              0               1</pre>
</div>
</div>
<p>Each value gets one row, with one dummy column marked for the bin it falls in; -500 falls below the floor into the first bin, and 5,000 and 9,000 sit at or above the ceiling in the last one.</p>
<p>In 0.2.1 a floor of 0 was not handled: every cut printed as the raw minimum (-1941), each of the four rows counted all 4,521 customers for an information value of 0, and the object it saved could not be scored at all: <code>rbin_create()</code> stopped on a length mismatch.</p>
<p>rbin takes its cut points from finite predictor values up to 1e300 in absolute value and stops beyond that with a message.</p>
</section>
<section id="clear-messages-for-dropped-rows" class="level2">
<h2 class="anchored" data-anchor-id="clear-messages-for-dropped-rows">Clear messages for dropped rows</h2>
<p>Where do rows with no outcome go? Three responses are blanked to mimic missing outcomes in this extract:</p>
<div class="cell">
<details open="" class="code-fold">
<summary>Code</summary>
<pre>d &lt;- mbank[, c(&quot;age&quot;, &quot;y&quot;)]
d$y[c(3, 7, 11)] &lt;- NA
rbin_equal_freq(d, y, age, bins = 4)</pre>
</details>
<div class="cell-output cell-output-stderr">
<pre>Warning: Dropping 3 rows with missing response.</pre>
</div>
<div class="cell-output cell-output-stdout">
<pre>Binning Summary
------------------------------------
Method               Equal Frequency 
Response             y 
Predictor            age 
Bins                 4 
Count                4518 
Goods                516 
Bads                 4002 
Entropy              0.51 
Information Value    0.04 


  lower_cut upper_cut bin_count good  bad  good_rate        woe          iv
1      -Inf        34      1289  167 1122 0.12955780 -0.1435685 0.006214159
2        34        40      1069  101  968 0.09448082  0.2116688 0.009766955
3        40        49      1055   95  960 0.09004739  0.2646136 0.014757908
4        49       Inf      1105  153  952 0.13846154 -0.2203156 0.012917231
    entropy
1 0.5562242
2 0.4512520
3 0.4366280
4 0.5801955</pre>
</div>
</div>
<p>The call drops the three rows, says how many it removed, and summarises the 4,518 that remain: 516 goods, 4,002 bads and an information value of 0.04.</p>
<p>In 0.2.1 the rows stayed in the count and the summary returned <code>NA</code> for goods, bads, entropy and information value in every bin that held one, while the count still read 4,521.</p>
</section>
<section id="behaviour-changes" class="level2">
<h2 class="anchored" data-anchor-id="behaviour-changes">Behaviour changes</h2>
<p>If you report bin counts, weight of evidence, information value or dummy variables from bins fitted with 0.2.1, refit before you score.</p>
<table class="caption-top table">
<colgroup>
<col style="width: 50%">
<col style="width: 50%">
</colgroup>
<thead>
<tr class="header">
<th>What you saved</th>
<th>What moves in 0.3.0</th>
</tr>
</thead>
<tbody>
<tr class="odd">
<td>Equal-frequency bins with missing predictors</td>
<td>Missing rows get their own bin, the cuts come from rows with a value, and the top interval count and total information value move (1,130 to 1,103; 0.06 to 0.04 in the <code>age</code> example)</td>
</tr>
<tr class="even">
<td>Bins on tied values</td>
<td>Tied values stay in one bin: ask for 5, get the 2 it can build, and the dummies follow the bins returned</td>
</tr>
<tr class="odd">
<td>Winsorized bins</td>
<td>The clamps bound the fit and the score; a saved 0.2.1 object ignored them, could not be scored, and <code>rbin_create()</code> stopped on a length mismatch</td>
</tr>
<tr class="even">
<td>Bins with missing responses</td>
<td>Rows without an outcome are dropped with a warning that gives the count, and the summary describes the complete cases</td>
</tr>
</tbody>
</table>
</section>
<section id="other-improvements" class="level2">
<h2 class="anchored" data-anchor-id="other-improvements">Other improvements</h2>
<ul>
<li>Bare column names, strings and variables that hold names work in every numeric binning function and in <code>rbin_create()</code>, including names with spaces or punctuation.</li>
<li>Character responses are sorted in the same order on every machine, so the second value is always the event; declare the response as a factor to choose the event level yourself.</li>
<li>Empty intervals keep zero counts and undefined rates and weight of evidence, with zero information value and entropy, instead of dropping out of the summary.</li>
<li><code>rbin_factor()</code> groups on integer IDs, so two distinct categories whose printed text looks the same stay separate, and an explicit <code>NA</code> factor level stays separate from a missing code.</li>
<li><code>rbin_create()</code> keeps bin order, keeps a column for a bin with no rows, makes colliding boundary labels distinct, and scores values outside the training range into the outer intervals (<a href="https://github.com/rsquaredacademy/rbin/issues/67" rel="nofollow" target="_blank">#67</a>).</li>
<li>A character predictor is no longer ignored: the numeric methods stop and point to <code>rbin_factor()</code> or <code>rbin_factor_create()</code> (<a href="https://github.com/rsquaredacademy/rbin/issues/70" rel="nofollow" target="_blank">#70</a>). 64-bit integers (<code>integer64</code>) and time differences (<code>difftime</code>) are refused with a message showing how to convert them.</li>
<li>Every method and both addins accept <code>data.table</code> input, and a response that is not 0/1, logical or a two-level factor or character stops with a message.</li>
<li>The package no longer checks CRAN for updates when it is attached.</li>
</ul>
</section>
<section id="whats-next" class="level2">
<h2 class="anchored" data-anchor-id="whats-next">What’s next</h2>
<p>Known issue: a bin with no events or no non-events gets an infinite weight of evidence and information value (<a href="https://github.com/rsquaredacademy/rbin/issues/68" rel="nofollow" target="_blank">#68</a>).</p>
<p>The other open reports concern input checks and messages, not results: argument names in errors and the addins (<a href="https://github.com/rsquaredacademy/rbin/issues/80" rel="nofollow" target="_blank">#80</a>), a one-column matrix predictor (<a href="https://github.com/rsquaredacademy/rbin/issues/79" rel="nofollow" target="_blank">#79</a>), and the conversion hints for date and time predictors (<a href="https://github.com/rsquaredacademy/rbin/issues/77" rel="nofollow" target="_blank">#77</a>). The first two are fixed on the development branch and will be in the next release.</p>
</section>
<section id="install-from-cran" class="level2">
<h2 class="anchored" data-anchor-id="install-from-cran">Install from CRAN</h2>
<div class="cell">
<details open="" class="code-fold">
<summary>Code</summary>
<pre>install.packages(&quot;rbin&quot;)</pre>
</details>
</div>
<p>You can see a full list of changes in the <a href="https://rbin.rsquaredacademy.com/news/" rel="nofollow" target="_blank">release notes</a>.</p>
<div class="ba-note">
<p>How we checked: every 0.3.0 number in this post comes from the code shown, run on CRAN rbin 0.3.0. The 0.2.1 figures come from the same scripts run on CRAN 0.2.1; the scripts and transcripts are in this post’s <code>runs/</code> folder.</p>
</div>
</section>
<section id="acknowledgements" class="level2">
<h2 class="anchored" data-anchor-id="acknowledgements">Acknowledgements</h2>
<p><code>rbin</code> is maintained by Aravind Hebbali. Issues and pull requests are welcome at <a href="https://github.com/rsquaredacademy/rbin" rel="nofollow" target="_blank">github.com/rsquaredacademy/rbin</a>.</p>


</section>

 
<div style="border: 1px solid; background: none repeat scroll 0 0 #EDEDED; margin: 1px; font-size: 13px;">
<div style="text-align: center;">To <strong>leave a comment</strong> for the author, please follow the link and comment on their blog: <strong><a href="https://blog.rsquaredacademy.com/posts/rbin-0-3-0/"> Rsquared Academy Blog</a></strong>.</div>
<hr />
<a href="https://www.r-bloggers.com/" rel="nofollow">R-bloggers.com</a> offers <strong><a href="https://feedburner.google.com/fb/a/mailverify?uri=RBloggers" rel="nofollow">daily e-mail updates</a></strong> about <a title="The R Project for Statistical Computing" href="https://www.r-project.org/" rel="nofollow">R</a> news and tutorials about <a title="R tutorials" href="https://www.r-bloggers.com/how-to-learn-r-2/" rel="nofollow">learning R</a> and many other topics. <a title="Data science jobs" href="https://www.r-users.com/" rel="nofollow">Click here if you're looking to post or find an R/data-science job</a>.

<hr>Want to share your content on R-bloggers?<a href="https://www.r-bloggers.com/add-your-blog/" rel="nofollow"> click here</a> if you have a blog, or <a href="http://r-posts.com/" rel="nofollow"> here</a> if you don't.
</div><strong>Continue reading</strong>: <a href="https://www.r-bloggers.com/2026/11/rbin-0-3-0/">rbin 0.3.0</a>]]></content:encoded>
					
		
		<enclosure url="https://blog.rsquaredacademy.com/img/rbin-0-3-0.png" length="0" type="image/png" />

		<post-id xmlns="com-wordpress:feed-additions:1">405182</post-id>	</item>
		<item>
		<title>On the Thélyson Orélien &#8216;scandal&#8217; and the use of AI for writing</title>
		<link>https://www.r-bloggers.com/2026/11/on-the-thelyson-orelien-scandal-and-the-use-of-ai-for-writing/</link>
		
		<dc:creator><![CDATA[T. Moudiki]]></dc:creator>
		<pubDate>Sat, 28 Nov 2026 00:00:00 +0000</pubDate>
				<category><![CDATA[R bloggers]]></category>
		<guid isPermaLink="false">https://thierrymoudiki.github.io//blog/2026/11/28/r/python/AI-for-writing</guid>

					<description><![CDATA[<div style = "width:60%; display: inline-block; float:left; "> Since the Thélyson Orélien 'scandal', I've been thinking about whether a classifier can actually detect a writing style. No, I'm not a Natural Language Processing expert (yet). But I've used classifiers a bit and seen some of their results, and any classifier needs a way to encode text ...</div>
<div style = "width: 40%; display: inline-block; float:right;"></div>
<div style="clear: both;"></div>
<strong>Continue reading</strong>: <a href="https://www.r-bloggers.com/2026/11/on-the-thelyson-orelien-scandal-and-the-use-of-ai-for-writing/">On the Thélyson Orélien ‘scandal’ and the use of AI for writing</a>]]></description>
										<content:encoded><![CDATA[<!-- 
<div style="min-height: 30px;">
[social4i size="small" align="align-left"]
</div>
-->

<div style="border: 1px solid; background: none repeat scroll 0 0 #EDEDED; margin: 1px; font-size: 12px;">
[This article was first published on  <strong><a href="https://thierrymoudiki.github.io//blog/2026/11/28/r/python/AI-for-writing"> T. Moudiki's Webpage - R</a></strong>, and kindly contributed to <a href="https://www.r-bloggers.com/" rel="nofollow">R-bloggers</a>].  (You can report issue about the content on this page <a href="https://www.r-bloggers.com/contact-us/">here</a>)
<hr>Want to share your content on R-bloggers?<a href="https://www.r-bloggers.com/add-your-blog/" rel="nofollow"> click here</a> if you have a blog, or <a href="http://r-posts.com/" rel="nofollow"> here</a> if you don't.
</div>
<p><strong>Disclaimer (or not, I’m comfortable with it):</strong> I co-edited this piece, based on my initial thoughts, with seven LLMs, using their default versions as of 2026-11-15 (Claude, ChatGPT, Gemini, DeepSeek, Qwen, Grok, and Mistral). What mattered to me was the essence of the argument more than the exact wording. The final version is my own (is it? Has this been settled yet? I don’t know). Any remaining errors are mine, and I take full responsibility for them. Read it from end to end; skip whatever you don’t fully get.</p>

<p>The subject is in the disclaimer.</p>

<p>Since the Thélyson Orélien “scandal”, I’ve been thinking about whether a classifier can actually detect a writing style. No, I’m not a Natural Language Processing expert (yet). But I’ve used classifiers a bit and seen some of their results. In this post, I’ll look at what a detector’s output numbers can—and cannot—tell us about who wrote a text. I won’t settle the authorship question. I do think, however, that the case raises some important points.</p>

<h2 id="the-case">The case</h2>

<p>In September 2026, Haitian-Canadian writer Thélyson Orélien won the Prix Première Plume for his debut novel, <em>C’était ça ou mourir</em>, published by Grasset [1]. A few weeks later, an X account called “Balance ton Claude” accused him of having written much of the book with generative AI. One of the account’s co-creators said he had analyzed excerpts using Pangram [2]. According to press reports, the detector returned a “100% probability” that the text was AI-generated [3].</p>

<p>Orélien denied that a single sentence of the novel had been produced by a machine, while acknowledging plagiarism in some older texts and apologizing for it [2,3]. His publisher, Boréal, initially stood by him [3]. On 21 October, however, it announced that AI had been used, citing new information without specifying exactly what it was. It also acknowledged that the extent of the use remained unknown [4].</p>

<p>I’m not going to settle the case here. It is, in many ways, <strong>100% representative of the permanent hysteria that now seems to accompany every online debate</strong>. But one thing is worth separating from the rest: the detector’s score became part of a public accusation. A score can be statistical evidence, and it can be challenged or manipulated through the experimental protocol. It is not proof of authorship.</p>

<p>There is also a basic distinction worth keeping in mind: the percentages reported by Pangram are shares of text, not probabilities that a person used AI. We’ll come back to that.</p>

<h2 id="a-small-experiment-in-adversarial-reviewing">A small experiment in adversarial reviewing</h2>

<p>The scandal hasn’t stopped me from using AI, though. At least for one thing: <strong>adversarial paper-reviewing</strong>.</p>

<p>Since ChatGPT’s arrival in 2023, the flood of LLM-written and LLM-polished papers has made it increasingly difficult to separate useful work from AI slop. I don’t want to waste time reviewing submissions that are obviously wrong or contain fabricated claims. And, because of <a href="https://www.change.org/stop_torturing_T_Moudiki" rel="nofollow" target="_blank">my specific context</a>, I also have to account for the not so occasional troll, clown, or their entire gang.</p>

<p>So I started experimenting with what I call <strong>adversarial review</strong>. Several LLMs independently review a paper, looking for flaws. Their reviews are then confronted with one another, and the disagreements become part of the process. It is closer to a review panel than to Daniel Kahneman’s idea of adversarial collaboration, where opponents jointly design an experiment [7]. But the spirit is similar: <strong>let disagreement do the work</strong>.</p>

<p>I tried this approach on Pangram’s technical report [8], using seven LLMs: one main reviewer and six independent reviewers. Each first produced a review of its own. The main reviewer then consolidated the feedback, and the group went through several rounds until it reached what I considered a reasonably satisfying consensus.</p>

<p>The report offered a useful case study: not only in AI-text detection, but in how much trust we should place in a headline number.</p>

<h2 id="how-much-can-we-trust-the-headline-number">How much can we trust the headline number?</h2>

<p>Pangram 4’s technical report gives three impressive figures: an AUROC of 0.9916, a false positive rate (FPR) of 0.0041%, and a false negative rate (FNR) of 0.3396% [8].</p>

<p><strong>A 0.99 AUROC is often a reason to look more closely when dealing with messy real-world data</strong>. But before getting to that, let’s unpack the numbers.</p>

<p>A classifier takes a text and labels it either “AI” or “Human”. That gives us four possible outcomes:</p>

<table>
  <thead>
    <tr>
      <th>Actual text</th>
      <th>Verdict: “AI”</th>
      <th>Verdict: “Human”</th>
    </tr>
  </thead>
  <tbody>
    <tr>
      <td>AI</td>
      <td>True positive (TP)</td>
      <td>False negative (FN)</td>
    </tr>
    <tr>
      <td>Human</td>
      <td>False positive (FP)</td>
      <td>True negative (TN)</td>
    </tr>
  </tbody>
</table>

<p>The rates below are calculated row by row: each one tells us what proportion of texts in a given actual category received a particular verdict.</p>

<table>
  <thead>
    <tr>
      <th>Rate</th>
      <th>Formula</th>
      <th>In words</th>
      <th style="text-align: right">Pangram 4 [8]</th>
    </tr>
  </thead>
  <tbody>
    <tr>
      <td>False negative rate (FNR)</td>
      <td>FN / (TP + FN)</td>
      <td>AI texts incorrectly classified as human</td>
      <td style="text-align: right">0.3396%</td>
    </tr>
    <tr>
      <td>True positive rate (TPR, sensitivity)</td>
      <td>1 − FNR</td>
      <td>AI texts correctly classified as AI</td>
      <td style="text-align: right">99.6604%</td>
    </tr>
    <tr>
      <td>False positive rate (FPR)</td>
      <td>FP / (FP + TN)</td>
      <td>Human texts incorrectly classified as AI</td>
      <td style="text-align: right">0.0041% (≈ 1 in 24,000)</td>
    </tr>
    <tr>
      <td>True negative rate (TNR, specificity)</td>
      <td>1 − FPR</td>
      <td>Human texts correctly classified as human</td>
      <td style="text-align: right">99.9959%</td>
    </tr>
  </tbody>
</table>

<p>These numbers describe performance at a particular classification threshold. But a detector doesn’t just produce a yes-or-no verdict: it first gives each text a score. A threshold determines whether that score is interpreted as “AI” or “Human”.</p>

<p>Lowering the threshold means more texts are classified as AI. That catches more AI-generated texts, increasing the true positive rate, but it also means more human texts get wrongly flagged, increasing the false positive rate. Raising the threshold does the opposite.</p>

<p>The <strong>ROC curve</strong> lays out all these possible trade-offs, plotting the true positive rate against the false positive rate as the threshold changes. The <strong>AUROC</strong>—the area under that curve—summarizes the detector’s performance across all thresholds, rather than at just one particular setting.</p>

<p><img src="https://i0.wp.com/thierrymoudiki.github.io/images/2026-11-28/2026-11-28-image0.png?w=578&#038;ssl=1" alt="ROC Curve." class="img-responsive" data-recalc-dims="1" /></p>

<p>There is a more intuitive way to understand AUROC [9]. Imagine a tournament in which every AI text competes against every human text. The detector wins a duel whenever it gives the AI text a higher score than the human text. The AUROC is the proportion of duels it wins.</p>

<p>Why does an area correspond to a win rate? Consider a toy example with three AI texts, scored 0.9, 0.8, and 0.4, and three human texts, scored 0.7, 0.3, and 0.2. There are nine possible duels.</p>

<p>As we lower the threshold, the ROC curve moves up whenever an AI text is passed and right whenever a human text is passed. Each cell in the 3 × 3 grid represents one duel. The cells under the curve correspond exactly to the duels in which the AI text has the higher score.</p>

<p>In this example, the detector wins eight out of nine duels. Its AUROC is therefore 8/9.</p>

<p><img src="https://i1.wp.com/thierrymoudiki.github.io/images/2026-11-28/2026-11-28-image1.png?w=578&#038;ssl=1" alt="Why an area is a win rate: on a 3 × 3 grid of duels, the cells under the ROC curve are exactly the duels won, here 8 out of 9." class="img-responsive" data-recalc-dims="1" /></p>

<h2 id="a-small-problem-with-the-reported-auroc">A small problem with the reported AUROC</h2>

<p>Now let’s return to Pangram’s figures.</p>

<p>The report gives a true positive rate of 99.6604% and a true negative rate of 99.9959%. In section 5.1, it explains that the AUROC ranks texts according to a post-processed, weighted share of AI characters. The final verdicts are based on those same character shares: a score of at least 0.8 means “AI”, while a score of at most 0.1 means “Human” [8].</p>

<p>That creates an interesting constraint.</p>

<p>Every duel between a true positive and a true negative is guaranteed to be a win for the detector: the AI text has a score of at least 0.8, while the human text has a score of at most 0.1.</p>

<p>The proportion of all possible duels of this kind is simply:</p>

<p>[
TPR \times TNR
= 99.6604\% \times 99.9959\%
\approx 99.656\%.
]</p>

<p>So at least 99.656% of all duels must be wins. The remaining 0.344% are undecided: the detector could win or lose them.</p>

<p>Even in the worst possible case, where it loses every one of those remaining duels, its AUROC cannot be lower than 0.99656.</p>

<p>That’s a lower bound, not an estimate. Given the report’s own error rates, the AUROC should be somewhere between 0.99656 and 1—provided the rates and the AUROC are computed on the same texts, with the same definitions and the same underlying score.</p>

<p>But the report gives an AUROC of 0.9916. That implies a loss rate of 0.84% of all duels, more than twice the maximum 0.344% that the reported error rates would allow.</p>

<p><img src="https://i2.wp.com/thierrymoudiki.github.io/images/2026-11-28/2026-11-28-image2.png?w=578&#038;ssl=1" alt="The duel picture: guaranteed wins cover at least 99.656% of all duels, so the share of lost duels can't exceed 0.344%, while the reported AUROC implies 0.84%." class="img-responsive" data-recalc-dims="1" /></p>

<p>There are several possible explanations. The contradiction only holds if all three figures are calculated on the same texts, if the AUROC ranks the same final scores used to produce the verdicts, and if the same definitions of positive and negative are used throughout.</p>

<p>The report doesn’t establish all of these conditions. It gives the AUROC in the abstract, but doesn’t clearly identify the texts used to calculate it. Perhaps the AUROC was measured on a different evaluation set. Perhaps the metrics were calculated at different levels, such as text segments versus whole documents. Or perhaps the figure was simply reported incorrectly.</p>

<p>We can’t tell from the report alone.</p>

<p>Funnily enough, the problem isn’t that the AUROC is too good: it sits <strong>below the floor set by the report’s own error rates</strong>.</p>

<p>Of the six other LLM reviewers, one reached the same conclusion. Four repeated the 0.9916 figure without questioning it, and one omitted it altogether. Again: an anecdote, not a statistic.</p>

<h2 id="is-an-auroc-of-099-suspicious">Is an AUROC of 0.99 suspicious?</h2>

<p>In a noisy, <a href="https://en.wikipedia.org/wiki/Statistical_classification" rel="nofollow" target="_blank">real-world tabular classification</a> problem, an AUROC close to 1 is often a reason to investigate possible feature leakage. But the key question is whether the test set resembles the data the model will encounter in practice.</p>

<p>In AI-text detection, near-perfect scores are not unusual when the test data closely resemble the training data. Pangram’s appendix includes a DetectRL benchmark in which a supervised RoBERTa model reaches an AUROC of 99.98% in-domain, while its F1 score drops to 83 on an unseen domain [8].</p>

<p>The distinction matters. Raw chatbot output compared with pre-ChatGPT human writing can be relatively easy to separate. Edited, mixed, or paraphrased text encountered in everyday use is a much harder problem.</p>

<p>So the right question isn’t “Is 0.99 too high?” It’s “How much does the test set look like the real world?”</p>

<p>There are at least three ways a benchmark can fail to answer that question.</p>

<p><strong>First, <a href="https://en.wikipedia.org/wiki/Overfitting" rel="nofollow" target="_blank">overfitting</a>.</strong> If researchers repeatedly tune a model against the same test set, they gradually adapt it to that particular set, even if they never train directly on it.</p>

<p><strong>Second, mismatch.</strong> A test set may not represent the data the model will encounter in practice. A model can perform brilliantly on one kind of text and struggle on another.</p>

<p><strong>Third, obsolescence.</strong> The test set may no longer reflect current chatbots or contemporary human writing.</p>

<p>A meta-analysis of more than 100 Kaggle competitions found little evidence of overfitting to public leaderboards [10]. One reason is that the public and private leaderboard sets were random draws from the same underlying pool. The situation becomes more complicated when the test data don’t represent the same population.</p>

<p>For example, researchers rebuilt the ImageNet test set using the original collection procedure. Model accuracy fell by 11–14%, although the relative rankings of models remained mostly stable [11]. The models hadn’t simply memorized the test images; they had learned to exploit aspects of the test set that made it easier than the broader task.</p>

<p>Repeatedly using a test set also erodes its value. One proposed solution is to ration access to it, preserving a holdout set for evaluation [12].</p>

<p>AI detectors face all three problems, plus one: <strong>contamination</strong>. Public benchmarks may end up in the training data of the very models being evaluated. When a vendor says it hasn’t trained on a benchmark, you often have to take its word for it—or avoid relying on that evaluation altogether.</p>

<h2 id="what-exactly-is-a-detector-detecting">What exactly is a detector detecting?</h2>

<p>So far, I’ve questioned one number. But even a perfectly measured number leaves a bigger question: what, exactly, is being detected?</p>

<p>A classifier detects patterns. It might pick up on word choices, sentence structures, punctuation, or habits involving semicolons and dashes. This is not fundamentally different from traditional authorship attribution. Researchers have, for example, used word frequencies to argue that James Madison wrote disputed Federalist Papers [13].</p>

<p>But writing style isn’t fixed. It changes with age, experience, influences, and what we read. Editors, co-authors, spellcheckers, and now LLMs can all contribute to a text. At some point, the idea of a purely individual writing style becomes difficult to sustain.</p>

<p>Pangram’s report acknowledges part of this problem. It introduces an “AI-assisted” category for texts with entangled authorship (§3.3), and notes that detecting human writing influenced by LLMs remains an open problem (§6) [8].</p>

<p>To understand why, it helps to think about how chatbots are trained.</p>

<p>The first stage is pretraining: a model is exposed to enormous amounts of text and learns to predict the next word. In doing so, it learns patterns in human writing, including unusual expressions and awkward turns of phrase. If that were the whole story, a chatbot would be little more than an autocomplete system for the internet.</p>

<p>But it isn’t. A second stage teaches the model how to respond to instructions. This typically involves supervised fine-tuning on prompts and preferred answers [14], followed by some form of preference or reward optimization. Methods such as direct preference optimization [15] and constitutional AI [16] are part of this broader family of techniques.</p>

<p>In a sense, this second stage acts like an editor. But it doesn’t edit an individual text in the way a human editor would. It edits the distribution from which future texts are generated. Every future response is, in a sense, pre-edited.</p>

<p>And this editor is not one person with a distinctive taste. It is closer to a committee of raters whose preferences tend to average out. That can make the resulting writing more uniform and reduce diversity [17].</p>

<p>There is another step. During generation, sampling methods such as top-k and nucleus sampling help avoid the blandness of always choosing the most probable next word, while also preventing the model from wandering too far into unlikely sequences [18]. These methods can further shape the range of language that appears in the final output.</p>

<p>Of course, even the human text used in the first stage was already edited to some extent: books, newspapers, encyclopedias, and other published writing have passed through their own editorial processes.</p>

<p>My hypothesis is that detectors are often picking up on this accumulated editing, rather than some essential quality of “machine-ness”. This could help explain why heavily edited human writing, especially academic prose, can be flagged as AI-generated. In one experiment, Pangram’s errors were concentrated in academic writing and essays by non-native English speakers (§4.1) [8].</p>

<p>There is another possible explanation for the latter: the detector’s reference corpus of human writing may be too narrow. Language that falls outside its idea of typical human writing can then look AI-generated.</p>

<p>These explanations are not mutually exclusive. But they lead to a testable prediction: <strong>within the same writing register, heavily edited human writing should be flagged as AI more often than lightly edited writing.</strong></p>

<h2 id="how-far-apart-must-the-distributions-be">How far apart must the distributions be?</h2>

<p>There is also a theoretical result worth considering.</p>

<p>A paper by Sadasivan and colleagues [19] gives an upper bound on the AUROC of any detector:</p>

<p>[
AUROC \leq \frac{1}{2} + TV &#8211; \frac{TV^2}{2},
]</p>

<p>where (TV) is the total variation distance between the distributions of human-written and AI-generated text. It ranges from 0, when the distributions are identical, to 1, when they are completely separated.</p>

<p>Rearranging the inequality, an AUROC of 0.99 requires a total variation distance of at least approximately 0.86. For Pangram’s reported AUROC of 0.9916, the required distance is approximately 0.87.</p>

<p>This doesn’t tell us the actual distance between the two distributions. It tells us how far apart they must be, at a minimum, for a detector to achieve the reported AUROC.</p>

<p>In other words, the AI and human texts in Pangram’s test set must be quite different.</p>

<p>Another result suggests that detection is possible whenever the two distributions are not exactly identical, but that the closer they are, the more text is needed to distinguish them [20]. Estimating the share of AI-generated text across a large collection of web pages may therefore be feasible, while judging whether a single short student essay was written by AI is much harder.</p>

<p>And as humans increasingly pick up LLM habits, the distinction may become even less clear. Future models trained on web data containing large amounts of AI-generated text could also contribute to a loss of linguistic diversity [21].</p>

<p>Asymptotically, the question isn’t “human or machine?” anymore, but <strong>“isn’t all of this human?”</strong></p>

<h2 id="three-different-questions">Three different questions</h2>

<p>I think it helps to distinguish three questions that often get conflated:</p>

<ol>
  <li><strong>Does this text resemble the output of a language model?</strong></li>
  <li><strong>Was this text actually produced or substantially changed by AI?</strong></li>
  <li><strong>Who is responsible for what the text says?</strong></li>
</ol>

<p>A classifier can reasonably try to answer the first question. But that doesn’t automatically answer the second, and it certainly doesn’t answer the third.</p>

<p>For the second, provenance may be more useful than style. Watermarking is one possible approach [22]. Verifiable records of how a text was produced could also help. These methods require cooperation and can be attacked or circumvented [19], but at least they address a more clearly defined question.</p>

<p>The third question is not something a classifier can answer.</p>

<p>There is also a problem of causation. A detector may find a correlation between certain linguistic patterns and AI-generated text, but that doesn’t establish that AI caused those patterns. If human and AI texts are already similar, a classifier trained on examples of each may not be able to distinguish the underlying causes.</p>

<p>And a detector’s score should not automatically be interpreted as a probability of authorship. Pangram’s report explicitly says that its confidence score is not a calibrated probability that the label is correct (§4.3.5) [8].</p>

<p>Finally, there is the problem of reproducibility. Commercial incentives and scientific transparency don’t always point in the same direction. Pangram’s report describes its model backbone only as “a popular open-weight MoE model” (§4.1) [8]. That makes it difficult for outsiders to reproduce the system.</p>

<p>The evaluation data matter just as much. In its Pangram 4.1 model card, the company says it revisited the English human test set behind earlier headline numbers and removed “junk text such as spam, advertising and programmatically generated documents” [23].</p>

<p>The company describes the cleaned set as more challenging. The recalibrated false positive rate is approximately 1 in 10,000, compared with 1 in 24,000 for Pangram 4. That is 2.4 times higher. The model version also changed, so we can’t isolate the effect of cleaning the test set. But it does illustrate how much a headline number can depend on the evaluation data.</p>

<p>I get it, though: if I open-source my adversarial reviewer, will I make millions, or the opposite?</p>

<h2 id="so-what-matters">So, what matters?</h2>

<p>All of which brings me back to the question underneath the metrics.</p>

<p><strong>What’s important eventually: the pleasure of reading? Whether someone wrote it with ink from Tanzania or Mongolia? Or whether it reflects more precisely what’s inside their heart?</strong></p>

<h2 id="references">References</h2>

<p>[1] Livres Hebdo (2026, September 3). Thélyson Orélien, lauréat du prix Première Plume 2026. https://www.livreshebdo.fr/article/thelyson-orelien-laureat-du-prix-premiere-plume-2026</p>

<p>[2] Sud Radio / AFP (2026, October 13). Thélyson Orélien dément avoir utilisé l’IA mais reconnaît des plagiats. https://www.sudradio.fr/societe/thelyson-orelien-dement-avoir-utilise-lia-mais-reconnait-des-plagiats</p>

<p>[3] Kuwait Times / AFP (2026, October 14). Canadian publisher supports Orelien after AI denial. https://kuwaittimes.com/article/51626/lifestyle/art-fashion/canadian-publisher-supports-orelien-after-ai-denial/</p>

<p>[4] Euronews (2026, October 21). Thélyson Orélien row: publisher says AI used to write “C’était ça ou mourir”. https://www.euronews.com/2026/10/21/thelyson-orelien-row-publisher-says-ai-used-to-write-cetait-ca-ou-mourir</p>

<p>[5] Kobak, D., González-Márquez, R., Horvát, E.-Á., &#038; Lause, J. (2025). Delving into LLM-assisted writing in biomedical publications through excess vocabulary. Science Advances, 11(27), eadt3813. https://doi.org/10.1126/sciadv.adt3813</p>

<p>[6] Liang, W., Zhang, Y., Wu, Z., Lepp, H., et al. (2024). Mapping the increasing use of LLMs in scientific papers. COLM 2024. https://arxiv.org/abs/2404.01268</p>

<p>[7] Mellers, B., Hertwig, R., &#038; Kahneman, D. (2001). Do frequency representations eliminate conjunction effects? An exercise in adversarial collaboration. Psychological Science, 12(4), 269–275. https://doi.org/10.1111/1467-9280.00350</p>

<p>[8] Glickenhaus, B., Thai, K., Russell, J., Masrour, E., Han, Y., Spero, M., &#038; Emi, B. (2026). Pangram 4 Technical Report. arXiv:2607.27183. https://arxiv.org/abs/2607.27183</p>

<p>[9] Hanley, J. A., &#038; McNeil, B. J. (1982). The meaning and use of the area under a receiver operating characteristic (ROC) curve. Radiology, 143(1), 29–36. https://doi.org/10.1148/radiology.143.1.7063747</p>

<p>[10] Roelofs, R., Shankar, V., Recht, B., Fridovich-Keil, S., Hardt, M., Miller, J., &#038; Schmidt, L. (2019). A meta-analysis of overfitting in machine learning. NeurIPS 32. https://papers.nips.cc/paper/9117-a-meta-analysis-of-overfitting-in-machine-learning</p>

<p>[11] Recht, B., Roelofs, R., Schmidt, L., &#038; Shankar, V. (2019). Do ImageNet classifiers generalize to ImageNet? Proceedings of ICML, PMLR 97, 5389–5400. https://arxiv.org/abs/1902.10811</p>

<p>[12] Dwork, C., Feldman, V., Hardt, M., Pitassi, T., Reingold, O., &#038; Roth, A. (2015). The reusable holdout: Preserving validity in adaptive data analysis. Science, 349(6248), 636–638. https://doi.org/10.1126/science.aaa9375</p>

<p>[13] Mosteller, F., &#038; Wallace, D. L. (1963). Inference in an authorship problem. Journal of the American Statistical Association, 58(302), 275–309. https://gwern.net/doc/statistics/bayes/1963-mosteller.pdf (expanded as the 1964 book <em>Inference and Disputed Authorship: The Federalist</em>: https://casbs.stanford.edu/inference-and-disputed-authorship-federalist)</p>

<p>[14] Ouyang, L., Wu, J., Jiang, X., et al. (2022). Training language models to follow instructions with human feedback. NeurIPS 35. https://arxiv.org/abs/2203.02155</p>

<p>[15] Rafailov, R., Sharma, A., Mitchell, E., Manning, C. D., Ermon, S., &#038; Finn, C. (2023). Direct preference optimization: Your language model is secretly a reward model. NeurIPS 36. https://proceedings.neurips.cc/paper_files/paper/2023/hash/a85b405ed65c6477a4fe8302b5e06ce7-Abstract.html</p>

<p>[16] Bai, Y., Kadavath, S., Kundu, S., Askell, A., et al. (2022). Constitutional AI: Harmlessness from AI feedback. arXiv:2212.08073. https://arxiv.org/abs/2212.08073</p>

<p>[17] Kirk, R., Mediratta, I., Nalmpantis, C., Luketina, J., Hambro, E., Grefenstette, E., &#038; Raileanu, R. (2024). Understanding the effects of RLHF on LLM generalisation and diversity. ICLR 2024. https://arxiv.org/abs/2310.06452</p>

<p>[18] Holtzman, A., Buys, J., Du, L., Forbes, M., &#038; Choi, Y. (2020). The curious case of neural text degeneration. ICLR 2020. https://arxiv.org/abs/1904.09751</p>

<p>[19] Sadasivan, V. S., Kumar, A., Balasubramanian, S., Wang, W., &#038; Feizi, S. (2023). Can AI-generated text be reliably detected? arXiv:2303.11156. https://arxiv.org/abs/2303.11156</p>

<p>[20] Chakraborty, S., Bedi, A. S., Zhu, S., An, B., Manocha, D., &#038; Huang, F. (2023). On the possibilities of AI-generated text detection. arXiv:2304.04736. https://arxiv.org/abs/2304.04736</p>

<p>[21] Shumailov, I., Shumaylov, Z., Zhao, Y., Papernot, N., Anderson, R., &#038; Gal, Y. (2024). AI models collapse when trained on recursively generated data. Nature, 631, 755–759. https://doi.org/10.1038/s41586-024-07566-y</p>

<p>[22] Kirchenbauer, J., Geiping, J., Wen, Y., Katz, J., Miers, I., &#038; Goldstein, T. (2023). A watermark for large language models. Proceedings of ICML, PMLR 202, 17061–17084. https://arxiv.org/abs/2301.10226</p>

<p>[23] Pangram Labs (2026). Pangram 4.1 Model Card. https://www.pangram.com/research/model-card/pangram-4-1</p>

<div style="border: 1px solid; background: none repeat scroll 0 0 #EDEDED; margin: 1px; font-size: 13px;">
<div style="text-align: center;">To <strong>leave a comment</strong> for the author, please follow the link and comment on their blog: <strong><a href="https://thierrymoudiki.github.io//blog/2026/11/28/r/python/AI-for-writing"> T. Moudiki's Webpage - R</a></strong>.</div>
<hr />
<a href="https://www.r-bloggers.com/" rel="nofollow">R-bloggers.com</a> offers <strong><a href="https://feedburner.google.com/fb/a/mailverify?uri=RBloggers" rel="nofollow">daily e-mail updates</a></strong> about <a title="The R Project for Statistical Computing" href="https://www.r-project.org/" rel="nofollow">R</a> news and tutorials about <a title="R tutorials" href="https://www.r-bloggers.com/how-to-learn-r-2/" rel="nofollow">learning R</a> and many other topics. <a title="Data science jobs" href="https://www.r-users.com/" rel="nofollow">Click here if you're looking to post or find an R/data-science job</a>.

<hr>Want to share your content on R-bloggers?<a href="https://www.r-bloggers.com/add-your-blog/" rel="nofollow"> click here</a> if you have a blog, or <a href="http://r-posts.com/" rel="nofollow"> here</a> if you don't.
</div><strong>Continue reading</strong>: <a href="https://www.r-bloggers.com/2026/11/on-the-thelyson-orelien-scandal-and-the-use-of-ai-for-writing/">On the Thélyson Orélien ‘scandal’ and the use of AI for writing</a>]]></content:encoded>
					
		
		<enclosure url="" length="0" type="" />

		<post-id xmlns="com-wordpress:feed-additions:1">405155</post-id>	</item>
		<item>
		<title>When will that elevator arrive?  Elevator dispatching</title>
		<link>https://www.r-bloggers.com/2026/11/when-will-that-elevator-arrive-elevator-dispatching/</link>
		
		<dc:creator><![CDATA[Jerry Tuttle]]></dc:creator>
		<pubDate>Fri, 27 Nov 2026 19:30:35 +0000</pubDate>
				<category><![CDATA[R bloggers]]></category>
		<guid isPermaLink="false">http://www.r-bloggers.com/?guid=7a577585c08837cd634eb4b073ee3761</guid>

					<description><![CDATA[<div style = "width:60%; display: inline-block; float:left; ">
<p>      </p>
<p>I was recently at a high-rise building with 23 floors and 6 elevators.  There always seemed to be a long wait for an elevator.  This made me think:  there must be elevator algorithms where the set of elevators d...</p></div>
<div style = "width: 40%; display: inline-block; float:right;"></div>
<div style="clear: both;"></div>
<strong>Continue reading</strong>: <a href="https://www.r-bloggers.com/2026/11/when-will-that-elevator-arrive-elevator-dispatching/">When will that elevator arrive?  Elevator dispatching</a>]]></description>
										<content:encoded><![CDATA[<!-- 
<div style="min-height: 30px;">
[social4i size="small" align="align-left"]
</div>
-->

<div style="border: 1px solid; background: none repeat scroll 0 0 #EDEDED; margin: 1px; font-size: 12px;">
[This article was first published on  <strong><a href="https://onlinecollegemathteacher.blogspot.com/2026/11/when-will-that-elevator-arrive-elevator.html"> Online College Math Teacher</a></strong>, and kindly contributed to <a href="https://www.r-bloggers.com/" rel="nofollow">R-bloggers</a>].  (You can report issue about the content on this page <a href="https://www.r-bloggers.com/contact-us/">here</a>)
<hr>Want to share your content on R-bloggers?<a href="https://www.r-bloggers.com/add-your-blog/" rel="nofollow"> click here</a> if you have a blog, or <a href="http://r-posts.com/" rel="nofollow"> here</a> if you don't.
</div>
<font size = 3>
  
<div class="separator" style="clear: both;"><a href="https://i2.wp.com/blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEglGRbu38Ag99_uKYvAsuFYLDO94Rh6Fgs2JPvxI9hEMTbz5ioopMgPqdBQjO-YhjoiM3L1StIVARj85NajxBHsNZPauffcoLwPIhFPleWY19DmeuU_iQUGLm4ZZSyQoAXf8vRyqZVPnyvcYO3knRioJvMfjxLRo_A4oQkEN5Z4FGLtpMF-4GUTNGs7o_Y/s1536/elevator.png?ssl=1" style="display: block; padding: 1em 0; text-align: center; " rel="nofollow" target="_blank"><img alt="" border="0" width="450" data-original-height="1024" data-original-width="450" src="https://i0.wp.com/blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEglGRbu38Ag99_uKYvAsuFYLDO94Rh6Fgs2JPvxI9hEMTbz5ioopMgPqdBQjO-YhjoiM3L1StIVARj85NajxBHsNZPauffcoLwPIhFPleWY19DmeuU_iQUGLm4ZZSyQoAXf8vRyqZVPnyvcYO3knRioJvMfjxLRo_A4oQkEN5Z4FGLtpMF-4GUTNGs7o_Y/s400/elevator.png?resize=450%2C1024&#038;ssl=1" data-recalc-dims="1"/></a></div>
  
      

I was recently at a high-rise building with 23 floors and 6 elevators.  There always seemed to be a long wait for an elevator.  This made me think:  there must be elevator algorithms where the set of elevators decides which one will answer your call. And of course there are.  Elevator dispatching falls under operations research, optimization, queuing theory, etc.<p>
 
      
Suppose I am on floor 11 and I press &#8220;Down.&#8221;  Some of the inputs to the algorithm might be: <br>
  

<ol>
  <li>Which elevators are currently moving down?</li>
  <li>Which are closest?</li>
  <li>How many stops are already scheduled?</li>
  <li>How full is each elevator?</li>
  <li>How long would I wait?</li>
</ol><p>
  
      
  The simplest modeling approach would be a nearest-elevator algorithm: when someone presses the down button, the elevator system assigns the passenger to the elevator that is physically closest in floors. This is an illustrative algorithm, not a standard industry algorithm.<p>
  
     
Let&#8217;s do some simulations in R. 
For a first approximation, we can make the following assumptions:
<ol>
  <li> The building has 23 floors, 6 elevators, and 5 passengers waiting to board. </li>
  <li> The elevators are initially distributed randomly throughout the building. </li>
  <li> Each elevator is stationary when the requests arrive. </li>
  <li> Each elevator travels at the same speed. </li>
  <li> The system assigns each passenger to the elevator closest to them in terms of floors, ignoring direction, waiting passengers, capacity, and existing assignments. </li>
  <li> Each elevator can be assigned multiple passengers.</li> 
  <li> The passenger assignments are calculated independently. The code does not update elevator routes after assigning a passenger. </li>
</ol><p>  
  

<pre> 
# nearest-elevator algorithm
set.seed(123)

# Building and elevator information
num_floors &lt;- 23
num_elevators &lt;- 6
num_passengers &lt;- 5

# Randomly position the six elevators
elevators &lt;- sample(1:num_floors, num_elevators,
                    replace = TRUE)

# Passenger floors
# Passenger 1 is you, on floor 11
passengers &lt;- c(11, sample(1:num_floors, 4,
                           replace = TRUE))

# Calculate assignments
assignments &lt;- data.frame(
  Passenger = 1:num_passengers,
  Floor = passengers,
  Elevator = NA,
  Distance = NA
)

for (i in 1:num_passengers) {

  # Distance from each elevator to passenger
  distances &lt;- abs(elevators - passengers[i])

  # Find closest elevator
  assignments$Elevator[i] &lt;- which.min(distances)   # If there is a tie, choose the first elevator.

  # Record distance
  assignments$Distance[i] &lt;- min(distances)
}

# Display elevator locations
cat(&quot;Elevator locations:\n&quot;)
print(elevators)

# Display passenger assignments
cat(&quot;\nPassenger assignments:\n&quot;)
print(assignments)
                             


Elevator locations:
[1] 15 19 14  3 10 18

Passenger assignments:
  Passenger Floor Elevator Distance
1         1    11        5        1
2         2    22        2        3
3         3    11        5        1
4         4     5        4        2
5         5    20        2        2


</pre>

      
In the simulation above, you (Passenger 1 on floor 11) are assigned to Elevator 5 on floor 10 because it is only 1 floor away, regardless of which direction it is moving. <p>

       
The nearest-elevator algorithm ignores an important factor: direction.

An elevator one floor away but moving in the wrong direction may take longer to reach you than an elevator several floors away that is already heading toward your floor.

A more useful approach is to estimate the time each elevator would take to reach the passenger. This is the basic idea behind an Estimated Time of Arrival (ETA) approach.

Our next simulation will consider each elevator's current floor, direction, and destination.

The important change is that we no longer assign a passenger solely on the basis of physical distance. Instead, we estimate how long each elevator would take to reach the passenger's floor. <p>

     

Assumptions for the simulation:

<ol>
  <li> There are 23 floors, 6 elevators, and 5 passengers waiting to board. </li>
  <li> Each elevator travels at one floor per second. </li>
  <li> Each elevator has a current floor, direction, and destination. </li>
  <li> Reversing direction adds a 2-second turnaround penalty. </li>
  <li> All five passengers request DOWN service. </li>
  <li> An elevator can accept multiple requests. </li>
  <li> We assign each passenger to the elevator with the shortest estimated arrival time. </li>
</ol><p>

For simplicity, we assume elevators reverse direction at their current destination and do not stop for intermediate passengers while estimating arrival time. <p>


<pre>
# Estimated Time of Arrival (ETA) algorithm
set.seed(123)

# Building specifications
num_floors &lt;- 23
num_elevators &lt;- 6

# Initialize elevators
elevators &lt;- data.frame(
  Elevator = 1:num_elevators,
  Floor = sample(1:num_floors, num_elevators, replace = TRUE),
  Direction = NA,
  Destination = NA
)

# Randomly assign elevator directions and destinations
for (i in 1:num_elevators) {
  
  possible_directions &lt;- c(-1, 0, 1)
  elevators$Direction[i] &lt;- sample(possible_directions, 1)
  
  # Prevent elevators from moving beyond building limits
  if (elevators$Floor[i] == 1 &#038;&#038; elevators$Direction[i] == -1) {
    elevators$Direction[i] &lt;- 0
  }
  
  if (elevators$Floor[i] == num_floors &#038;&#038; elevators$Direction[i] == 1) {
    elevators$Direction[i] &lt;- 0
  }
  
  # Assign a destination STRICTLY ahead of the current floor
  if (elevators$Direction[i] == 1) {
    up_floors &lt;- (elevators$Floor[i] + 1):num_floors
    elevators$Destination[i] &lt;- if (length(up_floors) == 1) up_floors else sample(up_floors, 1)
  } else if (elevators$Direction[i] == -1) {
    down_floors &lt;- 1:(elevators$Floor[i] - 1)
    elevators$Destination[i] &lt;- if (length(down_floors) == 1) down_floors else sample(down_floors, 1)
  } else {
    elevators$Destination[i] &lt;- elevators$Floor[i]
  }
}


# Function to estimate elevator arrival time for a DOWN request
# turnaround_penalty = 2 is an assumed penalty
arrival_time &lt;- function(current, direction, destination,
                         passenger_floor, passenger_dir = -1,
                         turnaround_penalty = 2) {
  
  # 1. Elevator is stationary
  if (direction == 0) {
    return(abs(current - passenger_floor))
  }
  
  # 2. Elevator is traveling UP
  if (direction == 1) {
    # Since the passenger wants to go DOWN (passenger_dir == -1), 
    # an UP elevator must finish its upward trip and reverse direction first.
    return((destination - current) +
             abs(destination - passenger_floor) +
             turnaround_penalty)
  }
  
  # 3. Elevator is traveling DOWN
  if (direction == -1) {
    # Check if the passenger is on or below the current floor, 
    # AND on or above the elevator's current destination
    if (passenger_floor = destination) {
      return(current - passenger_floor)
    } else if (passenger_floor &lt; destination) {
      # Passenger is further down in the SAME direction (no turnaround needed)
      return(current - passenger_floor)
    } else {
      # Passenger is ABOVE the elevator; elevator must finish going down,
      # reverse direction, and travel back up to the passenger
      return((current - destination) +
               abs(passenger_floor - destination) +
               turnaround_penalty)
    }
  }
}


# Passenger floors (Passenger 1 is on floor 11)
passengers &lt;- c(11, sample(1:num_floors, 4, replace = TRUE))

# Assign passengers to elevators
assignments &lt;- data.frame(
  Passenger = 1:5,
  Floor = passengers,
  Elevator = NA,
  Estimated_Time = NA
)

for (i in 1:5) {
  times &lt;- sapply(1:num_elevators, function(j) {
    arrival_time(
      elevators$Floor[j],
      elevators$Direction[j],
      elevators$Destination[j],
      passengers[i]
    )
  })
  
  best_elevator &lt;- which.min(times)
  assignments$Elevator[i] &lt;- best_elevator
  assignments$Estimated_Time[i] &lt;- times[best_elevator]
}

cat(&quot;\nELEVATOR STATUS\n&quot;)
print(elevators)

cat(&quot;\nPASSENGER ASSIGNMENTS\n&quot;)
print(assignments)


ELEVATOR STATUS
  Elevator Floor Direction Destination
1        1    15        -1          14
2        2    19        -1           9
3        3    14        -1          11
4        4     3         1          18
5        5    10         1          12
6        6    18         0          18

PASSENGER ASSIGNMENTS
  Passenger Floor Elevator Estimated_Time
1         1    11        3              3
2         2    22        6              4
3         3    11        3              3
4         4     5        2             14
5         5    20        6              2
</pre>
  
      
Here, Elevator 5 (floor 10) is moving upward toward floor 12, so the system instead assigns you to Elevator 3 on floor 14, which is already heading down and reaches you in 3 seconds. <p>

      
  More sophisticated systems use dynamic group control. They continually evaluate elevator positions, directions, existing calls, and predicted travel times. As new requests arrive or elevator conditions change, the system may revise its assignments.
<p>
  
Further Reading: Richard D. Peters, "Elevator Dispatching" (ELEVCON Paris 2014, Peters Research Ltd).<br> 
https://download.peters-research.com/library/Elevator_Dispatching.pdf <br>


####################################################################
<p>
End
</font>
<div style="border: 1px solid; background: none repeat scroll 0 0 #EDEDED; margin: 1px; font-size: 13px;">
<div style="text-align: center;">To <strong>leave a comment</strong> for the author, please follow the link and comment on their blog: <strong><a href="https://onlinecollegemathteacher.blogspot.com/2026/11/when-will-that-elevator-arrive-elevator.html"> Online College Math Teacher</a></strong>.</div>
<hr />
<a href="https://www.r-bloggers.com/" rel="nofollow">R-bloggers.com</a> offers <strong><a href="https://feedburner.google.com/fb/a/mailverify?uri=RBloggers" rel="nofollow">daily e-mail updates</a></strong> about <a title="The R Project for Statistical Computing" href="https://www.r-project.org/" rel="nofollow">R</a> news and tutorials about <a title="R tutorials" href="https://www.r-bloggers.com/how-to-learn-r-2/" rel="nofollow">learning R</a> and many other topics. <a title="Data science jobs" href="https://www.r-users.com/" rel="nofollow">Click here if you're looking to post or find an R/data-science job</a>.

<hr>Want to share your content on R-bloggers?<a href="https://www.r-bloggers.com/add-your-blog/" rel="nofollow"> click here</a> if you have a blog, or <a href="http://r-posts.com/" rel="nofollow"> here</a> if you don't.
</div><strong>Continue reading</strong>: <a href="https://www.r-bloggers.com/2026/11/when-will-that-elevator-arrive-elevator-dispatching/">When will that elevator arrive?  Elevator dispatching</a>]]></content:encoded>
					
		
		<enclosure url="" length="0" type="" />

		<post-id xmlns="com-wordpress:feed-additions:1">405153</post-id>	</item>
		<item>
		<title>LLM-driven optimisation modelling in R</title>
		<link>https://www.r-bloggers.com/2026/11/llm-driven-optimisation-modelling-in-r/</link>
		
		<dc:creator><![CDATA[R&#039;tichoke]]></dc:creator>
		<pubDate>Fri, 27 Nov 2026 18:30:00 +0000</pubDate>
				<category><![CDATA[R bloggers]]></category>
		<guid isPermaLink="false">https://rtichoke.netlify.app/posts/llm-written-optimisation-models.html</guid>

					<description><![CDATA[<p>When defining an optimisation problem, LLMs can be used as a translation layer. The solver is the calculator that does the actual work and makes no mistakes. The translator, however, could mistranslate occasionally. Still, as long as the problem ...</p>
<strong>Continue reading</strong>: <a href="https://www.r-bloggers.com/2026/11/llm-driven-optimisation-modelling-in-r/">LLM-driven optimisation modelling in R</a>]]></description>
										<content:encoded><![CDATA[<!-- 
<div style="min-height: 30px;">
[social4i size="small" align="align-left"]
</div>
-->

<div style="border: 1px solid; background: none repeat scroll 0 0 #EDEDED; margin: 1px; font-size: 12px;">
[This article was first published on  <strong><a href="https://rtichoke.netlify.app/posts/llm-written-optimisation-models.html"> R&#039;tichoke</a></strong>, and kindly contributed to <a href="https://www.r-bloggers.com/" rel="nofollow">R-bloggers</a>].  (You can report issue about the content on this page <a href="https://www.r-bloggers.com/contact-us/">here</a>)
<hr>Want to share your content on R-bloggers?<a href="https://www.r-bloggers.com/add-your-blog/" rel="nofollow"> click here</a> if you have a blog, or <a href="http://r-posts.com/" rel="nofollow"> here</a> if you don't.
</div>
 




<p>When defining an optimisation problem, LLMs can be used as a <strong>translation layer</strong>. The solver is the calculator that does the actual work and makes no mistakes. The translator, however, could mistranslate occasionally. Still, as long as the problem is specified well and translated correctly, the results are deterministic and reproducible.</p>
<p>This post focuses on building the whole chain in R:</p>
<ol type="1">
<li>Describe a credit risk problem statement in plain English</li>
<li>Let an LLM (via <code>ellmer</code>) translate the problem into <a href="https://dirkschumacher.github.io/ompr/" rel="nofollow" target="_blank"><code>ompr</code></a></li>
<li>Solve it with <a href="https://github.com/dirkschumacher/ompr.roi" rel="nofollow" target="_blank"><code>ompr.roi</code></a> + GLPK</li>
<li>Wrap it all in a reusable <code>nl_to_opt()</code> helper that re-prompts the LLM when the solver complains</li>
<li>Check the answer with LLM-generated controls</li>
</ol>
<div class="callout callout-style-default callout-note callout-titled">
<div class="callout-header d-flex align-content-center">
<div class="callout-icon-container">
<i class="callout-icon"></i>
</div>
<div class="callout-title-container flex-fill">
Note
</div>
</div>
<div class="callout-body-container callout-body">
<p>The post uses <a href="https://openrouter.ai/" rel="nofollow" target="_blank">OpenRouter</a> as the LLM provider. To run the code in this post, create an OpenRouter key and set it as the <code>OPENROUTER_API_KEY</code> environment variable (for example in your <code>.Renviron</code>).</p>
</div>
</div>
<section id="required-packages" class="level2">
<h2 class="anchored" data-anchor-id="required-packages">Required Packages</h2>
<div class="cell">
<pre># install.packages(c(&quot;ellmer&quot;, &quot;ompr&quot;, &quot;ompr.roi&quot;, &quot;ROI&quot;, &quot;ROI.plugin.glpk&quot;, &quot;dplyr&quot;))
library(ellmer)
library(ompr)
library(ompr.roi)
library(ROI.plugin.glpk)
library(dplyr)</pre>
</div>
</section>
<section id="the-business-problem" class="level2">
<h2 class="anchored" data-anchor-id="the-business-problem">The Business Problem</h2>
<p>Suppose we want to decide how much credit exposure to allocate to each risk grade. The sample dataset has seven risk grades and the problem can be specified in English as:</p>
<blockquote class="blockquote">
<p><em>“We have a budget of $20 million to lend. Allocate exposure across the seven risk grades to maximise expected profit. Expected loss must stay under 6% of total exposure. No grade may hold more than 30% of total exposure. Do not lend more to a grade than its observed demand.”</em></p>
</blockquote>
<p>First, let’s turn the loan-level data into a small segment table; the LLM only receives a description of its columns.</p>
<div class="cell">
<pre># Sample dataset
credit &lt;- read.csv(&quot;https://bit.ly/42ypcnJ&quot;)

seg &lt;- credit |&gt;
  group_by(grade) |&gt;
  summarise(
    n      = n(),
    pd     = mean(bad_flag),          # observed default rate
    rate   = mean(int_rate) / 100,    # average interest rate as a decimal
    demand = sum(loan_amnt),          # total $ requested in the sample
    .groups = &quot;drop&quot;
  ) |&gt;
  mutate(
    lgd = 0.6,                        # assumed loss given default
    profit_per_dollar = (1 - pd) * rate - pd * lgd,
    loss_per_dollar   = pd * lgd
  )

print(seg)</pre>
<div class="cell-output cell-output-stdout">
<pre># A tibble: 7 × 8
  grade     n     pd   rate   demand   lgd profit_per_dollar loss_per_dollar
  &lt;chr&gt; &lt;int&gt;  &lt;dbl&gt;  &lt;dbl&gt;    &lt;int&gt; &lt;dbl&gt;             &lt;dbl&gt;           &lt;dbl&gt;
1 A      1882 0.0361 0.0708 27887875   0.6           0.0465           0.0217
2 B      3057 0.0782 0.107  43993175   0.6           0.0516           0.0469
3 C      2805 0.133  0.142  42971225   0.6           0.0431           0.0798
4 D      1435 0.179  0.182  22352850   0.6           0.0416           0.107 
5 E       590 0.244  0.220  10115800   0.6           0.0196           0.146 
6 F       182 0.357  0.259   3374775   0.6          -0.0481           0.214 
7 G        49 0.327  0.280    907975   0.6          -0.00752          0.196 </pre>
</div>
</div>
</section>
<section id="llm-call-to-generate-the-model-specification" class="level2">
<h2 class="anchored" data-anchor-id="llm-call-to-generate-the-model-specification">LLM call to generate the model specification</h2>
<p>A good prompt does three things &#8211; it describes the data, pins down the output format, and states the rules of the road (variable names, solver, units). Here, instead of using ellmer’s structured output, we’ll ask for a plain text reply.</p>
<div class="cell">
<pre>prompt &lt;- &quot;
You are an expert in operations research who writes R code using the `ompr` package.

You will be given a business problem and a data frame called `seg` with these columns:
- grade: segment name
- pd: probability of default (0 to 1)
- rate: interest rate as a decimal (0.12 = 12%)
- demand: maximum dollars that can be lent to the segment
- profit_per_dollar: expected profit per $1 lent
- loss_per_dollar: expected loss per $1 lent

Rules:
- Return only R code, no explanations and no library() calls.
- Build the model with `model &lt;- MIPModel() |&gt; ...` and assign it to an object called `model`.
- Do not call solve_model() or print anything. Just build `model`.
- Use one continuous, non-negative variable x[i] per row of `seg` (dollars lent).
- Every constraint must be linear.
- Refer to columns as seg$column_name[i] (bare column names will not be found). Do not hard-code numbers from the data.
- Write sums with sum_over()
- Scalar inputs (such as the budget) are in a list called `params`.
&quot;

# Function to talk to an existing agent
ask_llm &lt;- function(chat, prompt) {
  reply &lt;- as.character(chat$chat(prompt, echo = &quot;none&quot;))
  
  # Models often wrap code in ``` fences, so drop those lines
  lines &lt;- strsplit(reply, &quot;\n&quot;)[[1]]
  
  paste(lines[!startsWith(trimws(lines), &quot;```&quot;)], collapse = &quot;\n&quot;)
}

# Set the system behaviour of the agent for the first time
chat &lt;- chat_openrouter(system_prompt = prompt)</pre>
</div>
<p>Now that the behaviour has been set, we can define the actual problem prompt!</p>
<div class="cell">
<pre>problem &lt;- &quot;
Allocate the budget across grades to maximise total expected profit.
Total exposure must not exceed the budget.
Total expected loss must stay under 6% of total exposure.
No grade may hold more than 30% of total exposure.
No grade may receive more than its demand.
&quot;

# Send to agent
code &lt;- ask_llm(chat, problem)

# Print the response
cat(code)</pre>
<div class="cell-output cell-output-stdout">
<pre>model &lt;- MIPModel() |&gt;
  add_variable(x[i], i = 1:nrow(seg), type = &quot;continuous&quot;, lb = 0) |&gt;
  set_objective(sum_over(seg$profit_per_dollar[i] * x[i], i = 1:nrow(seg)), sense = &quot;max&quot;) |&gt;
  add_constraint(sum_over(x[i], i = 1:nrow(seg)) &lt;= params$budget) |&gt;
  add_constraint(sum_over(seg$loss_per_dollar[i] * x[i], i = 1:nrow(seg)) &lt;= 0.06 * sum_over(x[i], i = 1:nrow(seg))) |&gt;
  add_constraint(x[i] &lt;= 0.30 * sum_over(x[j], j = 1:nrow(seg)), i = 1:nrow(seg)) |&gt;
  add_constraint(x[i] &lt;= seg$demand[i], i = 1:nrow(seg))</pre>
</div>
</div>
<p>Let’s understand what’s in the output first:</p>
<ul>
<li><strong>Variables</strong>: one dollar amount per grade, never negative.</li>
<li><strong>Objective</strong>: expected profit per dollar times dollars lent, summed over grades.</li>
<li><strong>Budget</strong>: total lent is at most the budget.</li>
<li><strong>Loss cap</strong>: the “under 6% of exposure” rule is a <em>ratio</em>, which looks non-linear. Moving the denominator across makes it linear: <code>sum(loss_i * x_i) &lt;= 0.06 * sum(x_i)</code>. This is a step LLMs can easily fumble.</li>
<li><strong>Concentration</strong>: each grade is at most 30% of the <em>total exposure actually lent</em>, not 30% of the budget.</li>
<li><strong>Demand</strong>: a simple upper bound per grade.</li>
</ul>
</section>
<section id="solving-the-model" class="level2">
<h2 class="anchored" data-anchor-id="solving-the-model">Solving the model</h2>
<div class="cell">
<pre># Create the exact variables needed for the call to the solver
params &lt;- list(budget = 20e6) ## Specify budget

env &lt;- new.env() ## Create a new environment where the call will be evaluated
env$seg    &lt;- seg  ## Create a variable called seg with the segment level table from earlier
env$params &lt;- params  ## Create a variable called params

# Evaluate the LLM output inside the new environment which creates the &quot;model&quot; object
eval(parse(text = code), envir = env)

# Solve the model object
result &lt;- solve_model(env$model, with_ROI(solver = &quot;glpk&quot;))

# Check if a solution was found
result$status</pre>
<div class="cell-output cell-output-stdout">
<pre>[1] &quot;success&quot;</pre>
</div>
<pre># Print the optimal solution
get_solution(result, x[i]) |&gt;
  mutate(grade = seg$grade[i]) |&gt;
  select(grade, exposure = value)</pre>
<div class="cell-output cell-output-stdout">
<pre>  grade exposure
1     A    6e+06
2     B    6e+06
3     C    6e+06
4     D    2e+06
5     E    0e+00
6     F    0e+00
7     G    0e+00</pre>
</div>
</div>
<p>With <code>ompr.roi</code>, a status of <code>&quot;success&quot;</code> means GLPK found an optimal solution; anything else (infeasible, unbounded) comes back as <code>&quot;error&quot;</code>. Note that the LLM-generated code was run in a separate environment containing <code>seg</code> and <code>params</code>. This isn’t a security sandbox.</p>
</section>
<section id="a-reusable-helper-nl_to_opt" class="level2">
<h2 class="anchored" data-anchor-id="a-reusable-helper-nl_to_opt">A Reusable Helper: <code>nl_to_opt()</code></h2>
<p>Now the fun part. We can wrap everything into one clean function. The idea is: ask, run, and if something breaks, <strong>show the LLM its own error message</strong> and ask again.</p>
<div class="cell">
<pre>nl_to_opt &lt;- function(problem,
                      data,
                      params = list(),
                      system_prompt,
                      max_tries = 3,
                      solver = &quot;glpk&quot;,
                      model = NULL) {

  # Set the system behaviour as usual
  chat &lt;- chat_openrouter(system_prompt = system_prompt, 
                          model = model)

  # Get the problem definition
  prompt &lt;- problem
  history &lt;- list()

  for (attempt in seq_len(max_tries)) {
    code &lt;- ask_llm(chat, prompt)

    # Run the generated code in a clean environment that sees the data and ompr
    env &lt;- new.env(parent = globalenv())
    env$seg &lt;- data
    env$params &lt;- params

    # Build and solve the model. Any error is captured as a message.
    outcome &lt;- tryCatch({
      eval(parse(text = code), envir = env)
      if (is.null(env$model)) stop(&quot;Assign your model to an object called `model`.&quot;)

      res &lt;- solve_model(env$model, with_ROI(solver = solver))
      # ompr.roi reports &quot;success&quot; for an optimal solve, &quot;error&quot; otherwise
      if (res$status != &quot;success&quot;) stop(&quot;The model is infeasible or unbounded.&quot;)

      list(ok = TRUE, result = res, model = env$model)
    }, error = function(e) list(ok = FALSE, msg = conditionMessage(e)))

    history[[attempt]] &lt;- list(code = code, 
                               ok = outcome$ok,
                               msg = if (!outcome$ok) outcome$msg)

    if (outcome$ok) {
      return(list(
        model    = outcome$model,
        result   = outcome$result,
        code     = code,
        attempts = attempt,
        history  = history
      ))
    }

    # Feed the error back and try again
    prompt &lt;- sprintf(
      &quot;Your code failed.\n\nError: %s\n\nPlease return corrected code for the same problem.&quot;,
      outcome$msg
    )
  }

  stop(&quot;No working model after &quot;, max_tries, &quot; attempts. Last error: &quot;,
       history[[max_tries]]$msg)
}</pre>
</div>
<p>Using it takes one call:</p>
<div class="cell">
<pre>out &lt;- nl_to_opt(
  problem       = problem,
  data          = seg,
  params        = list(budget = 20e6),
  system_prompt = prompt
)

out$attempts        # how many tries it took</pre>
<div class="cell-output cell-output-stdout">
<pre>[1] 1</pre>
</div>
<pre>cat(out$code)       # the model the LLM wrote</pre>
<div class="cell-output cell-output-stdout">
<pre>model &lt;- MIPModel() |&gt;
  add_variable(x[i], i = 1:nrow(seg), type = &quot;continuous&quot;, lb = 0) |&gt;
  set_objective(sum_over(seg$profit_per_dollar[i] * x[i], i = 1:nrow(seg)), sense = &quot;max&quot;) |&gt;
  add_constraint(sum_over(x[i], i = 1:nrow(seg)) &lt;= params$budget) |&gt;
  add_constraint(sum_over(seg$loss_per_dollar[i] * x[i], i = 1:nrow(seg)) &lt;= 0.06 * sum_over(x[i], i = 1:nrow(seg))) |&gt;
  add_constraint(x[i] &lt;= 0.30 * sum_over(x[j], j = 1:nrow(seg)), i = 1:nrow(seg)) |&gt;
  add_constraint(x[i] &lt;= seg$demand[i], i = 1:nrow(seg))</pre>
</div>
<pre>get_solution(out$result, x[i])</pre>
<div class="cell-output cell-output-stdout">
<pre>  variable i value
1        x 1 6e+06
2        x 2 6e+06
3        x 3 6e+06
4        x 4 2e+06
5        x 5 0e+00
6        x 6 0e+00
7        x 7 0e+00</pre>
</div>
</div>
</section>
<section id="how-to-build-controls" class="level2">
<h2 class="anchored" data-anchor-id="how-to-build-controls">How to Build Controls</h2>
<p>Since we are using an LLM to translate our business problem into a model that the solver can solve, it’s important to build the right set of controls to ensure the outcome is accurate.</p>
<p>Instead of coding each check by hand, we can ask an LLM to translate plain-English controls into R. We use a <strong>fresh chat</strong> that never sees the optimisation code, like a second reviewer who only gets the rulebook and the final numbers.</p>
<div class="cell">
<pre>controls &lt;- c(
  &quot;Total amount lent must not exceed the budget&quot;,
  &quot;Total expected loss must be at most 6% of the total amount lent&quot;,
  &quot;No grade may hold more than 30% of the total amount lent&quot;,
  &quot;No grade may receive more than its demand&quot;,
  &quot;No grade may receive a negative amount&quot;
)

checker_prompt &lt;- &quot;
Write base R code that tests a lending allocation against a list of controls.
- x is a numeric vector of dollars lent, in the same row order as the data frame seg.
- seg has columns grade, demand and loss_per_dollar. The budget is params$budget.
- Return only code that creates a data frame `checks` with one row per control, in order.
- Column `rule` is the control text. Column `passed` is logical (TRUE or FALSE).
- Allow a tolerance of 1e-6 on every limit.
&quot;

checker    &lt;- chat_openrouter(system_prompt = checker_prompt)
check_code &lt;- ask_llm(checker, paste(controls, collapse = &quot;\n&quot;))

cat(check_code)</pre>
<div class="cell-output cell-output-stdout">
<pre>total_lent &lt;- sum(x)
total_expected_loss &lt;- sum(x * seg$loss_per_dollar)
grade_lending &lt;- tapply(x, seg$grade, sum)
grade_demand &lt;- tapply(seg$demand, seg$grade, sum)

checks &lt;- data.frame(
  rule = c(
    &quot;Total amount lent must not exceed the budget&quot;,
    &quot;Total expected loss must be at most 6% of the total amount lent&quot;,
    &quot;No grade may hold more than 30% of the total amount lent&quot;,
    &quot;No grade may receive more than its demand&quot;,
    &quot;No grade may receive a negative amount&quot;
  ),
  passed = c(
    total_lent &lt;= params$budget + 1e-6,
    total_expected_loss &lt;= 0.06 * total_lent + 1e-6,
    max(grade_lending) &lt;= 0.30 * total_lent + 1e-6,
    all(grade_lending &lt;= seg$demand[match(names(grade_lending), names(grade_demand))] + 1e-6),
    all(x &gt;= -1e-6)
  )
)</pre>
</div>
</div>
<p>A small helper runs the generated checks on any allocation. We test the solver’s answer, and also an allocation we <em>know</em> is bad ($25 million in grade G alone), because the checker can make mistakes too.</p>
<div class="cell">
<pre>run_controls &lt;- function(x) {
  env &lt;- list2env(list(x = x, seg = seg, params = params), parent = globalenv())
  eval(parse(text = check_code), env)

  # Guard against dropped or badly formed checks
  stopifnot(nrow(env$checks) == length(controls),
            is.logical(env$checks$passed), !anyNA(env$checks$passed))
  env$checks
}

# The solver's answer: every control should pass
run_controls(get_solution(out$result, x[i])$value)</pre>
<div class="cell-output cell-output-stdout">
<pre>                                                             rule passed
1                    Total amount lent must not exceed the budget   TRUE
2 Total expected loss must be at most 6% of the total amount lent   TRUE
3        No grade may hold more than 30% of the total amount lent   TRUE
4                       No grade may receive more than its demand   TRUE
5                          No grade may receive a negative amount   TRUE</pre>
</div>
<pre># The bad allocation: the first four controls should fail
run_controls(ifelse(seg$grade == &quot;G&quot;, 25e6, 0))</pre>
<div class="cell-output cell-output-stdout">
<pre>                                                             rule passed
1                    Total amount lent must not exceed the budget  FALSE
2 Total expected loss must be at most 6% of the total amount lent  FALSE
3        No grade may hold more than 30% of the total amount lent  FALSE
4                       No grade may receive more than its demand  FALSE
5                          No grade may receive a negative amount   TRUE</pre>
</div>
</div>
<p>However, passing these controls shows that the answer <strong>follows the rules specified</strong>, not that it is the <strong>best</strong> answer. A model with an extra constraint, or one that lends nothing, could still pass. Hence, some manual review and scenario testing is required.</p>
</section>
<section id="further-reading" class="level2">
<h2 class="anchored" data-anchor-id="further-reading">Further Reading</h2>
<ul>
<li><a href="https://ellmer.tidyverse.org/" rel="nofollow" target="_blank"><code>ellmer</code> documentation</a></li>
<li><a href="https://dirkschumacher.github.io/ompr/" rel="nofollow" target="_blank"><code>ompr</code> documentation</a> and <a href="https://dirkschumacher.github.io/ompr/reference/index.html" rel="nofollow" target="_blank">function reference</a></li>
<li><a href="https://github.com/dirkschumacher/ompr.roi" rel="nofollow" target="_blank"><code>ompr.roi</code> on GitHub</a>, the bridge from <code>ompr</code> to ROI solvers such as GLPK</li>
<li><a href="https://rtichoke.netlify.app/posts/building-particle-swarm-optimizer.html" rel="nofollow" target="_blank">Particle swarm optimisation from scratch</a> for a derivative-free alternative to LP</li>
<li><a href="https://rtichoke.netlify.app/posts/portfolio_optimisation_pso.html" rel="nofollow" target="_blank">Portfolio optimisation with PSO</a></li>
</ul>


</section>

 
<div style="border: 1px solid; background: none repeat scroll 0 0 #EDEDED; margin: 1px; font-size: 13px;">
<div style="text-align: center;">To <strong>leave a comment</strong> for the author, please follow the link and comment on their blog: <strong><a href="https://rtichoke.netlify.app/posts/llm-written-optimisation-models.html"> R&#039;tichoke</a></strong>.</div>
<hr />
<a href="https://www.r-bloggers.com/" rel="nofollow">R-bloggers.com</a> offers <strong><a href="https://feedburner.google.com/fb/a/mailverify?uri=RBloggers" rel="nofollow">daily e-mail updates</a></strong> about <a title="The R Project for Statistical Computing" href="https://www.r-project.org/" rel="nofollow">R</a> news and tutorials about <a title="R tutorials" href="https://www.r-bloggers.com/how-to-learn-r-2/" rel="nofollow">learning R</a> and many other topics. <a title="Data science jobs" href="https://www.r-users.com/" rel="nofollow">Click here if you're looking to post or find an R/data-science job</a>.

<hr>Want to share your content on R-bloggers?<a href="https://www.r-bloggers.com/add-your-blog/" rel="nofollow"> click here</a> if you have a blog, or <a href="http://r-posts.com/" rel="nofollow"> here</a> if you don't.
</div><strong>Continue reading</strong>: <a href="https://www.r-bloggers.com/2026/11/llm-driven-optimisation-modelling-in-r/">LLM-driven optimisation modelling in R</a>]]></content:encoded>
					
		
		<enclosure url="https://rtichoke.netlify.app/images/llm-optimisation.png" length="0" type="image/png" />

		<post-id xmlns="com-wordpress:feed-additions:1">405159</post-id>	</item>
		<item>
		<title>mvgam 2.0 on CRAN: State-Space models built on brms</title>
		<link>https://www.r-bloggers.com/2026/11/mvgam-2-0-on-cran-state-space-models-built-on-brms/</link>
		
		<dc:creator><![CDATA[GAMbler]]></dc:creator>
		<pubDate>Fri, 27 Nov 2026 00:00:00 +0000</pubDate>
				<category><![CDATA[R bloggers]]></category>
		<guid isPermaLink="false">https://ecogambler.netlify.app/blog/mvgam-2/</guid>

					<description><![CDATA[<div style = "width:60%; display: inline-block; float:left; ">
<p>Welcoming mvgam 2.0 to CRAN</p>
<p>Version 2.0 of mvgam<br />
has now been published on CRAN. When I<br />
announced the first CRAN release, I finished with a list of features I wanted to add. Two of those were zero-inflated observation model...</p></div>
<div style = "width: 40%; display: inline-block; float:right;"></div>
<div style="clear: both;"></div>
<strong>Continue reading</strong>: <a href="https://www.r-bloggers.com/2026/11/mvgam-2-0-on-cran-state-space-models-built-on-brms/">mvgam 2.0 on CRAN: State-Space models built on brms</a>]]></description>
										<content:encoded><![CDATA[<!-- 
<div style="min-height: 30px;">
[social4i size="small" align="align-left"]
</div>
-->

<div style="border: 1px solid; background: none repeat scroll 0 0 #EDEDED; margin: 1px; font-size: 12px;">
[This article was first published on  <strong><a href="https://ecogambler.netlify.app/blog/mvgam-2/"> GAMbler</a></strong>, and kindly contributed to <a href="https://www.r-bloggers.com/" rel="nofollow">R-bloggers</a>].  (You can report issue about the content on this page <a href="https://www.r-bloggers.com/contact-us/">here</a>)
<hr>Want to share your content on R-bloggers?<a href="https://www.r-bloggers.com/add-your-blog/" rel="nofollow"> click here</a> if you have a blog, or <a href="http://r-posts.com/" rel="nofollow"> here</a> if you don't.
</div>




<h2 id="welcoming-mvgam-20-to-cran">Welcoming mvgam 2.0 to CRAN
  <a href="https://ecogambler.netlify.app/blog/mvgam-2/#welcoming-mvgam-20-to-cran" rel="nofollow" target="_blank"><svg class="anchor-symbol" aria-hidden="true" height="26" width="26" viewBox="0 0 22 22" xmlns="http://www.w3.org/2000/svg">
      <path d="M0 0h24v24H0z" fill="currentColor"></path>
      <path d="M3.9 12c0-1.71 1.39-3.1 3.1-3.1h4V7H7c-2.76.0-5 2.24-5 5s2.24 5 5 5h4v-1.9H7c-1.71.0-3.1-1.39-3.1-3.1zM8 13h8v-2H8v2zm9-6h-4v1.9h4c1.71.0 3.1 1.39 3.1 3.1s-1.39 3.1-3.1 3.1h-4V17h4c2.76.0 5-2.24 5-5s-2.24-5-5-5z"></path>
    </svg></a>
</h2>
<p>Version 2.0 of <code>mvgam</code> 
<a href="https://cran.r-project.org/package=mvgam" rel="nofollow" target="_blank">has now been published on CRAN</a>. When I 
<a href="https://ecogambler.netlify.app/blog/mvgam-on-cran/" rel="nofollow" target="_blank">announced the first CRAN release</a>, I finished with a list of features I wanted to add. Two of those were zero-inflated observation models and correlated random effects. Both are now available, along with many other features, because version 2.0 uses 
<a href="https://paulbuerkner.com/brms/" rel="nofollow" target="_blank"><code>brms</code></a> to write the observation model.</p>
<p>Version 1 of <code>mvgam</code> wrote its own <code>Stan</code> code for every model. This made it quick to add new types of latent dynamic processes, but the observation side of a model could only ever do what I had written for it. <code>brms</code> already handles that side extremely well, with support for random effects, distributional regression, monotonic effects, missing value imputation and a long list of response families. In version 2.0, <code>brms</code> writes the observation model and <code>mvgam</code> adds the latent dynamic process, along with the tools we need for time series, such as forecasting, forecast evaluation and summaries of the dynamics. Any formula we can write in <code>brms</code> can now be paired with a latent dynamic process. For example, here is a model for counts of several species, with a smooth effect of temperature and correlated random intercepts and rainfall slopes for each survey site:</p>
<pre>mvgam(
  count ~ s(temperature) + (1 + rainfall | site),
  trend_formula = ~ s(ndvi) + VAR(ma = TRUE),
  data = surveys,
  family = negbinomial()
)
</pre><p>Beneath the observations, each species has a latent process that responds to vegetation greenness (<code>ndvi</code>) and evolves as a Vector Autoregressive Moving Average. The dynamics of each species can then influence the others. In this post I explain how models like this one are put together, describe the dynamic processes that are available and work through a first model. I also list the main changes for anyone moving code over from version 1.</p>




<h2 id="what-does-mvgam-do">What does mvgam do?
  <a href="https://ecogambler.netlify.app/blog/mvgam-2/#what-does-mvgam-do" rel="nofollow" target="_blank"><svg class="anchor-symbol" aria-hidden="true" height="26" width="26" viewBox="0 0 22 22" xmlns="http://www.w3.org/2000/svg">
      <path d="M0 0h24v24H0z" fill="currentColor"></path>
      <path d="M3.9 12c0-1.71 1.39-3.1 3.1-3.1h4V7H7c-2.76.0-5 2.24-5 5s2.24 5 5 5h4v-1.9H7c-1.71.0-3.1-1.39-3.1-3.1zM8 13h8v-2H8v2zm9-6h-4v1.9h4c1.71.0 3.1 1.39 3.1 3.1s-1.39 3.1-3.1 3.1h-4V17h4c2.76.0 5-2.24 5-5s-2.24-5-5-5z"></path>
    </svg></a>
</h2>
<p><code>mvgam</code> fits <em>State-Space</em> models. These assume that some unobserved <em>process</em> evolves through time and that the observations we collect are noisy, possibly non-Gaussian, measurements of that process. Because the process is modelled separately from the observations, we can still estimate it at times where an observation is missing.</p>
<p><img src="https://ecogambler.netlify.app/blog/mvgam-2/SS_model.svg" alt="Illustration of a basic State-Space model. A latent dynamic process (X) can evolve independently from the way we take observations (Y) of that process"></p>
<p>Assume <code>\(\tilde{\boldsymbol{y}}_{i,t}\)</code> is the conditional expectation of series <code>\(i\)</code> at time <code>\(t\)</code>, with an invertible link function <code>\(g\)</code>. In version 2.0 the model has two linear predictors:</p>
<p><code>$$g(\tilde{\boldsymbol{y}}_{i,t}) = \eta_{i,t} + z_{i,t}$$</code></p>
<p><code>$$z_{i,t} = \mu_{i,t} + x_{i,t}$$</code></p>
<p>Where:</p>
<ul>
<li><code>\(\eta_{i,t}\)</code> is the linear predictor of the observation model, which we write using the <code>formula</code> argument in <code>brms</code> syntax</li>
<li><code>\(z_{i,t}\)</code> is the latent state</li>
<li><code>\(\mu_{i,t}\)</code> is the mean of the latent state, which we write using the <code>trend_formula</code> argument</li>
<li><code>\(x_{i,t}\)</code> is a dynamic component that follows one of the processes described below</li>
</ul>
<p>For example, if <code>\(x\)</code> follows a first-order autoregression then</p>
<p><code>$$x_{i,t} = \phi_i x_{i,t-1} + \epsilon_{i,t}$$</code></p>
<p><code>$$\epsilon_{i,t} \sim \text{Normal}(0, \sigma_i)$$</code></p>
<p>Where <code>\(\phi_i\)</code> is the autoregressive coefficient for series <code>\(i\)</code> and <code>\(\sigma_i\)</code> is the standard deviation of its process errors.</p>
<p>This split matters when deciding where a covariate should go. A covariate in <code>trend_formula</code> acts on the latent state. Its effect then carries forward through the dynamics. A covariate in <code>formula</code> acts on the observations at their own time point, which is a better place for things like survey effort or detection conditions.</p>




<h2 id="supported-observation-families">Supported observation families
  <a href="https://ecogambler.netlify.app/blog/mvgam-2/#supported-observation-families" rel="nofollow" target="_blank"><svg class="anchor-symbol" aria-hidden="true" height="26" width="26" viewBox="0 0 22 22" xmlns="http://www.w3.org/2000/svg">
      <path d="M0 0h24v24H0z" fill="currentColor"></path>
      <path d="M3.9 12c0-1.71 1.39-3.1 3.1-3.1h4V7H7c-2.76.0-5 2.24-5 5s2.24 5 5 5h4v-1.9H7c-1.71.0-3.1-1.39-3.1-3.1zM8 13h8v-2H8v2zm9-6h-4v1.9h4c1.71.0 3.1 1.39 3.1 3.1s-1.39 3.1-3.1 3.1h-4V17h4c2.76.0 5-2.24 5-5s-2.24-5-5-5z"></path>
    </svg></a>
</h2>
<p>Almost every family that <code>brms</code> supports can be used, including the zero-inflated and hurdle families, the ordinal families, and distributional models in which parameters such as <code>\(\sigma\)</code> or <code>\(\phi\)</code> get their own formulae. Mixture families are the one exception. <code>mvgam</code> also adds some families of its own:</p>
<table>
<thead>
<tr>
<th style="text-align:center">Distribution</th>
<th style="text-align:center">Function</th>
<th style="text-align:center">Support</th>
</tr>
</thead>
<tbody>
<tr>
<td style="text-align:center">Tweedie</td>
<td style="text-align:center"><code>tweedie()</code></td>
<td style="text-align:center">Non-negative real values, with an atom at zero</td>
</tr>
<tr>
<td style="text-align:center">Beta negative binomial</td>
<td style="text-align:center"><code>beta_nb()</code></td>
<td style="text-align:center">Heavy-tailed non-negative integers</td>
</tr>
<tr>
<td style="text-align:center">Conway-Maxwell binomial</td>
<td style="text-align:center"><code>com_binomial()</code></td>
<td style="text-align:center">Over- or under-dispersed counts out of known trials</td>
</tr>
<tr>
<td style="text-align:center">Occupancy</td>
<td style="text-align:center"><code>occ()</code></td>
<td style="text-align:center">Binary detections from repeat visits</td>
</tr>
<tr>
<td style="text-align:center">N-mixture</td>
<td style="text-align:center"><code>nmix()</code></td>
<td style="text-align:center">Counts from repeat visits</td>
</tr>
<tr>
<td style="text-align:center">Dirichlet</td>
<td style="text-align:center"><code>diri()</code></td>
<td style="text-align:center">Compositions that sum to one</td>
</tr>
<tr>
<td style="text-align:center">Multinomial</td>
<td style="text-align:center"><code>multi()</code></td>
<td style="text-align:center">Counts of categories</td>
</tr>
<tr>
<td style="text-align:center">Categorical</td>
<td style="text-align:center"><code>categ()</code></td>
<td style="text-align:center">One category per unit</td>
</tr>
<tr>
<td style="text-align:center">Multivariate normal</td>
<td style="text-align:center"><code>mvn()</code></td>
<td style="text-align:center">Several continuous responses per unit</td>
</tr>
<tr>
<td style="text-align:center">Multivariate Student-t</td>
<td style="text-align:center"><code>mvt()</code></td>
<td style="text-align:center">Several heavy-tailed responses per unit</td>
</tr>
</tbody>
</table>
<p><code>occ()</code> and <code>nmix()</code> estimate detection probability together with the latent occupancy or abundance. The composition families (<code>diri()</code>, <code>multi()</code>, <code>categ()</code>) take data in the same <em>long</em> format as the other families. They are useful for modelling compositions, a topic I covered in an earlier post on 
<a href="https://ecogambler.netlify.app/blog/plant-community-dirichlet/" rel="nofollow" target="_blank">Dirichlet regression for plant communities</a>.</p>




<h2 id="supported-temporal-dynamic-processes">Supported temporal dynamic processes
  <a href="https://ecogambler.netlify.app/blog/mvgam-2/#supported-temporal-dynamic-processes" rel="nofollow" target="_blank"><svg class="anchor-symbol" aria-hidden="true" height="26" width="26" viewBox="0 0 22 22" xmlns="http://www.w3.org/2000/svg">
      <path d="M0 0h24v24H0z" fill="currentColor"></path>
      <path d="M3.9 12c0-1.71 1.39-3.1 3.1-3.1h4V7H7c-2.76.0-5 2.24-5 5s2.24 5 5 5h4v-1.9H7c-1.71.0-3.1-1.39-3.1-3.1zM8 13h8v-2H8v2zm9-6h-4v1.9h4c1.71.0 3.1 1.39 3.1 3.1s-1.39 3.1-3.1 3.1h-4V17h4c2.76.0 5-2.24 5-5s-2.24-5-5-5z"></path>
    </svg></a>
</h2>
<p>In version 1 we chose the dynamic process with the <code>trend_model</code> argument. In version 2.0 the process is a term in <code>trend_formula</code>, for example <code>trend_formula = ~ AR(p = 1)</code>. Each process can be fitted independently to each series, with correlated process errors across series (using <code>cor = TRUE</code>), or as a <em>dynamic factor</em> model with fewer latent factors than there are series (using <code>n_lv</code>). All of the processes are documented in 
<a href="https://nicholasjclark.github.io/mvgam/reference/trend_constructors.html" rel="nofollow" target="_blank"><code>?trend_constructors</code></a>.</p>




<h3 id="random-walks-and-autoregressions">Random Walks and Autoregressions
  <a href="https://ecogambler.netlify.app/blog/mvgam-2/#random-walks-and-autoregressions" rel="nofollow" target="_blank"><svg class="anchor-symbol" aria-hidden="true" height="26" width="26" viewBox="0 0 22 22" xmlns="http://www.w3.org/2000/svg">
      <path d="M0 0h24v24H0z" fill="currentColor"></path>
      <path d="M3.9 12c0-1.71 1.39-3.1 3.1-3.1h4V7H7c-2.76.0-5 2.24-5 5s2.24 5 5 5h4v-1.9H7c-1.71.0-3.1-1.39-3.1-3.1zM8 13h8v-2H8v2zm9-6h-4v1.9h4c1.71.0 3.1 1.39 3.1 3.1s-1.39 3.1-3.1 3.1h-4V17h4c2.76.0 5-2.24 5-5s-2.24-5-5-5z"></path>
    </svg></a>
</h3>
<p>For series measured at regular intervals, use <code>RW()</code> to set up a Random Walk or <code>AR(p = ...)</code> to set up an autoregression. The autoregression can be of any order or use a sparse set of lags. For monthly data, for example, <code>AR(p = c(1, 12))</code> captures dependence on the previous month and on the same month in the previous year. Both processes can include a moving average term using <code>ma = TRUE</code>.</p>
<p>An autoregression over consecutive lags is kept stationary because <code>mvgam</code> samples its partial autocorrelations and then transforms these into the autoregressive coefficients. A sparse set of lags carries no such guarantee. When there are multiple series, the coefficients can be estimated separately for each series, shared among all series (<code>coef_sharing = &quot;shared&quot;</code>), or partially pooled toward a common mean (<code>coef_sharing = &quot;hierarchical&quot;</code>).</p>




<h3 id="vector-autoregressions">Vector Autoregressions
  <a href="https://ecogambler.netlify.app/blog/mvgam-2/#vector-autoregressions" rel="nofollow" target="_blank"><svg class="anchor-symbol" aria-hidden="true" height="26" width="26" viewBox="0 0 22 22" xmlns="http://www.w3.org/2000/svg">
      <path d="M0 0h24v24H0z" fill="currentColor"></path>
      <path d="M3.9 12c0-1.71 1.39-3.1 3.1-3.1h4V7H7c-2.76.0-5 2.24-5 5s2.24 5 5 5h4v-1.9H7c-1.71.0-3.1-1.39-3.1-3.1zM8 13h8v-2H8v2zm9-6h-4v1.9h4c1.71.0 3.1 1.39 3.1 3.1s-1.39 3.1-3.1 3.1h-4V17h4c2.76.0 5-2.24 5-5s-2.24-5-5-5z"></path>
    </svg></a>
</h3>
<p>When series are expected to interact with one another, for example when the abundance of a predator in one month influences the abundance of its prey in the next, use <code>VAR(p = ...)</code>. A VAR(<code>\(p\)</code>) model takes the form:</p>
<p><code>$$x_t = \sum_{l=1}^{p} A_l x_{t-l} + \epsilon_t$$</code></p>
<p><code>$$\epsilon_t \sim \text{MVNormal}(0, \Sigma)$$</code></p>
<p>Where:</p>
<ul>
<li><code>\(x_t\)</code> is now a vector of latent states for all series at time <code>\(t\)</code></li>
<li><code>\(A_l\)</code> is a matrix of autoregressive coefficients at lag <code>\(l\)</code>, in which the diagonals capture lagged self-dependence and the off-diagonals capture lagged cross-dependence among series</li>
<li><code>\(\Sigma\)</code> is the covariance matrix of the process errors, which captures contemporaneous correlations among series</li>
</ul>
<p>Stationarity is enforced through the structured prior of 
<a href="https://www.tandfonline.com/doi/full/10.1080/10618600.2022.2079648" rel="nofollow" target="_blank">Heaps (2023)</a>. Setting <code>ma = TRUE</code> adds a moving average term to give a VARMA model. If the series are nested within a grouping factor, <code>VAR(gr = region, subgr = species)</code> fits a hierarchical panel VAR, where each region has its own coefficient and correlation matrices that are drawn from shared hyperparameters. Once the model is fitted, the impulse response, variance decomposition and stability functions (<code>irf()</code>, <code>fevd()</code>, <code>stability()</code>) can be used to ask questions about how the series interact. I described these tools in more detail in an earlier post on 
<a href="https://ecogambler.netlify.app/blog/vector-autoregressions/" rel="nofollow" target="_blank">State-Space Vector Autoregressions</a>. The 
<a href="https://nicholasjclark.github.io/mvgam/articles/var.html" rel="nofollow" target="_blank">VAR</a> and 
<a href="https://nicholasjclark.github.io/mvgam/articles/hierarchical_var.html" rel="nofollow" target="_blank">hierarchical VAR</a> articles give worked examples.</p>




<h3 id="continuous-time-ar1-processes">Continuous time AR(1) processes
  <a href="https://ecogambler.netlify.app/blog/mvgam-2/#continuous-time-ar1-processes" rel="nofollow" target="_blank"><svg class="anchor-symbol" aria-hidden="true" height="26" width="26" viewBox="0 0 22 22" xmlns="http://www.w3.org/2000/svg">
      <path d="M0 0h24v24H0z" fill="currentColor"></path>
      <path d="M3.9 12c0-1.71 1.39-3.1 3.1-3.1h4V7H7c-2.76.0-5 2.24-5 5s2.24 5 5 5h4v-1.9H7c-1.71.0-3.1-1.39-3.1-3.1zM8 13h8v-2H8v2zm9-6h-4v1.9h4c1.71.0 3.1 1.39 3.1 3.1s-1.39 3.1-3.1 3.1h-4V17h4c2.76.0 5-2.24 5-5s-2.24-5-5-5z"></path>
    </svg></a>
</h3>
<p>Many ecological time series are not measured at regular intervals. We might have weekly samples in one season and monthly samples in another. <code>CAR()</code> sets up a first-order autoregression in continuous time, where the dependence decays with the amount of time that has passed between observations:</p>
<p><code>$$x_{i,t} \sim \text{Normal}\left(\phi_i^{\Delta_t} x_{i,t-1},\ \sigma_i \sqrt{\frac{1 - \phi_i^{2\Delta_t}}{1 - \phi_i^2}}\right)$$</code></p>
<p>Where <code>\(\Delta_t\)</code> is the time since the previous observation. When <code>\(\Delta_t = 1\)</code> this is the same as an ordinary AR(1). Longer gaps allow the latent state to wander further from its previous value. Each series can be observed at its own set of times. The process errors can also be correlated among series using <code>cor = TRUE</code>.</p>




<h3 id="local-linear-trends">Local linear trends
  <a href="https://ecogambler.netlify.app/blog/mvgam-2/#local-linear-trends" rel="nofollow" target="_blank"><svg class="anchor-symbol" aria-hidden="true" height="26" width="26" viewBox="0 0 22 22" xmlns="http://www.w3.org/2000/svg">
      <path d="M0 0h24v24H0z" fill="currentColor"></path>
      <path d="M3.9 12c0-1.71 1.39-3.1 3.1-3.1h4V7H7c-2.76.0-5 2.24-5 5s2.24 5 5 5h4v-1.9H7c-1.71.0-3.1-1.39-3.1-3.1zM8 13h8v-2H8v2zm9-6h-4v1.9h4c1.71.0 3.1 1.39 3.1 3.1s-1.39 3.1-3.1 3.1h-4V17h4c2.76.0 5-2.24 5-5s-2.24-5-5-5z"></path>
    </svg></a>
</h3>
<p>Some series grow or decline over long periods while their seasonal patterns also change. <code>LLT()</code> sets up a <em>level</em> and a <em>slope</em> that both evolve through time, as in exponential smoothing models. The slope can be damped using <code>damped = TRUE</code>. We can also add a seasonal component, built from as many harmonics as needed, that is allowed to drift from year to year (for example <code>LLT(season = 12, harmonics = 3)</code>). The <code>seasonality()</code> function then summarises how the amplitude and timing of the seasonal cycle changed through time, which is a more direct route to the questions I explored with GAMs in my post on 
<a href="https://ecogambler.netlify.app/blog/time-varying-seasonality/" rel="nofollow" target="_blank">time-varying seasonality</a>.</p>




<h3 id="piecewise-logistic-and-linear-trends">Piecewise logistic and linear trends
  <a href="https://ecogambler.netlify.app/blog/mvgam-2/#piecewise-logistic-and-linear-trends" rel="nofollow" target="_blank"><svg class="anchor-symbol" aria-hidden="true" height="26" width="26" viewBox="0 0 22 22" xmlns="http://www.w3.org/2000/svg">
      <path d="M0 0h24v24H0z" fill="currentColor"></path>
      <path d="M3.9 12c0-1.71 1.39-3.1 3.1-3.1h4V7H7c-2.76.0-5 2.24-5 5s2.24 5 5 5h4v-1.9H7c-1.71.0-3.1-1.39-3.1-3.1zM8 13h8v-2H8v2zm9-6h-4v1.9h4c1.71.0 3.1 1.39 3.1 3.1s-1.39 3.1-3.1 3.1h-4V17h4c2.76.0 5-2.24 5-5s-2.24-5-5-5z"></path>
    </svg></a>
</h3>
<p>For series where the rate of growth changes abruptly, or where growth saturates at some carrying capacity, <code>PW()</code> sets up the piecewise linear and logistic trends described by 
<a href="https://www.tandfonline.com/doi/full/10.1080/00031305.2017.1380080" rel="nofollow" target="_blank">Taylor and Letham (2018)</a>. The growth rate is allowed to change at a set of potential changepoints spread across the training period. The logistic version levels off at a carrying capacity.</p>




<h3 id="correlated-residuals-without-dynamics">Correlated residuals without dynamics
  <a href="https://ecogambler.netlify.app/blog/mvgam-2/#correlated-residuals-without-dynamics" rel="nofollow" target="_blank"><svg class="anchor-symbol" aria-hidden="true" height="26" width="26" viewBox="0 0 22 22" xmlns="http://www.w3.org/2000/svg">
      <path d="M0 0h24v24H0z" fill="currentColor"></path>
      <path d="M3.9 12c0-1.71 1.39-3.1 3.1-3.1h4V7H7c-2.76.0-5 2.24-5 5s2.24 5 5 5h4v-1.9H7c-1.71.0-3.1-1.39-3.1-3.1zM8 13h8v-2H8v2zm9-6h-4v1.9h4c1.71.0 3.1 1.39 3.1 3.1s-1.39 3.1-3.1 3.1h-4V17h4c2.76.0 5-2.24 5-5s-2.24-5-5-5z"></path>
    </svg></a>
</h3>
<p><code>ZMVN()</code> sets up a zero-mean multivariate normal process with no temporal dependence. This is useful for capturing residual correlations among series, or among species that are sampled at the same sites. It is also the process that <code>jsdgam()</code> uses to build joint species distribution models.</p>




<h2 id="regression-formulae">Regression formulae
  <a href="https://ecogambler.netlify.app/blog/mvgam-2/#regression-formulae" rel="nofollow" target="_blank"><svg class="anchor-symbol" aria-hidden="true" height="26" width="26" viewBox="0 0 22 22" xmlns="http://www.w3.org/2000/svg">
      <path d="M0 0h24v24H0z" fill="currentColor"></path>
      <path d="M3.9 12c0-1.71 1.39-3.1 3.1-3.1h4V7H7c-2.76.0-5 2.24-5 5s2.24 5 5 5h4v-1.9H7c-1.71.0-3.1-1.39-3.1-3.1zM8 13h8v-2H8v2zm9-6h-4v1.9h4c1.71.0 3.1 1.39 3.1 3.1s-1.39 3.1-3.1 3.1h-4V17h4c2.76.0 5-2.24 5-5s-2.24-5-5-5z"></path>
    </svg></a>
</h2>
<p>The observation <code>formula</code> accepts the full <code>brms</code> syntax. This includes smooths from <code>mgcv</code> (<code>s()</code>, <code>te()</code>, <code>t2()</code>), random effects such as <code>(1 | group)</code>, Gaussian Processes using <code>gp()</code>, monotonic effects using <code>mo()</code> and distributional formulae using <code>bf()</code>. Several responses can share one latent process when we use <code>mvbind()</code> or <code>mvbf()</code>. This is how an <em>integrated distribution model</em> combines different types of survey data, such as counts from one program and detection / non-detection data from another, to estimate a single underlying process. The 
<a href="https://nicholasjclark.github.io/mvgam/articles/mvbf.html" rel="nofollow" target="_blank">multivariate</a> and 
<a href="https://nicholasjclark.github.io/mvgam/articles/idm.html" rel="nofollow" target="_blank">integrated distribution model</a> articles show how to set these up.</p>
<p>The <code>trend_formula</code> accepts the same terms, plus one of the processes above. In a dynamic factor model, <code>by = lv_axis()</code> gives each latent factor its own smooth function of a covariate, as in <code>trend_formula = ~ s(temperature, by = lv_axis()) + AR(n_lv = 2)</code>. We can also use the <code>loadings_prior</code> argument to give the factor loadings a structured prior based on species traits or a phylogeny, which the 
<a href="https://nicholasjclark.github.io/mvgam/articles/dfm.html" rel="nofollow" target="_blank">dynamic factor vignette</a> explains in detail.</p>




<h2 id="a-first-model">A first model
  <a href="https://ecogambler.netlify.app/blog/mvgam-2/#a-first-model" rel="nofollow" target="_blank"><svg class="anchor-symbol" aria-hidden="true" height="26" width="26" viewBox="0 0 22 22" xmlns="http://www.w3.org/2000/svg">
      <path d="M0 0h24v24H0z" fill="currentColor"></path>
      <path d="M3.9 12c0-1.71 1.39-3.1 3.1-3.1h4V7H7c-2.76.0-5 2.24-5 5s2.24 5 5 5h4v-1.9H7c-1.71.0-3.1-1.39-3.1-3.1zM8 13h8v-2H8v2zm9-6h-4v1.9h4c1.71.0 3.1 1.39 3.1 3.1s-1.39 3.1-3.1 3.1h-4V17h4c2.76.0 5-2.24 5-5s-2.24-5-5-5z"></path>
    </svg></a>
</h2>
<p>To show how this all fits together, we will model monthly captures of the Desert Pocket Mouse (<em>Chaetodipus penicillatus</em>), using the <code>portal_data</code> that ships with the package. We will hold out the final year of data to evaluate forecasts. Load the data and split it into training and testing sets. <code>mvgam_data()</code> then checks the data against the chosen family before any <code>Stan</code> code is written. It also plots the series, its distribution and its autocorrelation function, with the testing observations shown in black:</p>
<pre>library(mvgam)
data(portal_data)
pp &lt;- droplevels(subset(portal_data, series == &quot;PP&quot;))
pp_train &lt;- subset(pp, time &lt;= 68)
pp_test &lt;- subset(pp, time &gt; 68)
mvgam_data(
  pp_train,
  family = poisson(),
  y = &quot;captures&quot;,
  newdata = pp_test
)
</pre><img src="https://i1.wp.com/ecogambler.netlify.app/blog/mvgam-2/index_files/figure-html/data-1.png?w=80%25&#038;ssl=1" alt="" style="display: block; margin: auto;" data-recalc-dims="1" />
<p>Captures move between long runs of zeros and peaks above 20. The autocorrelation function shows that captures in one month are strongly related to captures in the previous one or two months. We will model captures as a function of minimum temperature and vegetation greenness, with both effects acting on a latent state that follows a first-order autoregression. Before fitting the model, <code>get_prior()</code> lists every parameter that will be estimated, along with its default prior. Notice that the list includes parameters for the latent process as well as for the observation model:</p>
<pre>get_prior(
  captures ~ 1,
  trend_formula = ~ s(mintemp, k = 6) + s(ndvi_ma12, k = 6) + AR(),
  data = pp_train,
  family = poisson()
)

##                   prior       class                coef group resp dpar nlpar
##  student_t(3, 1.2, 2.5)   Intercept                                          
##          exponential(2) sigma_trend                                          
##          normal(0, 0.5)   ar1_trend                                          
##                  (flat)     b_trend                                          
##                  (flat)     b_trend          smintemp_1                      
##                  (flat)     b_trend        sndvi_ma12_1                      
##    student_t(3, 0, 2.5)   sds_trend                                          
##    student_t(3, 0, 2.5)   sds_trend   s(mintemp, k = 6)                      
##    student_t(3, 0, 2.5)   sds_trend s(ndvi_ma12, k = 6)                      
##  lb ub tag       source
##                 default
##   0             default
##  -1  1          default
##                 default
##            (vectorized)
##            (vectorized)
##   0             default
##   0        (vectorized)
##   0        (vectorized)
</pre><p>Now fit the model. Supplying <code>newdata</code> stores the testing data with the model. <code>forecast()</code> and the plotting functions can then use them:</p>
<pre>fit &lt;- mvgam(
  captures ~ 1,
  trend_formula = ~ s(mintemp, k = 6) + s(ndvi_ma12, k = 6) + AR(),
  data = pp_train,
  newdata = pp_test,
  family = poisson(),
  silent = 2,
  seed = 1
)
</pre><p>The summary follows the same layout as a <code>brms</code> summary, with a separate block for parameters of the latent process:</p>
<pre>summary(fit)

##  Family: poisson 
##   Links: mu = log 
## Formula: captures ~ 1 
##    Data: pp_train (Number of observations: 68) 
##  Trends: AR(1); formula: ~s(mintemp, k = 6) + s(ndvi_ma12, k = 6) 
##   Draws: 4 chains, each with iter = 2000; warmup = 1000; thin = 1; 
##          total post-warmup draws = 4000
## 
## == Observation Model ==
## Regression Coefficients:
##           Estimate Est.Error l-95% CI u-95% CI Rhat Bulk_ESS Tail_ESS
## Intercept     0.83      0.62    -0.52     2.11 1.02      362       94
## 
## == Trend Model ==
## Smoothing Spline Hyperparameters:
##                   Estimate Est.Error l-95% CI u-95% CI Rhat Bulk_ESS Tail_ESS
## sds(smintemp_1)       1.20      1.13     0.03     4.29 1.01      372      123
## sds(sndvi_ma12_1)     2.31      1.59     0.14     6.29 1.00     1052     1061
## 
## Regression Coefficients:
##              Estimate Est.Error l-95% CI u-95% CI Rhat Bulk_ESS Tail_ESS
## smintemp_1       3.21      2.85    -5.45     8.27 1.01      309       97
## sndvi_ma12_1     2.80      4.24    -5.22    12.48 1.00     1273     1167
## 
## Trend Specific Parameters:
##                 Estimate Est.Error l-95% CI u-95% CI Rhat Bulk_ESS Tail_ESS
## sigma_trend[PP]     0.70      0.14     0.45     1.02 1.00     1252     2223
## ar1_trend[PP]       0.81      0.10     0.58     0.96 1.00     1001     1030
## 
## Draws were sampled using sampling(NUTS). For each parameter, Bulk_ESS
## and Tail_ESS are effective sample size measures, and Rhat is the potential
## scale reduction factor on split chains (at convergence, Rhat = 1).
## 
## Next steps:
##   - `pp_check(fit)`: posterior predictive checks
##   - `forecast(fit, newdata = ...)`: out-of-sample forecasts
##   - `lfo_cv(fit)`: leave-future-out model comparison
##   - `conditional_effects(fit)`: covariate effects
## Use `how_to_cite(fit)` for a methods paragraph and `methods_md(fit)` for its equations.
</pre><p>Because the model is built with <code>brms</code>, its post-processing functions also work on the fitted model. For example, <code>conditional_effects()</code> plots the expected number of captures across each covariate:</p>
<pre>plot(conditional_effects(fit, type = &quot;expected&quot;), ask = FALSE)
</pre><p><img src="https://i0.wp.com/ecogambler.netlify.app/blog/mvgam-2/index_files/figure-html/effects-1.png?w=90%25&#038;ssl=1" alt="" style="display: block; margin: auto;" data-recalc-dims="1" /><img src="https://i0.wp.com/ecogambler.netlify.app/blog/mvgam-2/index_files/figure-html/effects-2.png?w=90%25&#038;ssl=1" alt="" style="display: block; margin: auto;" data-recalc-dims="1" /></p>
<p>Expected captures increase with minimum temperature, most steeply in the warmest months, while the effect of vegetation greenness peaks at intermediate values. Both effects are quite uncertain. Next, <code>forecast()</code> carries the latent state forward from its final estimated values into the testing period:</p>
<pre>fc &lt;- forecast(fit)
plot(fc)
</pre><img src="https://i0.wp.com/ecogambler.netlify.app/blog/mvgam-2/index_files/figure-html/forecast-1.png?w=80%25&#038;ssl=1" alt="" style="display: block; margin: auto;" data-recalc-dims="1" />
<p>The testing observations, shown as black points to the right of the dashed line, fall within the forecast intervals. But where does all of that forecast uncertainty come from? <code>forecast_uncertainty()</code> splits the forecast variance into contributions from uncertainty in the regression coefficients, uncertainty in the parameters of the latent dynamics and the process error that accumulates as the forecast moves further away from the training data:</p>
<pre>plot(forecast_uncertainty(fit, newdata = pp_test))
</pre><img src="https://i1.wp.com/ecogambler.netlify.app/blog/mvgam-2/index_files/figure-html/uncertainty-1.png?w=70%25&#038;ssl=1" alt="" style="display: block; margin: auto;" data-recalc-dims="1" />
<p>Process error dominates at every horizon. The total variance roughly triples over the first eight months before levelling off. This process error represents month-to-month variation in the population that none of the covariates in the model can explain. It accumulates with every additional month that the forecast extends beyond the data. The 
<a href="https://nicholasjclark.github.io/mvgam/articles/mvgam_overview.html" rel="nofollow" target="_blank">overview vignette</a> takes this example further with residual checks, a model of all four rodent species with correlated dynamics and comparisons of forecast scores. The 
<a href="https://nicholasjclark.github.io/mvgam/articles/forecast_evaluation.html" rel="nofollow" target="_blank">forecast evaluation article</a> covers <code>compare_scores()</code> and <code>compare_elpds()</code> for choosing among models.</p>




<h2 id="imperfect-detection-and-joint-species-distribution-models">Imperfect detection and joint species distribution models
  <a href="https://ecogambler.netlify.app/blog/mvgam-2/#imperfect-detection-and-joint-species-distribution-models" rel="nofollow" target="_blank"><svg class="anchor-symbol" aria-hidden="true" height="26" width="26" viewBox="0 0 22 22" xmlns="http://www.w3.org/2000/svg">
      <path d="M0 0h24v24H0z" fill="currentColor"></path>
      <path d="M3.9 12c0-1.71 1.39-3.1 3.1-3.1h4V7H7c-2.76.0-5 2.24-5 5s2.24 5 5 5h4v-1.9H7c-1.71.0-3.1-1.39-3.1-3.1zM8 13h8v-2H8v2zm9-6h-4v1.9h4c1.71.0 3.1 1.39 3.1 3.1s-1.39 3.1-3.1 3.1h-4V17h4c2.76.0 5-2.24 5-5s-2.24-5-5-5z"></path>
    </svg></a>
</h2>
<p>Ecological surveys rarely detect every individual, or even every species, that is present. <code>occ()</code> is a new family in version 2.0. Like <code>nmix()</code>, it models the detection process explicitly. The latent process then describes the true occupancy or abundance at each site. <code>forecast(type = &quot;latent_state&quot;)</code> produces forecasts of that true state. Both families now also have multi-season variants. See the 
<a href="https://nicholasjclark.github.io/mvgam/articles/occupancy.html" rel="nofollow" target="_blank">occupancy</a> and 
<a href="https://nicholasjclark.github.io/mvgam/articles/nmix.html" rel="nofollow" target="_blank">N-mixture</a> articles for worked examples.</p>
<p><code>jsdgam()</code> fits joint species distribution models, in which latent factors capture associations among species that the covariates cannot explain. In version 2.0 these models can also include species traits, trait-by-environment interactions, a phylogeny and the composition families. Three functions (<code>species_effects()</code>, <code>community()</code>, <code>residual_cor()</code>) then summarise how each species responds to the environment and which species co-occur more or less often than the covariates would predict. The 
<a href="https://nicholasjclark.github.io/mvgam/articles/jsdgam.html" rel="nofollow" target="_blank">JSDM article</a> works through an example.</p>




<h2 id="moving-from-version-1">Moving from version 1
  <a href="https://ecogambler.netlify.app/blog/mvgam-2/#moving-from-version-1" rel="nofollow" target="_blank"><svg class="anchor-symbol" aria-hidden="true" height="26" width="26" viewBox="0 0 22 22" xmlns="http://www.w3.org/2000/svg">
      <path d="M0 0h24v24H0z" fill="currentColor"></path>
      <path d="M3.9 12c0-1.71 1.39-3.1 3.1-3.1h4V7H7c-2.76.0-5 2.24-5 5s2.24 5 5 5h4v-1.9H7c-1.71.0-3.1-1.39-3.1-3.1zM8 13h8v-2H8v2zm9-6h-4v1.9h4c1.71.0 3.1 1.39 3.1 3.1s-1.39 3.1-3.1 3.1h-4V17h4c2.76.0 5-2.24 5-5s-2.24-5-5-5z"></path>
    </svg></a>
</h2>
<p>Most code written for version 1 will need some rewriting. The main changes are:</p>
<ul>
<li><code>trend_model = AR()</code> becomes <code>trend_formula = ~ AR()</code>. The <code>n_lv</code> and <code>trend_map</code> arguments move into the trend constructor</li>
<li>Data for a model with a latent process need a factor <code>series</code> column, even when there is only one series</li>
<li><code>get_mvgam_priors()</code> becomes <code>get_prior()</code>, <code>code()</code> becomes <code>stancode()</code>, and the <code>plot_mvgam_*()</code> functions become <code>plot()</code> methods</li>
<li><code>gp()</code> replaces <code>GP()</code> and <code>dynamic()</code>. <code>mo()</code> replaces the monotonic smooth bases</li>
<li>Some families are renamed to match <code>brms</code>: <code>nb()</code> is now <code>negbinomial()</code>, <code>student_t()</code> is <code>student()</code> and <code>betar()</code> is <code>Beta()</code></li>
</ul>
<p>The 
<a href="https://nicholasjclark.github.io/mvgam/news/index.html" rel="nofollow" target="_blank">NEWS file</a> lists every breaking change along with its replacement. The 
<a href="https://nicholasjclark.github.io/mvgam/articles/data.html" rel="nofollow" target="_blank">data vignette</a> explains the required data format.</p>




<h2 id="see-the-cheatsheets-for-a-workflow-overview">See the cheatsheets for a workflow overview
  <a href="https://ecogambler.netlify.app/blog/mvgam-2/#see-the-cheatsheets-for-a-workflow-overview" rel="nofollow" target="_blank"><svg class="anchor-symbol" aria-hidden="true" height="26" width="26" viewBox="0 0 22 22" xmlns="http://www.w3.org/2000/svg">
      <path d="M0 0h24v24H0z" fill="currentColor"></path>
      <path d="M3.9 12c0-1.71 1.39-3.1 3.1-3.1h4V7H7c-2.76.0-5 2.24-5 5s2.24 5 5 5h4v-1.9H7c-1.71.0-3.1-1.39-3.1-3.1zM8 13h8v-2H8v2zm9-6h-4v1.9h4c1.71.0 3.1 1.39 3.1 3.1s-1.39 3.1-3.1 3.1h-4V17h4c2.76.0 5-2.24 5-5s-2.24-5-5-5z"></path>
    </svg></a>
</h2>
<p>
<a href="https://nicholasjclark.github.io/mvgam/cheatsheets/mvgam_cheatsheet.pdf" rel="nofollow" target="_blank"><img src="https://i2.wp.com/nicholasjclark.github.io/mvgam/cheatsheets/mvgam_cheatsheet.png?w=578&#038;ssl=1" alt="mvgam usage cheatsheet" data-recalc-dims="1"></a></p>
<p>
<a href="https://nicholasjclark.github.io/mvgam/cheatsheets/jsdgam_cheatsheet.pdf" rel="nofollow" target="_blank"><img src="https://i1.wp.com/nicholasjclark.github.io/mvgam/cheatsheets/jsdgam_cheatsheet.png?w=578&#038;ssl=1" alt="jsdgam cheatsheet for joint species distribution models" data-recalc-dims="1"></a></p>




<h2 id="thanks">Thanks
  <a href="https://ecogambler.netlify.app/blog/mvgam-2/#thanks" rel="nofollow" target="_blank"><svg class="anchor-symbol" aria-hidden="true" height="26" width="26" viewBox="0 0 22 22" xmlns="http://www.w3.org/2000/svg">
      <path d="M0 0h24v24H0z" fill="currentColor"></path>
      <path d="M3.9 12c0-1.71 1.39-3.1 3.1-3.1h4V7H7c-2.76.0-5 2.24-5 5s2.24 5 5 5h4v-1.9H7c-1.71.0-3.1-1.39-3.1-3.1zM8 13h8v-2H8v2zm9-6h-4v1.9h4c1.71.0 3.1 1.39 3.1 3.1s-1.39 3.1-3.1 3.1h-4V17h4c2.76.0 5-2.24 5-5s-2.24-5-5-5z"></path>
    </svg></a>
</h2>
<p>This release relies on the work of Paul Bürkner, the other <code>brms</code> developers and the <code>Stan</code> team. 
<a href="https://github.com/jbogomolovas2" rel="nofollow" target="_blank">@jbogomolovas2</a> worked out the mathematics of the <code>com_binomial()</code> family. Thanks also to everyone who has reported bugs and suggested features. If you find a problem or have an idea, please 
<a href="https://github.com/nicholasjclark/mvgam/issues" rel="nofollow" target="_blank">open an issue on GitHub</a>.</p>

<div style="border: 1px solid; background: none repeat scroll 0 0 #EDEDED; margin: 1px; font-size: 13px;">
<div style="text-align: center;">To <strong>leave a comment</strong> for the author, please follow the link and comment on their blog: <strong><a href="https://ecogambler.netlify.app/blog/mvgam-2/"> GAMbler</a></strong>.</div>
<hr />
<a href="https://www.r-bloggers.com/" rel="nofollow">R-bloggers.com</a> offers <strong><a href="https://feedburner.google.com/fb/a/mailverify?uri=RBloggers" rel="nofollow">daily e-mail updates</a></strong> about <a title="The R Project for Statistical Computing" href="https://www.r-project.org/" rel="nofollow">R</a> news and tutorials about <a title="R tutorials" href="https://www.r-bloggers.com/how-to-learn-r-2/" rel="nofollow">learning R</a> and many other topics. <a title="Data science jobs" href="https://www.r-users.com/" rel="nofollow">Click here if you're looking to post or find an R/data-science job</a>.

<hr>Want to share your content on R-bloggers?<a href="https://www.r-bloggers.com/add-your-blog/" rel="nofollow"> click here</a> if you have a blog, or <a href="http://r-posts.com/" rel="nofollow"> here</a> if you don't.
</div><strong>Continue reading</strong>: <a href="https://www.r-bloggers.com/2026/11/mvgam-2-0-on-cran-state-space-models-built-on-brms/">mvgam 2.0 on CRAN: State-Space models built on brms</a>]]></content:encoded>
					
		
		<enclosure url="" length="0" type="" />

		<post-id xmlns="com-wordpress:feed-additions:1">405140</post-id>	</item>
		<item>
		<title>Customising gratia plots with ggplot2 themes</title>
		<link>https://www.r-bloggers.com/2026/11/customising-gratia-plots-with-ggplot2-themes/</link>
		
		<dc:creator><![CDATA[Gavin Simpson]]></dc:creator>
		<pubDate>Thu, 26 Nov 2026 23:00:00 +0000</pubDate>
				<category><![CDATA[R bloggers]]></category>
		<guid isPermaLink="false">https://fromthebottomoftheheap.net/2026/11/27/gratia-plot-themes/</guid>

					<description><![CDATA[<div style = "width:60%; display: inline-block; float:left; ">
<p>With gratia 0.12.1, you can change the colour of a smooth or the opacity of its interval after calling draw() using the new theme system. These settings now live in ggplot2 themes, alongside familiar options for backgrounds and text. That makes i...</p></div>
<div style = "width: 40%; display: inline-block; float:right;"></div>
<div style="clear: both;"></div>
<strong>Continue reading</strong>: <a href="https://www.r-bloggers.com/2026/11/customising-gratia-plots-with-ggplot2-themes/">Customising gratia plots with ggplot2 themes</a>]]></description>
										<content:encoded><![CDATA[<!-- 
<div style="min-height: 30px;">
[social4i size="small" align="align-left"]
</div>
-->

<div style="border: 1px solid; background: none repeat scroll 0 0 #EDEDED; margin: 1px; font-size: 12px;">
[This article was first published on  <strong><a href="https://fromthebottomoftheheap.net/2026/11/27/gratia-plot-themes/"> From the bottom of the heap — R posts</a></strong>, and kindly contributed to <a href="https://www.r-bloggers.com/" rel="nofollow">R-bloggers</a>].  (You can report issue about the content on this page <a href="https://www.r-bloggers.com/contact-us/">here</a>)
<hr>Want to share your content on R-bloggers?<a href="https://www.r-bloggers.com/add-your-blog/" rel="nofollow"> click here</a> if you have a blog, or <a href="http://r-posts.com/" rel="nofollow"> here</a> if you don't.
</div>






<div class="no-row-height column-margin column-container"></div><p>With gratia 0.12.1, you can change the colour of a smooth or the opacity of its interval <em>after</em> calling <code>draw()</code> using the new theme system. These settings now live in ggplot2 themes, alongside familiar options for backgrounds and text. That makes it easier to use the same style across several figures or give an existing figure a different look.</p>
<p>I’ll use two curves from a plant experiment to show how to style a set of panels, reuse the style, and choose colours for grouped curves.</p>
<section id="start-with-a-fitted-model" class="level2">
<h2 data-anchor-id="start-with-a-fitted-model">Start with a fitted model</h2>
<p>The <code>CO2</code> data that come with R record carbon dioxide uptake by grass plants from Quebec and Mississippi. Half the plants from each origin were chilled, and uptake was measured at the same set of concentrations for each plant <span class="citation" data-cites="potvin-lechowicz-tardif-1990">(Potvin et al., 1990)</span>.</p>
<p>For this post I’ll reuse the model from gratia’s <a href="https://gavinsimpson.github.io/gratia/articles/prediction-comparisons.html" rel="nofollow" target="_blank">prediction comparisons article</a>. It fits a separate concentration smooth for each treatment and includes a plant random intercept for the repeated measurements.</p>
<div class="cell">
<pre>library(&quot;mgcv&quot;)
library(&quot;gratia&quot;)
library(&quot;ggplot2&quot;)
library(&quot;dplyr&quot;)

plant &lt;- as_tibble(datasets::CO2) |&gt;
  mutate(
    Plant = factor(Plant, ordered = FALSE),
    Treatment = factor(
      Treatment,
      levels = c(&quot;nonchilled&quot;, &quot;chilled&quot;),
      labels = c(&quot;Non-chilled plants&quot;, &quot;Chilled plants&quot;)
    )
  )

m &lt;- gam(
  uptake ~ Type * Treatment + s(conc, by = Treatment, k = 5) +
    s(Plant, bs = &quot;re&quot;),
  data = plant, family = Gamma(link = &quot;log&quot;), method = &quot;REML&quot;
)</pre>
</div>
<p>To keep the plots simple, I’ll focus only on the two estimated smooth functions, using <code>draw()</code>’s <code>select</code> argument with <code>partial_match = TRUE</code> to pick out the two concentration smooths by their shared label, <code>s(conc)</code>. The curves show each smooth’s contribution on the log scale. The <em>ggplot</em> object is saved so that it can be reused.</p>
<div class="cell">
<pre>p &lt;- draw(m, select = &quot;s(conc)&quot;, partial_match = TRUE, ncol = 2)
p</pre>
<div class="cell-output-display">
<div>
<figure class="figure">
<p><img src="https://i0.wp.com/fromthebottomoftheheap.net/2026/11/27/gratia-plot-themes/index_files/figure-html/default-uptake-smooths-1.png?w=450&#038;ssl=1" class="img-fluid figure-img" alt="Two panels show the concentration smooths for non-chilled and chilled plants as black curves with grey uncertainty ribbons."  data-recalc-dims="1"></p>
</figure>
</div>
</div>
</div>
</section>
<section id="style-the-curve-and-its-interval" class="level2">
<h2 data-anchor-id="style-the-curve-and-its-interval">Style the curve and its interval</h2>
<p>The theme element <code>geom.gratia.smooth</code> controls the fitted line. <code>geom.gratia.interval</code> supplies the ribbon fill, while <code>gratia.alpha.interval</code> controls how transparent the fill is. I’ll use the same blue for the line and ribbon, with a lower opacity for the ribbon.</p>
<div class="cell">
<pre>uptake_style &lt;- theme(
  geom.gratia.smooth = element_geom(colour = &quot;#275D8C&quot;, linewidth = 0.9),
  geom.gratia.interval = element_geom(fill = &quot;#275D8C&quot;),
  gratia.alpha.interval = 0.18
)

p &#038; theme_bw() &#038; uptake_style</pre>
<div class="cell-output-display">
<div>
<figure class="figure">
<p><img src="https://i2.wp.com/fromthebottomoftheheap.net/2026/11/27/gratia-plot-themes/index_files/figure-html/themed-uptake-smooths-1.png?w=450&#038;ssl=1" class="img-fluid figure-img" alt="The same two smooth panels on white backgrounds, with dark blue curves and pale blue ribbons."  data-recalc-dims="1"></p>
</figure>
</div>
</div>
</div>
<p><code>draw()</code> returns a patchwork, so <em>patchwork</em>’s <code>&</code> is used to send both themes to every panel. With a single ggplot, use <code>+</code>. When used with a combined figure, <code>+</code> would apply the theme to the last panel only.</p>
<p>If you’re updating an existing script, move <code>smooth_col</code> from the <code>draw()</code> call into <code>geom.gratia.smooth</code>, <code>ci_col</code> into <code>geom.gratia.interval</code>, and <code>ci_alpha</code> into <code>gratia.alpha.interval</code>. The old arguments are deprecated. While they still work, an explicitly supplied colour or opacity takes precedence over the corresponding theme setting, so remove it from the call when you migrate.</p>
</section>
<section id="reuse-the-theme-for-new-plots" class="level2">
<h2 data-anchor-id="reuse-the-theme-for-new-plots">Reuse the theme for new plots</h2>
<p>Use <code>gratia_theme_set()</code> to style a series of new plots. Each call invisibly returns the gratia theme that was active immediately before the call, or <code>NULL</code> if no gratia theme was set. I save that value in <code>previous_style</code> so I can restore it after assembling the panels.</p>
<p>I put <code>theme_bw()</code> first because it sets a complete theme. Adding <code>uptake_style</code> after it gives me the white background with the blue line and ribbon.</p>
<div class="cell">
<pre>previous_style &lt;- gratia_theme_set(theme_bw() + uptake_style)
panels &lt;- assemble(m, select = &quot;s(conc)&quot;, partial_match = TRUE)
gratia_theme_set(previous_style)

panels[[1]]</pre>
<div class="cell-output-display">
<div>
<figure class="figure">
<p><img src="https://i0.wp.com/fromthebottomoftheheap.net/2026/11/27/gratia-plot-themes/index_files/figure-html/reusable-uptake-style-1.png?w=450&#038;ssl=1" class="img-fluid figure-img" alt="The first treatment smooth alone, with a white background and the same blue curve and ribbon."  data-recalc-dims="1"></p>
</figure>
</div>
</div>
</div>
<p><code>assemble()</code> attaches the combined theme to each panel as it creates it. Restoring <code>previous_style</code> sets the theme for future gratia plots. The saved panel still has its white background and blue styling. Use <code>gratia_theme_get()</code> to see which gratia theme is active.</p>
</section>
<section id="using-a-shared-palette-for-colour-and-fill-scales" class="level2">
<h2 data-anchor-id="using-a-shared-palette-for-colour-and-fill-scales">Using a shared palette for colour and fill scales</h2>
<p>Often, we want to put the set of factor-by smooths in one panel using <code>grouped = &quot;factor-by&quot;</code>. Then, colour identifies the grouping variable, which here is the treatment. For mapped colours like these, we can use one of the many discrete palettes available for ggplot2, and which can also be set through the theme. <code>gratia_palette()</code> supplies a palette function. Give the same function to the colour and fill settings so each curve matches its own ribbon. In the code below, I switch to Paul Tol’s <em>bright</em> colour palette instead of the default Okabe Ito palette.</p>
<p>I also wrap the treatment labels in the legend with <code>draw_label_control()</code>. That comes in handy when the figure has to fit in a narrow column.</p>
<div class="cell">
<pre>tol &lt;- gratia_palette(&quot;tol_bright&quot;)
legend_layout &lt;- draw_label_control(legend = list(wrap = 15))

draw(
  m, select = &quot;s(conc)&quot;, partial_match = TRUE,
  grouped = &quot;factor-by&quot;, label_control = legend_layout
) &#038;
  theme_bw() &#038;
  theme(palette.colour.discrete = tol, palette.fill.discrete = tol)</pre>
<div class="cell-output-display">
<div>
<figure class="figure">
<p><img src="https://i1.wp.com/fromthebottomoftheheap.net/2026/11/27/gratia-plot-themes/index_files/figure-html/grouped-uptake-palette-1.png?w=450&#038;ssl=1" class="img-fluid figure-img" alt="The two treatment curves overlaid, with each line and its ribbon sharing a colour and the longer treatment label wrapped in the legend."  data-recalc-dims="1"></p>
</figure>
</div>
</div>
</div>
<p>Paul Tol’s palettes have different capacities, so pick one with enough colours for your groups. That said, trying to distinguish groups by colour is going to be difficulty as the number of groups gets large.</p>
<p>For the full list of component settings and mappings from older arguments, see the package’s <a href="https://gavinsimpson.github.io/gratia/articles/custom-plotting.html" rel="nofollow" target="_blank">Customising gratia plots article</a>.</p>
</section>
<section id="future-directions" class="level2">
<h2 data-anchor-id="future-directions">Future directions</h2>
<p>This is the first outing for the theming system, and there are some features of ggplot2’s themes that aren’t part of the new gratia system, so clashes may occur. If you have comments on the new theme system or suggestions for additions to it, let me know in the comments below.</p>
</section>
<section id="references" class="level2">
<h2 data-anchor-id="references">References</h2>
<div id="refs" class="references csl-bib-body hanging-indent">
<div id="ref-potvin-lechowicz-tardif-1990" class="csl-entry">
Potvin, C., Lechowicz, M. J., and Tardif, S. (1990). The statistical analysis of ecophysiological response curves obtained from experiments involving repeated measures. <em>Ecology</em> 71, 1389–1400. doi:<a href="https://doi.org/10.2307/1938276" rel="nofollow" target="_blank">10.2307/1938276</a>.
</div>
</div>


</section>

 
<div style="border: 1px solid; background: none repeat scroll 0 0 #EDEDED; margin: 1px; font-size: 13px;">
<div style="text-align: center;">To <strong>leave a comment</strong> for the author, please follow the link and comment on their blog: <strong><a href="https://fromthebottomoftheheap.net/2026/11/27/gratia-plot-themes/"> From the bottom of the heap — R posts</a></strong>.</div>
<hr />
<a href="https://www.r-bloggers.com/" rel="nofollow">R-bloggers.com</a> offers <strong><a href="https://feedburner.google.com/fb/a/mailverify?uri=RBloggers" rel="nofollow">daily e-mail updates</a></strong> about <a title="The R Project for Statistical Computing" href="https://www.r-project.org/" rel="nofollow">R</a> news and tutorials about <a title="R tutorials" href="https://www.r-bloggers.com/how-to-learn-r-2/" rel="nofollow">learning R</a> and many other topics. <a title="Data science jobs" href="https://www.r-users.com/" rel="nofollow">Click here if you're looking to post or find an R/data-science job</a>.

<hr>Want to share your content on R-bloggers?<a href="https://www.r-bloggers.com/add-your-blog/" rel="nofollow"> click here</a> if you have a blog, or <a href="http://r-posts.com/" rel="nofollow"> here</a> if you don't.
</div><strong>Continue reading</strong>: <a href="https://www.r-bloggers.com/2026/11/customising-gratia-plots-with-ggplot2-themes/">Customising gratia plots with ggplot2 themes</a>]]></content:encoded>
					
		
		<enclosure url="" length="0" type="" />

		<post-id xmlns="com-wordpress:feed-additions:1">405142</post-id>	</item>
		<item>
		<title>“Just ask the model for translation”</title>
		<link>https://www.r-bloggers.com/2026/11/just-ask-the-model-for-translation/</link>
		
		<dc:creator><![CDATA[Colin Fay]]></dc:creator>
		<pubDate>Thu, 26 Nov 2026 13:16:32 +0000</pubDate>
				<category><![CDATA[R bloggers]]></category>
		<guid isPermaLink="false">https://rtask.thinkr.fr/?p=30283</guid>

					<description><![CDATA[<div style = "width:60%; display: inline-block; float:left; "> You can read the original post in its original format on Rtask website by ThinkR here: “Just ask the model for translation”<br />
I was recently in charge of ensuring the migration from a piece of code that translated text with a translation API to a setup where only LLMs were ...</div>
<div style = "width: 40%; display: inline-block; float:right;"></div>
<div style="clear: both;"></div>
<strong>Continue reading</strong>: <a href="https://www.r-bloggers.com/2026/11/just-ask-the-model-for-translation/">“Just ask the model for translation”</a>]]></description>
										<content:encoded><![CDATA[<!-- 
<div style="min-height: 30px;">
[social4i size="small" align="align-left"]
</div>
-->

<div style="border: 1px solid; background: none repeat scroll 0 0 #EDEDED; margin: 1px; font-size: 12px;">
[This article was first published on  <strong><a href="https://rtask.thinkr.fr/just-ask-the-model-for-translation/"> Rtask</a></strong>, and kindly contributed to <a href="https://www.r-bloggers.com/" rel="nofollow">R-bloggers</a>].  (You can report issue about the content on this page <a href="https://www.r-bloggers.com/contact-us/">here</a>)
<hr>Want to share your content on R-bloggers?<a href="https://www.r-bloggers.com/add-your-blog/" rel="nofollow"> click here</a> if you have a blog, or <a href="http://r-posts.com/" rel="nofollow"> here</a> if you don't.
</div>
<p>You can read the original post in its original format on <a rel="nofollow" href="https://rtask.thinkr.fr/" target="_blank">Rtask</a> website by ThinkR here: <a rel="nofollow" href="https://rtask.thinkr.fr/just-ask-the-model-for-translation/" target="_blank">“Just ask the model for translation”</a></p>
<p>I was recently in charge of ensuring the migration from a piece of code that translated text with a translation API to a setup where only LLMs were available. When I asked how to set up the translation, I was told to <strong>“just ask the model for translation”</strong>. I wish it was that simple <img src="https://s.w.org/images/core/emoji/13.0.0/72x72/1f605.png" alt="😅" class="wp-smiley" style="height: 1em; max-height: 1em;" /></p>
<p>Side note: this blogpost wasn’t written by an LLM, and to prove it, here is a picture of me writing it:</p>
<p><img loading="lazy" fetchpriority="high" decoding="async" src="https://i0.wp.com/rtask.thinkr.fr/wp-content/uploads/colin-writing-1024x512.jpg?w=450&#038;ssl=1" alt="" class="aligncenter size-large wp-image-30300" srcset_temp="https://i0.wp.com/rtask.thinkr.fr/wp-content/uploads/colin-writing-1024x512.jpg?w=450&#038;ssl=1 1024w, https://rtask.thinkr.fr/wp-content/uploads/colin-writing-300x150.jpg 300w, https://rtask.thinkr.fr/wp-content/uploads/colin-writing-768x384.jpg 768w, https://rtask.thinkr.fr/wp-content/uploads/colin-writing.jpg 1200w" sizes="(max-width: 1024px) 100vw, 1024px" data-recalc-dims="1" /></p>
<p>But yes, Claude proof-read it, given that, you know, I’m a French guy writing in English. And fun fact: the French translation was performed by Claude, but that’s easier as I’m able to re-read it 🫣</p>
<h2>Context</h2>
<p>(Yep, the real client context is not that one but I kept confidentiality)</p>
<p>The product is a Shiny app that allows you to search for a metal band, get the list of available albums, and print the lyrics of all the songs inside a web page. You can then download a pdf of the lyrics on your laptop. The content is stored inside the app as YAML files, where entries are in markdown.</p>
<p>We display on the page both an entry with the band bio (very simple, just <code>{band} is a {style} band from {country}</code>), and the lyrics, in their original language, and a translation in a handful of other languages. Given that these are metal lyrics, the topics can be very specific, and contain names that need to be kept in their original language, and other specificity like places, references, etc.</p>
<p>The content arrives in R as a list of markdown strings, so that it can be both displayed on the page and written to pdf with Quarto. Yes, there might be better solutions to do that, but we’re not here to discuss that. We’re here to talk about the transition from sending this R list of markdown strings to the Google Translation API, to sending it to an LLM.</p>
<h2>The issue with LLM translation</h2>
<blockquote><p>
  Notes: for the sake of demonstration, the code in this section is just a prompt to the API with the model version and “Translate the following text from English to French.”</p>
<p>  Notes bis: the outputs below are illustrative.
</p></blockquote>
<h3>LLMs are non-deterministic</h3>
<p>You can ask them twice the same thing, <strong>they might not respond the same</strong>. Which is not what we want for our use case, both because of the content and because of the technical format:</p>
<ul>
<li>The markdown should <strong>always be kept as is</strong> so that it’s rendered correctly,</li>
<li>Some parts of the text <strong>should stay as is</strong>. For example, we might not want the lyrics of “We Are Motörhead” to translate the “Motörhead” part.</li>
</ul>
<p>For example, here is a long sentence, passed twice to the same model:</p>
<pre>&gt; translate(
     &quot;The manager told the developer that she had to review the report with her team before the deadline,
      so the client waiting by the bank asked whether he could bring his own light.&quot;,
     model = &quot;claude-sonnet-5-5&quot;
 ) |&gt; extract()
[1] &quot;Le manager a dit à la développeuse qu'elle devait revoir le rapport avec son équipe avant la date limite, alors le client qui attendait près de la banque a demandé s'il pouvait apporter sa propre lumière.&quot;
&gt; translate(
     &quot;The manager told the developer that she had to review the report with her team before the deadline,
      so the client waiting by the bank asked whether he could bring his own light.&quot;,
     model = &quot;claude-sonnet-5-5&quot;
) |&gt; extract()
[1] &quot;Le responsable a dit à la développeuse qu'elle devait revoir le rapport avec son équipe avant la date limite, donc le client attendant près de la banque a demandé s'il pouvait apporter sa propre lumière.&quot;
</pre>
<p>See? “manager” is translated “manager” the first time, and “responsable” the second time, and “so” “alors” then “donc”.</p>
<p>Another example that is crucial to what I was trying to do: the output might return a json object with names that vary:</p>
<pre># First time
&gt; translate_section(
     &quot;Hello world.&quot;
)
$text
[1] &quot;Bonjour le monde&quot;

# Second time
&gt; translate_section(
     &quot;Hello world.&quot;
)
$translation
[1] &quot;Bonjour le monde&quot;
</pre>
<p>Which makes it, well, hard to handle in R because when receiving the JSON and converting it to a list, we want <strong>the structure to always be the same</strong>.</p>
<h3>All models are not made equal</h3>
<p><strong>Some LLMs can determine that something is ambiguous. Others don’t.</strong> Let’s play with the sentence: “I saw her duck”, which is ambiguous by design. Depending on the model you call, you’ll get one version (the animal), or the other (the action), or a large text stating that this is ambiguous.</p>
<h4>With Claude Haiku 5.5</h4>
<pre>&gt; translate(
+     &quot;I saw her duck.&quot;,
+     model = &quot;claude-haiku-5-5&quot;
+   ) |&gt; extract()
[1] &quot;J'ai vu son canard.&quot;
</pre>
<h4>With Claude Sonnet 5.5</h4>
<pre>&gt; translate(
+     &quot;I saw her duck.&quot;,
+     model = &quot;claude-sonnet-5-5&quot;
+   ) |&gt; extract()
[1] &quot;Je l'ai vu se baisser.&quot;
</pre>
<h4>With Claude Opus 5.5</h4>
<pre>&gt; translate(
+   &quot;I saw her duck.&quot;,
+    model = &quot;claude-opus-5-5&quot;
+ ) %&gt;% cat()
Possible translations:

- **Je l'ai vue se baisser.** — if &quot;duck&quot; means *lower her head/body*.
- **J'ai vu son canard.** — if &quot;duck&quot; means the animal belonging to her.
</pre>
<p>The fact that we receive different translations, for now, is fine: this is the behaviour we could have from a standard translation service. But <strong>getting the results from the last call is a bit more problematic</strong>.</p>
<h4>LLM can add elements in their answers</h4>
<p>One known issue with LLMs is that <strong>they can add context to a sentence, or just noise</strong>, like “sure”, or “here is”. That’s what “claude-haiku-5-5” did:</p>
<pre>&gt; translate(
+     &quot;Hello&quot;,
+     model = &quot;claude-haiku-5-5&quot;
+   ) |&gt; extract()
[1] &quot;Hello can be translated to French as \&quot;Bonjour.\&quot;&quot;
</pre>
<p>Which is not what we want in a translation function. Another, subtle element, but most models will add punctuation if you send it a sentence without a final dot.</p>
<pre>&gt; translate(
+     &quot;I see here dog&quot;,
+     model = &quot;claude-sonnet-5-5&quot;
+   ) |&gt; extract()
[1] &quot;Je vois son chien.&quot;
</pre>
<h4>Output might not be predictable</h4>
<p>Another issue that extends from the previous section: I found a case where <strong>asking for JSON returned the markdown fences</strong>:</p>
<pre>&gt; translate(
+     &quot;I see here dog&quot;,
+     model = &quot;claude-sonnet-5-5&quot;
+   ) |&gt; extract()
[1] &quot;```json {'result':''...&quot;
</pre>
<h2>So, what do we do?</h2>
<p>We would expect from a generative service to get different answers. I mean, we’re kind of used to the idea that if we ask Claude “generate me lyrics for a death metal song”, we’ll get a different answer.</p>
<p>But that’s not what we want from a translator: we need the response to be, if not fully predictable, at least <strong>structured, and constrained</strong> enough so that it can go through the rest of the pipeline (markdown rendering, Quarto, PDF) without anything breaking.</p>
<p>Spoiler: <strong>nothing below makes the model deterministic</strong>. It only shrinks what the model is allowed to answer, and detects when it goes out of bounds anyway.</p>
<h3>Structured output</h3>
<p>The first thing we need to be sure of: the output has <strong>a predictable structure</strong>, so that it can be handled in R without any problem.</p>
<p>The output of the LLM will be a string, so we need to be sure we use a structured, interoperable format. In other words, we need <strong>a JSON string, with fixed names</strong>. You can prompt your model all you want (“answer with a JSON object with a <code>translation</code> key”), you’ll get <code>translation</code> today, <code>text</code> tomorrow, and a JSON wrapped in markdown fences the day after. This is a real challenge, and Claude offers what is called <strong>structured outputs</strong>: you send a JSON schema with your request, and the API <strong>constrains the generation to match it</strong>. The documentation is here: https://platform.claude.com/docs/en/build-with-claude/structured-outputs</p>
<p>The schema is deliberately boring: one key, one string.</p>
<pre>translation_schema &lt;- list(
  type = &quot;object&quot;,
  properties = list(
    translation = list(
      type = &quot;string&quot;
    )
  ),
  required = list(
    &quot;translation&quot;
  ),
  additionalProperties = FALSE
)

translate_text &lt;- function(
  text,
  system_prompt,
  model = &quot;claude-sonnet-5-5&quot;
) {
  # ...
  httr2::req_body_json(
    list(
      model = model,
      max_tokens = 4096,
      system = system_prompt,
      messages = list(
        list(
          role = &quot;user&quot;,
          content = text
        )
      ),
      output_config = list(
        format = list(
          type = &quot;json_schema&quot;,
          schema = translation_schema
        )
      )
    )
  )
  # ...
}
</pre>
<p>That way, the output Claude returns will be <strong>constrained to the given schema</strong>: a valid JSON with a <code>translation</code> key, in the text block of the response (<code>content[[1]]$text</code> in R), ready to be parsed with <code>jsonlite::fromJSON()</code>.</p>
<h3>Engineering the prompt to enforce things</h3>
<p><strong>A precise prompt can’t guarantee anything</strong>, but it removes most of the annoying behaviours we’ve seen above:</p>
<pre>system_prompt &lt;- paste(
  c(
    &quot;You are a professional translator from English into French.&quot;,
    &quot;Return only the translation: no comment, no explanation, no alternative.&quot;,
    &quot;If the text is ambiguous, pick the most likely reading without mentioning it.&quot;,
    &quot;Keep the Markdown syntax as is (**bold**, _italic_, links) and translate the text inside it.&quot;,
    &quot;Do not add or remove punctuation.&quot;,
    &quot;Keep every [[KEEP_n]] token unchanged.&quot;,
    &quot;Always translate 'manager' as 'responsable'.&quot;
  ),
  collapse = &quot;\n&quot;
)
</pre>
<p>The fun part was iterating over the model, sending things to be translated, and getting the error from it, so that I could enrich the prompt.</p>
<p>As you can see, each rule answers <strong>one failure from the previous section</strong>: “Hello can be translated to French as…” (rule 2), the “Possible translations” answer (rule 3), the missing final dot of “I see here dog” (rule 5), and the <code>manager</code>/<code>responsable</code> flip-flop (the last one: a mini glossary, for terms that must always be translated the same way).</p>
<h3>Keeping some terms as they are</h3>
<p>Remember “We Are Motörhead”? Telling the model “don’t translate band names” works most of the time anyway, but again, we rely on the model to guess them. The app already knows the band name and the album titles, so <strong>instead of asking the model to remember them, I take them out of the text before the call</strong>, as tokens (<code>[[KEEP_1]]</code>, <code>[[KEEP_2]]</code>…), and put them back after, with a small dictionary:</p>
<pre>|key   | value    |
|---   |---       |
|KEEP_1| Motörhead|
</pre>
<h3>Checking what comes back</h3>
<p><strong>A prompt is a request, not a guarantee.</strong> So the last piece is a function that compares the source that is sent, and the translation that comes back: <strong>same number of markdown tokens, and all <code>[[KEEP_n]]</code> still there</strong>. I tried to make word count work as a metric, but the app actually has languages like german, in which the size can vary a lot compared to english.</p>
<p>Of course, this is <strong>a purely syntactical check, and won’t see wrong meanings</strong>. For that, we need <strong>the human eye</strong> anyway.</p>
<h3>Why not translate once?</h3>
<p>We could imagine a translation for the content for each combination of band/language/song and store it in the app. But of course, the real use case is a bit more complicated, and storing is practically impossible, given that <strong>the user can input text in the application</strong> that are included in the translation.</p>
<h2>Conclusion</h2>
<p>“Just ask the model for translation.”</p>
<p>Yes, that’s doable, but not as easy as it sounds. <strong>You can’t just throw a translation request at a model and expect things to work</strong>, and that’s inherently linked to the way LLMs work.</p>
<p>So I did my best, so that, you know, we can be “Motörhead” worldwide.</p>
<p>This post is better presented on its original ThinkR website here: <a rel="nofollow" href="https://rtask.thinkr.fr/just-ask-the-model-for-translation/" target="_blank">“Just ask the model for translation”</a></p>

<div style="border: 1px solid; background: none repeat scroll 0 0 #EDEDED; margin: 1px; font-size: 13px;">
<div style="text-align: center;">To <strong>leave a comment</strong> for the author, please follow the link and comment on their blog: <strong><a href="https://rtask.thinkr.fr/just-ask-the-model-for-translation/"> Rtask</a></strong>.</div>
<hr />
<a href="https://www.r-bloggers.com/" rel="nofollow">R-bloggers.com</a> offers <strong><a href="https://feedburner.google.com/fb/a/mailverify?uri=RBloggers" rel="nofollow">daily e-mail updates</a></strong> about <a title="The R Project for Statistical Computing" href="https://www.r-project.org/" rel="nofollow">R</a> news and tutorials about <a title="R tutorials" href="https://www.r-bloggers.com/how-to-learn-r-2/" rel="nofollow">learning R</a> and many other topics. <a title="Data science jobs" href="https://www.r-users.com/" rel="nofollow">Click here if you're looking to post or find an R/data-science job</a>.

<hr>Want to share your content on R-bloggers?<a href="https://www.r-bloggers.com/add-your-blog/" rel="nofollow"> click here</a> if you have a blog, or <a href="http://r-posts.com/" rel="nofollow"> here</a> if you don't.
</div><strong>Continue reading</strong>: <a href="https://www.r-bloggers.com/2026/11/just-ask-the-model-for-translation/">“Just ask the model for translation”</a>]]></content:encoded>
					
		
		<enclosure url="" length="0" type="" />

		<post-id xmlns="com-wordpress:feed-additions:1">405124</post-id>	</item>
		<item>
		<title>vistributions 0.2.2</title>
		<link>https://www.r-bloggers.com/2026/11/vistributions-0-2-2/</link>
		
		<dc:creator><![CDATA[Aravind Hebbali]]></dc:creator>
		<pubDate>Thu, 26 Nov 2026 00:00:00 +0000</pubDate>
				<category><![CDATA[R bloggers]]></category>
		<guid isPermaLink="false">https://blog.rsquaredacademy.com/posts/vistributions-0-2-2/</guid>

					<description><![CDATA[<div style = "width:60%; display: inline-block; float:left; ">
<p>vistributions 0.2.2</p>
<p>vistributions draws the probability and percentile questions you ask of the normal, t, chi-square, F and binomial distributions, with the answer printed on the plot.<br />
Version 0.2.2 is a correctness release. What the plot shade...</p></div>
<div style = "width: 40%; display: inline-block; float:right;"></div>
<div style="clear: both;"></div>
<strong>Continue reading</strong>: <a href="https://www.r-bloggers.com/2026/11/vistributions-0-2-2/">vistributions 0.2.2</a>]]></description>
										<content:encoded><![CDATA[<!-- 
<div style="min-height: 30px;">
[social4i size="small" align="align-left"]
</div>
-->

<div style="border: 1px solid; background: none repeat scroll 0 0 #EDEDED; margin: 1px; font-size: 12px;">
[This article was first published on  <strong><a href="https://blog.rsquaredacademy.com/posts/vistributions-0-2-2/"> Rsquared Academy Blog</a></strong>, and kindly contributed to <a href="https://www.r-bloggers.com/" rel="nofollow">R-bloggers</a>].  (You can report issue about the content on this page <a href="https://www.r-bloggers.com/contact-us/">here</a>)
<hr>Want to share your content on R-bloggers?<a href="https://www.r-bloggers.com/add-your-blog/" rel="nofollow"> click here</a> if you have a blog, or <a href="http://r-posts.com/" rel="nofollow"> here</a> if you don't.
</div>
 




<p>vistributions 0.2.2</p>
<p><img src="https://i0.wp.com/blog.rsquaredacademy.com/img/vistributions-0-2-2.png?w=578&#038;ssl=1" class="img-fluid" style="width:100.0%" alt="vistributions hex logo next to the tagline Visualize probabilities and percentiles of distributions in R, the line 0.2.2, accuracy and input checks, the package name vistributions and vistributions.rsquaredacademy.com" data-recalc-dims="1"></p>
<p>vistributions draws the probability and percentile questions you ask of the normal, t, chi-square, F and binomial distributions, with the answer printed on the plot.</p>
<p>Version 0.2.2 is a correctness release. What the plot shades and what its caption prints now agree with the exact probability, and inputs that cannot describe an event stop with a clear message. If you use the binomial functions to size an event, read the first section.</p>
<section id="install-from-cran" class="level2">
<h2 class="anchored" data-anchor-id="install-from-cran">Install from CRAN</h2>
<div class="cell">
<details open="" class="code-fold">
<summary>Code</summary>
<pre>install.packages(&quot;vistributions&quot;)</pre>
</details>
</div>
<p>The full list of changes is in the <a href="https://vistributions.rsquaredacademy.com/news/" rel="nofollow" target="_blank">release notes</a>.</p>
</section>
<section id="shading-follows-the-event" class="level2">
<h2 class="anchored" data-anchor-id="shading-follows-the-event">Shading follows the event</h2>
<p>A trial cohort has 40 users, and about 25% of trial users usually upgrade. How likely is it that exactly 10 of them upgrade?</p>
<div class="cell">
<details open="" class="code-fold">
<summary>Code</summary>
<pre>vdist_binom_prob(n = 40, p = 0.25, s = 10, type = &quot;exact&quot;)</pre>
</details>
<div class="cell-output-display">
<div>
<figure class="figure">
<p><img src="https://i2.wp.com/blog.rsquaredacademy.com/posts/vistributions-0-2-2/index_files/figure-html/binom-exact-1.png?w=450&#038;ssl=1" class="img-fluid figure-img" alt="Binomial distribution of upgrades out of 40 trial users at a 25% rate, with the bar for exactly 10 upgrades shaded and the caption P(X = 10)."  data-recalc-dims="1"></p>
</figure>
</div>
</div>
</div>
<p>The exact value, from base R:</p>
<div class="cell">
<details open="" class="code-fold">
<summary>Code</summary>
<pre>dbinom(10, size = 40, prob = 0.25)</pre>
</details>
<div class="cell-output cell-output-stdout">
<pre>[1] 0.1443643</pre>
</div>
</div>
<p>The caption and the shaded bar match this value. The change matters most for large <code>n</code>, where bars are grouped. A grouped bar that crossed the cutoff was painted whole: for <code>n = 10000</code>, <code>p = 0.01</code> and <code>s = 100</code>, the shaded area was 19.26% for an event whose exact probability is 4.01% (<a href="https://vistributions.rsquaredacademy.com/news/" rel="nofollow" target="_blank">release notes</a>). Every event cutoff is now a bar edge, so the shaded bar heights add up to <code>dbinom()</code> or <code>pbinom()</code> for the event.</p>
</section>
<section id="inputs-that-cannot-be-an-event" class="level2">
<h2 class="anchored" data-anchor-id="inputs-that-cannot-be-an-event">Inputs that cannot be an event</h2>
<p>A count of successes has to lie between 0 and the number of trials. Asking for a negative count used to be accepted, with the caption <code>P(X) &lt;= -1 = 0</code>. It now gives the same clear error as a count above <code>n</code>:</p>
<div class="cell">
<details open="" class="code-fold">
<summary>Code</summary>
<pre>tryCatch(
  vdist_binom_prob(n = 10, p = 0.3, s = -1, type = &quot;lower&quot;),
  error = function(e) conditionMessage(e)
)</pre>
</details>
<div class="cell-output cell-output-stdout">
<pre>[1] &quot;s must be a whole number of successes between 0 and n (n = 10).&quot;</pre>
</div>
</div>
<p>The same release adds checks for the other families, for example whole-number arguments for the binomial and a documented range for percentile probabilities (<code>1e-12 &lt; probs &lt; 1 - 1e-12</code>).</p>
</section>
<section id="percentiles-under-a-decimal-comma" class="level2">
<h2 class="anchored" data-anchor-id="percentiles-under-a-decimal-comma">Percentiles under a decimal comma</h2>
<p>Delivery times are about 48 hours on average, with a standard deviation of 6 hours. By what time have 95% of orders arrived?</p>
<p>With <code>options(OutDec = &quot;,&quot;)</code>, which is common in European locales, every percentile and probability export used to fail with <code>NAs introduced by coercion</code>. The decimal mark is now fixed to <code>.</code> wherever numbers are printed and parsed back:</p>
<div class="cell">
<details open="" class="code-fold">
<summary>Code</summary>
<pre>old &lt;- options(OutDec = &quot;,&quot;)
vdist_normal_perc(probs = 0.95, mean = 48, sd = 6, type = &quot;lower&quot;)</pre>
</details>
<div class="cell-output-display">
<div>
<figure class="figure">
<p><img src="https://i2.wp.com/blog.rsquaredacademy.com/posts/vistributions-0-2-2/index_files/figure-html/outdec-1.png?w=450&#038;ssl=1" class="img-fluid figure-img" alt="Normal distribution of delivery times with mean 48 hours and standard deviation 6 hours, the lower 95% shaded and the 95th percentile cutoff marked."  data-recalc-dims="1"></p>
</figure>
</div>
</div>
<details open="" class="code-fold">
<summary>Code</summary>
<pre>options(old)</pre>
</details>
</div>
<div class="cell">
<details open="" class="code-fold">
<summary>Code</summary>
<pre>qnorm(0.95, mean = 48, sd = 6)</pre>
</details>
<div class="cell-output cell-output-stdout">
<pre>[1] 57.86912</pre>
</div>
</div>
</section>
<section id="other-improvements" class="level2">
<h2 class="anchored" data-anchor-id="other-improvements">Other improvements</h2>
<ul>
<li>Continuous percentile probabilities and the normal scale have documented limits, and every limit stops with its own message.</li>
<li>Captions print enough digits for the percentage they show, including probabilities below 0.1%.</li>
<li>Binomial captions put the inequality inside <code>P()</code>, for example <code>P(X &gt;= 4)</code>, and round once from the exact probability.</li>
<li><code>vdist_t_*()</code>, <code>vdist_chisquare_*()</code> and <code>vdist_f_*()</code> no longer truncate non-integer degrees of freedom.</li>
<li>Plot grids have a bounded number of points, however large the scale.</li>
</ul>
<p>The release notes carry the rest.</p>
</section>
<section id="documentation" class="level2">
<h2 class="anchored" data-anchor-id="documentation">Documentation</h2>
<p>Documentation and examples for every function are at <a href="https://vistributions.rsquaredacademy.com/" rel="nofollow" target="_blank">vistributions.rsquaredacademy.com</a>. Report problems at <a href="https://github.com/rsquaredacademy/vistributions/issues" rel="nofollow" target="_blank">github.com/rsquaredacademy/vistributions/issues</a>.</p>


</section>

 
<div style="border: 1px solid; background: none repeat scroll 0 0 #EDEDED; margin: 1px; font-size: 13px;">
<div style="text-align: center;">To <strong>leave a comment</strong> for the author, please follow the link and comment on their blog: <strong><a href="https://blog.rsquaredacademy.com/posts/vistributions-0-2-2/"> Rsquared Academy Blog</a></strong>.</div>
<hr />
<a href="https://www.r-bloggers.com/" rel="nofollow">R-bloggers.com</a> offers <strong><a href="https://feedburner.google.com/fb/a/mailverify?uri=RBloggers" rel="nofollow">daily e-mail updates</a></strong> about <a title="The R Project for Statistical Computing" href="https://www.r-project.org/" rel="nofollow">R</a> news and tutorials about <a title="R tutorials" href="https://www.r-bloggers.com/how-to-learn-r-2/" rel="nofollow">learning R</a> and many other topics. <a title="Data science jobs" href="https://www.r-users.com/" rel="nofollow">Click here if you're looking to post or find an R/data-science job</a>.

<hr>Want to share your content on R-bloggers?<a href="https://www.r-bloggers.com/add-your-blog/" rel="nofollow"> click here</a> if you have a blog, or <a href="http://r-posts.com/" rel="nofollow"> here</a> if you don't.
</div><strong>Continue reading</strong>: <a href="https://www.r-bloggers.com/2026/11/vistributions-0-2-2/">vistributions 0.2.2</a>]]></content:encoded>
					
		
		<enclosure url="https://blog.rsquaredacademy.com/img/vistributions-0-2-2.png" length="0" type="image/png" />

		<post-id xmlns="com-wordpress:feed-additions:1">405128</post-id>	</item>
		<item>
		<title>rOpenSci News Digest, November 2026</title>
		<link>https://www.r-bloggers.com/2026/11/ropensci-news-digest-november-2026/</link>
		
		<dc:creator><![CDATA[rOpenSci]]></dc:creator>
		<pubDate>Thu, 26 Nov 2026 00:00:00 +0000</pubDate>
				<category><![CDATA[R bloggers]]></category>
		<guid isPermaLink="false">https://ropensci.org/blog/2026/11/26/news-november-2026/</guid>

					<description><![CDATA[<p>Dear rOpenSci friends, it’s time for our monthly news roundup! You can read this post on our blog. Now let’s dive into the activity at and around rOpenSci!</p>
<p>rOpenSci HQ</p>
<p>New release: rOpenSci Champions Program Mentor Guidelines<br />
We’v...</p>
<strong>Continue reading</strong>: <a href="https://www.r-bloggers.com/2026/11/ropensci-news-digest-november-2026/">rOpenSci News Digest, November 2026</a>]]></description>
										<content:encoded><![CDATA[<!-- 
<div style="min-height: 30px;">
[social4i size="small" align="align-left"]
</div>
-->

<div style="border: 1px solid; background: none repeat scroll 0 0 #EDEDED; margin: 1px; font-size: 12px;">
[This article was first published on  <strong><a href="https://ropensci.org/blog/2026/11/26/news-november-2026/"> rOpenSci - open tools for open science</a></strong>, and kindly contributed to <a href="https://www.r-bloggers.com/" rel="nofollow">R-bloggers</a>].  (You can report issue about the content on this page <a href="https://www.r-bloggers.com/contact-us/">here</a>)
<hr>Want to share your content on R-bloggers?<a href="https://www.r-bloggers.com/add-your-blog/" rel="nofollow"> click here</a> if you have a blog, or <a href="http://r-posts.com/" rel="nofollow"> here</a> if you don't.
</div>

<!-- Before sending DELETE THE INDEX_CACHE and re-knit! -->
<p>Dear rOpenSci friends, it’s time for our monthly news roundup! You can read this post <a href="https://ropensci.org/blog/2026/11/26/news-november-2026" rel="nofollow" target="_blank">on our blog</a>. Now let’s dive into the activity at and around rOpenSci!</p>
<h2>
rOpenSci HQ
</h2><h3>
New release: rOpenSci Champions Program Mentor Guidelines
</h3><p>We’ve released a new version of our <a href="https://ropensci-org.github.io/champions-mentor-guidelines/" rel="nofollow" target="_blank">guide for mentors in our Champions Program</a>. It includes useful content such how to organize a meeting with one’s mentee, and resources about mentoring skills. Check it out!</p>
<h3>
Editorial board updates
</h3><h4>
Welcome Francisco!
</h4><p><a href="https://ropensci.org/author/francisco-rodriguez-sanchez/" rel="nofollow" target="_blank">Francisco Rodriguez-Sanchez</a> joined as a guest editor back in 2023 and has now <a href="https://github.com/ropensci/software-review/issues?q=is%3Aissue++label%3A6%2Fapproved+assignee%3APakillo" rel="nofollow" target="_blank">handled two approved packages</a>. He’s now a full member of the editorial board. Thank you and welcome!</p>
<h4>
Thanks Jeff and Emi!
</h4><p><a href="https://ropensci.org/author/Jeff-Hollister" rel="nofollow" target="_blank">Jeff Hollister</a> and <a href="https://ropensci.org/author/emi-tanaka/" rel="nofollow" target="_blank">Emi Tanaka</a> are stepping off the editorial board. Since 2021 Jeff has <a href="https://github.com/ropensci/software-review/issues?q=is%3Aissue+assignee%3Ajhollist+label%3A6%2Fapproved" rel="nofollow" target="_blank">handled seven approved packages</a> and served twice as the Editor-in-Chief. Emi joined the editorial board in 2023 and has <a href="https://github.com/ropensci/software-review/issues?q=is%3Aissue+assignee%3Aemitanaka+label%3A6%2Fapproved" rel="nofollow" target="_blank">handled two approved packages</a>. Thank you both and all the best in your next adventures!</p>
<h3>
Quinceañera
</h3><p>We continue to uncover the stories of the people behind rOpenSci. This month, you can read about:</p>
<ul>
<li><a href="https://ropensci.org/blog/2026/11/02/champions-histories-carolina-pradier/" rel="nofollow" target="_blank">Carolina Pradier, rOpenSci Champion and mentor</a>,</li>
<li><a href="https://ropensci.org/blog/2026/11/04/celebrating-ropensci/" rel="nofollow" target="_blank">Athanasia Mo Mowinckel, rOpenSci mentor (and more)</a>,</li>
<li><a href="https://ropensci.org/blog/2026/11/19/brisbane-to-community/" rel="nofollow" target="_blank">Adam Sparks, editor and package maintainer</a>.</li>
</ul>
<p>Stay tuned for more rOpenSci stories.</p>
<h3>
Coworking
</h3><p>Read <a href="https://ropensci.org/blog/2023/06/21/coworking/" rel="nofollow" target="_blank">all about coworking</a>!</p>
<ul>
<li>Tuesday December 8th<sup>*</sup>, 14:00 Europe Central (13:00 UTC) <a href="https://ropensci.org/events/coworking-2026-12/" rel="nofollow" target="_blank">“Code Linting in R”</a>, with <a href="https://ropensci.org/author/steffi-lazerte" rel="nofollow" target="_blank">Steffi LaZerte</a> and co-host <a href="https://ropensci.org/author/etienne-bacher/" rel="nofollow" target="_blank">Etienne Bacher</a>.
<ul>
<li>Read up on Code Linting and apply some linters to your R code</li>
<li>Meet co-host, Etienne Bacher, and discuss code linting in general, or <a href="https://flir.etiennebacher.com/" rel="nofollow" target="_blank">flir</a> and <a href="https://jarl.etiennebacher.com/" rel="nofollow" target="_blank">Jarl</a> in particular<br>
* Note that December coworking is a week later than usual</li>
</ul>
</li>
<li>Tuesday January 19th, 2027 17:00 (UTC) <a href="https://ropensci.org/events/coworking-2027-01/" rel="nofollow" target="_blank">“Getting to know PREreview”</a>, with <a href="https://ropensci.org/author/steffi-lazerte" rel="nofollow" target="_blank">Steffi LaZerte</a> and co-hosts <a href="https://ropensci.org/author/vanessa-fairhurst/" rel="nofollow" target="_blank">Vanessa Fairhurst</a> and <a href="https://ropensci.org/author/daniela-saderi/" rel="nofollow" target="_blank">Daniela Saderi</a>.
<ul>
<li><a href="https://prereview.org/" rel="nofollow" target="_blank">Visit PREreview</a></li>
<li>Meet co-hosts, Vanessa Fairhurst and Daniela Saderi, and learn more about PREreview and how you might get involved</li>
</ul>
</li>
</ul>
<p>And remember, you can always cowork independently on work related to R, work on packages that tend to be neglected, or work on what ever you need to get done!</p>
<h2>
R Project Sprint 2027, 3 days in week of Apr 12, Boston | Virtual
</h2><p>Join this collaborative event to work on contributions to the code and documentation of base R, or to infrastructure that supports such contributions. Travel funding is available for this event. Limited places are available for novice and experienced contributors to participate in person or online. Applications open now: <a href="https://contributor.r-project.org/r-project-sprint-2027" rel="nofollow" target="_blank">https://contributor.r-project.org/r-project-sprint-2027</a> Deadline: Friday 4 December (midnight Anywhere on Earth)</p>
<h2>
Software <img src="https://s.w.org/images/core/emoji/13.0.0/72x72/1f4e6.png" alt="📦" class="wp-smiley" style="height: 1em; max-height: 1em;" />
</h2><p>The following two packages recently became a part of our software suite:</p>
<ul>
<li>
<p><a href="https://docs.ropensci.org/nert" rel="nofollow" target="_blank">nert</a>, developed by Sam Rogers together with Adam H. Sparks, Wasin Pipattungsakul, Russell Edson, and Max Moldovan: Provides curated access to raster environmental data published by Australia’s Terrestrial Ecosystem Research Network (TERN; <a href="https://www.tern.org.au/" rel="nofollow" target="_blank">https://www.tern.org.au/</a>), spanning national soil attribute, soil classification, soil biodiversity, soil moisture, actual evapotranspiration, vegetation canopy height and phenology products. The package reads Cloud-Optimised GeoTIFF (COG) and virtual raster files directly from the TERN data server via Geospatial Data Abstraction Library (GDAL) vsicurl virtual file system range requests, streaming only the requested spatial and temporal subset for efficient data transfer. The environmental raster data are returned as terra SpatRaster objects. A convenient helper function is also provided that provides a batch-download capability given specific locations and dates, returning the extracted data values in an analysis-ready data.table. Access to the TERN datasets using this package requires a free TERN API key. It has been <a href="https://github.com/ropensci/software-review/issues/785" rel="nofollow" target="_blank">reviewed</a> by Michael Sumner and Shandiya Balasubramaniam.</p>
</li>
<li>
<p><a href="https://docs.ropensci.org/camtrapReport" rel="nofollow" target="_blank">camtrapReport</a>, developed by Elham Ebrahimi: Provides an extensible workflow for processing camera-trap data in the Camtrap DP format and automatically generating reproducible data-status and ecological reports in HTML or PDF format. The package supports data-quality checks, ecological summaries, visualisations, maps, tables and modular report sections for wildlife-monitoring applications. Optional taxonomic enrichment queries the Global Biodiversity Information Facility Species API <a href="https://techdocs.gbif.org/en/openapi/v1/species" rel="nofollow" target="_blank">https://techdocs.gbif.org/en/openapi/v1/species</a> through taxize. Browser-based map backgrounds use OpenStreetMap <a href="https://www.openstreetmap.org/" rel="nofollow" target="_blank">https://www.openstreetmap.org</a>, OSM Germany <a href="https://openstreetmap.de/germanstyle/" rel="nofollow" target="_blank">https://openstreetmap.de/germanstyle/</a> and OpenTopoMap <a href="https://opentopomap.org/" rel="nofollow" target="_blank">https://opentopomap.org</a>, subject to their usage terms. It has been <a href="https://github.com/ropensci/software-review/issues/799" rel="nofollow" target="_blank">reviewed</a> by Florian Mayer and Catherine Sun.</p>
</li>
</ul>
<p>Discover <a href="https://ropensci.org/packages" rel="nofollow" target="_blank">more packages</a>, read more about <a href="https://ropensci.org/software-review" rel="nofollow" target="_blank">Software Peer Review</a>.</p>
<h3>
New versions
</h3><p>The following twenty-two packages have had an update since the last newsletter: <a href="https://docs.ropensci.org/nlrx" title="Setup, Run and Analyze NetLogo Model Simulations from R via XML" rel="nofollow" target="_blank">nlrx</a> (<a href="https://github.com/ropensci/nlrx/releases/tag/v0.5.0" rel="nofollow" target="_blank"><code>v0.5.0</code></a>), <a href="https://docs.ropensci.org/cffr" title="Generate Citation File Format (CFF) Metadata" rel="nofollow" target="_blank">cffr</a> (<a href="https://github.com/ropensci/cffr/releases/tag/v1.4.3" rel="nofollow" target="_blank"><code>v1.4.3</code></a>), <a href="https://docs.ropensci.org/parzer" title="Parse Messy Geographic Coordinates" rel="nofollow" target="_blank">parzer</a> (<a href="https://github.com/ropensci/parzer/releases/tag/v0.6.0" rel="nofollow" target="_blank"><code>v0.6.0</code></a>), <a href="https://docs.ropensci.org/nuts" title="Convert European Regional Data" rel="nofollow" target="_blank">nuts</a> (<a href="https://github.com/ropensci/nuts/releases/tag/v1.3.0" rel="nofollow" target="_blank"><code>v1.3.0</code></a>), <a href="https://docs.ropensci.org/ghql" title="General Purpose GraphQL Client" rel="nofollow" target="_blank">ghql</a> (<a href="https://github.com/ropensci/ghql/releases/tag/v0.1.3" rel="nofollow" target="_blank"><code>v0.1.3</code></a>), <a href="https://docs.ropensci.org/tarchetypes" title="Archetypes for Targets" rel="nofollow" target="_blank">tarchetypes</a> (<a href="https://github.com/ropensci/tarchetypes/releases/tag/0.14.2" rel="nofollow" target="_blank"><code>0.14.2</code></a>), <a href="https://docs.ropensci.org/targets" title="Dynamic Function-Oriented Make-Like Declarative Pipelines" rel="nofollow" target="_blank">targets</a> (<a href="https://github.com/ropensci/targets/releases/tag/1.12.1" rel="nofollow" target="_blank"><code>1.12.1</code></a>), <a href="https://docs.ropensci.org/nert" title="Curated Access to TERN Environmental Raster Data" rel="nofollow" target="_blank">nert</a> (<a href="https://github.com/ropensci/nert/releases/tag/v2.1.0" rel="nofollow" target="_blank"><code>v2.1.0</code></a>), <a href="https://docs.ropensci.org/coevolve" title="Fit Bayesian Generalized Dynamic Phylogenetic Models using Stan or JAX" rel="nofollow" target="_blank">coevolve</a> (<a href="https://github.com/ropensci/coevolve/releases/tag/v1.3.0" rel="nofollow" target="_blank"><code>v1.3.0</code></a>), <a href="https://docs.ropensci.org/srr" title="rOpenSci Software Review Roclets" rel="nofollow" target="_blank">srr</a> (<a href="https://github.com/ropensci-review-tools/srr/releases/tag/v1.1.0" rel="nofollow" target="_blank"><code>v1.1.0</code></a>), <a href="https://docs.ropensci.org/lingtypology" title="Linguistic Typology and Mapping" rel="nofollow" target="_blank">lingtypology</a> (<a href="https://github.com/ropensci/lingtypology/releases/tag/v1.1.27" rel="nofollow" target="_blank"><code>v1.1.27</code></a>), <a href="https://docs.ropensci.org/dittodb" title="A Test Environment for Database Requests" rel="nofollow" target="_blank">dittodb</a> (<a href="https://github.com/ropensci/dittodb/releases/tag/v0.1.12" rel="nofollow" target="_blank"><code>v0.1.12</code></a>), <a href="https://docs.ropensci.org/BaseSet" title="Working with Sets the Tidy Way" rel="nofollow" target="_blank">BaseSet</a> (<a href="https://github.com/ropensci/BaseSet/releases/tag/v1.0.1" rel="nofollow" target="_blank"><code>v1.0.1</code></a>), <a href="https://docs.ropensci.org/dbparser" title="Drugs Databases Parser" rel="nofollow" target="_blank">dbparser</a> (<a href="https://github.com/ropensci/dbparser/releases/tag/v2.3.0" rel="nofollow" target="_blank"><code>v2.3.0</code></a>), <a href="https://docs.ropensci.org/dataspice" title="Create Lightweight Schema.org Descriptions of Data" rel="nofollow" target="_blank">dataspice</a> (<a href="https://github.com/ropensci/dataspice/releases/tag/v1.2.1" rel="nofollow" target="_blank"><code>v1.2.1</code></a>), <a href="https://docs.ropensci.org/naijR" title="Operations to Ease Data Analyses Specific to Nigeria" rel="nofollow" target="_blank">naijR</a> (<a href="https://github.com/ropensci/naijR/releases/tag/v0.7.1" rel="nofollow" target="_blank"><code>v0.7.1</code></a>), <a href="https://docs.ropensci.org/EpiStrainDynamics" title="Infer temporal trends of multiple pathogens" rel="nofollow" target="_blank">EpiStrainDynamics</a> (<a href="https://github.com/ropensci/EpiStrainDynamics/releases/tag/v0.2.0" rel="nofollow" target="_blank"><code>v0.2.0</code></a>), <a href="https://docs.ropensci.org/opencage" title="Geocode with the OpenCage API" rel="nofollow" target="_blank">opencage</a> (<a href="https://github.com/ropensci/opencage/releases/tag/v0.3.0" rel="nofollow" target="_blank"><code>v0.3.0</code></a>), <a href="https://docs.ropensci.org/galamm" title="Generalized Additive Latent and Mixed Models" rel="nofollow" target="_blank">galamm</a> (<a href="https://github.com/ropensci/galamm/releases/tag/v0.4.2" rel="nofollow" target="_blank"><code>v0.4.2</code></a>), <a href="https://docs.ropensci.org/frictionless" title="Read and Write Frictionless Data Packages" rel="nofollow" target="_blank">frictionless</a> (<a href="https://github.com/frictionlessdata/frictionless-r/releases/tag/v2.0.1" rel="nofollow" target="_blank"><code>v2.0.1</code></a>), <a href="https://docs.ropensci.org/DataSpaceR" title="Interface to the CAVD DataSpace" rel="nofollow" target="_blank">DataSpaceR</a> (<a href="https://github.com/ropensci/DataSpaceR/releases/tag/v1.0.3" rel="nofollow" target="_blank"><code>v1.0.3</code></a>), and <a href="https://docs.ropensci.org/lakefetch" title="Calculate Fetch and Wave Exposure for Lake Sampling Points" rel="nofollow" target="_blank">lakefetch</a> (<a href="https://github.com/ropensci/lakefetch/releases/tag/v0.1.14" rel="nofollow" target="_blank"><code>v0.1.14</code></a>).</p>
<h2>
Software Peer Review
</h2><p>There are fourteen recently closed and active submissions and 6 submissions on hold. Issues are at different stages:</p>
<ul>
<li>
<p>Two at <a href="https://github.com/ropensci/software-review/issues?q=is%3Aissue+is%3Aopen+sort%3Aupdated-desc+label%3A%226/approved%22" rel="nofollow" target="_blank">‘6/approved’</a>:</p>
<ul>
<li>
<p><a href="https://github.com/ropensci/software-review/issues/799" rel="nofollow" target="_blank">camtrapReport</a>, Camera-Trap Report Generator. Submitted by <a href="https://www.wur.nl/en/persons/e-elham-ebrahimi" rel="nofollow" target="_blank">Elham Ebrahimi</a>.</p>
</li>
<li>
<p><a href="https://github.com/ropensci/software-review/issues/785" rel="nofollow" target="_blank">nert</a>, Curated Access to TERN Environmental Raster Data. Submitted by <a href="https://scholar.google.com.au/citations?user=zG1uKrcAAAAJ&#038;hl=en" rel="nofollow" target="_blank">Max Moldovan</a>.</p>
</li>
</ul>
</li>
<li>
<p>One at <a href="https://github.com/ropensci/software-review/issues?q=is%3Aissue+is%3Aopen+sort%3Aupdated-desc+label%3A%225/awaiting-reviewer(s)-response%22" rel="nofollow" target="_blank">‘5/awaiting-reviewer(s)-response’</a>:</p>
<ul>
<li><a href="https://github.com/ropensci/software-review/issues/744" rel="nofollow" target="_blank">RAQSAPI</a>, A Simple Interface to the US EPA Air Quality System Data Mart API. Submitted by <a href="https://github.com/mccroweyclinton-EPA" rel="nofollow" target="_blank">mccroweyclinton-EPA</a>.</li>
</ul>
</li>
<li>
<p>One at <a href="https://github.com/ropensci/software-review/issues?q=is%3Aissue+is%3Aopen+sort%3Aupdated-desc+label%3A%224/review(s)-in-awaiting-changes%22" rel="nofollow" target="_blank">‘4/review(s)-in-awaiting-changes’</a>:</p>
<ul>
<li><a href="https://github.com/ropensci/software-review/issues/775" rel="nofollow" target="_blank">grumpy</a>, Read NumPy .npy and .npz Files. Submitted by <a href="https://hugogruson.fr/" rel="nofollow" target="_blank">Hugo Gruson</a>.</li>
</ul>
</li>
<li>
<p>Six at <a href="https://github.com/ropensci/software-review/issues?q=is%3Aissue+is%3Aopen+sort%3Aupdated-desc+label%3A%223/reviewer(s)-assigned%22" rel="nofollow" target="_blank">‘3/reviewer(s)-assigned’</a>:</p>
<ul>
<li>
<p><a href="https://github.com/ropensci/software-review/issues/824" rel="nofollow" target="_blank">GeneExprLupusMx</a>, Lupus RNA-Seq Data from Mexican Women with Bilingual Lessons. Submitted by <a href="https://eveliacoss.github.io/" rel="nofollow" target="_blank">Evelia Lorena Coss-Navarrete</a>.</p>
</li>
<li>
<p><a href="https://github.com/ropensci/software-review/issues/809" rel="nofollow" target="_blank">emodnet.wcs</a>, Access EMODnet Web Coverage Service data through R. Submitted by <a href="https://masalmon.eu/" rel="nofollow" target="_blank">Maëlle Salmon</a>.</p>
</li>
<li>
<p><a href="https://github.com/ropensci/software-review/issues/808" rel="nofollow" target="_blank">corila</a>, Sparse modelling with grouped and correlated features allowing for privileged information. Submitted by <a href="https://rauschenberger.github.io/" rel="nofollow" target="_blank">Armin Rauschenberger</a>. (Stats).</p>
</li>
<li>
<p><a href="https://github.com/ropensci/software-review/issues/807" rel="nofollow" target="_blank">qualtdict</a>, Generate Variable Dictionaries and Labelled Survey Data for Qualtrics Surveys. Submitted by <a href="https://github.com/lyh970817" rel="nofollow" target="_blank">lyh970817</a>.</p>
</li>
<li>
<p><a href="https://github.com/ropensci/software-review/issues/796" rel="nofollow" target="_blank">metasurvey.core</a>, Local Engine for Reproducible Survey Data Processing. Submitted by <a href="https://github.com/mauroloprete" rel="nofollow" target="_blank">Mauro Loprete</a>.</p>
</li>
<li>
<p><a href="https://github.com/ropensci/software-review/issues/774" rel="nofollow" target="_blank">tezr</a>, Access Thesis Metadata from Turkiye’s National Thesis Center. Submitted by <a href="https://github.com/emraher" rel="nofollow" target="_blank">Emrah Er</a>.</p>
</li>
</ul>
</li>
<li>
<p>Two at <a href="https://github.com/ropensci/software-review/issues?q=is%3Aissue+is%3Aopen+sort%3Aupdated-desc+label%3A%222/seeking-reviewer(s)%22" rel="nofollow" target="_blank">‘2/seeking-reviewer(s)’</a>:</p>
<ul>
<li>
<p><a href="https://github.com/ropensci/software-review/issues/810" rel="nofollow" target="_blank">dyadicMarkov</a>, Pattern Estimation and Identification for Dyadic Sequences Using Transition Matrices in R. Submitted by <a href="https://github.com/BoellenruecherM" rel="nofollow" target="_blank">Mattia Böllenrücher</a>. (Stats).</p>
</li>
<li>
<p><a href="https://github.com/ropensci/software-review/issues/805" rel="nofollow" target="_blank">tarpolyglot</a>, Run Python, Julia, Rust, and C++ Inside targets Pipeline Steps. Submitted by <a href="https://github.com/Pierre9344" rel="nofollow" target="_blank">Pierre9344</a>.</p>
</li>
</ul>
</li>
<li>
<p>Two at <a href="https://github.com/ropensci/software-review/issues?q=is%3Aissue+is%3Aopen+sort%3Aupdated-desc+label%3A%221/editor-checks%22" rel="nofollow" target="_blank">‘1/editor-checks’</a>:</p>
<ul>
<li>
<p><a href="https://github.com/ropensci/software-review/issues/786" rel="nofollow" target="_blank">seasight</a>, Tools for Seasonal Adjustment Diagnostics and Reporting. Submitted by <a href="https://p-wegmueller.github.io/" rel="nofollow" target="_blank">Philipp Wegmueller</a>. (Stats).</p>
</li>
<li>
<p><a href="https://github.com/ropensci/software-review/issues/777" rel="nofollow" target="_blank">OptSurvCutR</a>, Optimal Survival Cut-Point Discovery for Time-to-Event Analysis with OptSurvCutR. Submitted by <a href="https://github.com/paytonyau" rel="nofollow" target="_blank">Payton Yau</a>. (Stats).</p>
</li>
</ul>
</li>
</ul>
<p>Find out more about <a href="https://ropensci.org/software-review" rel="nofollow" target="_blank">Software Peer Review</a> and how to get involved.</p>
<h2>
On the blog
</h2><!-- Do not forget to rebase your branch! -->
<ul>
<li>
<p><a href="https://ropensci.org/blog/2026/11/04/celebrating-ropensci" rel="nofollow" target="_blank">Kindness, Curiosity, and Kitties: A rOpenSci 15th Anniversary Interview with Mo</a> by Yanina Bellini Saibene. As part of rOpenSci’s 15th anniversary, Community Manager Yani talks with Mo about her journey from a first software review to years of contributions across the rOpenSci community. Mo shares what keeps her involved and offers advice for newcomers.</p>
</li>
<li>
<p><a href="https://ropensci.org/blog/2026/11/19/brisbane-to-community" rel="nofollow" target="_blank">From Brisbane to the rOpenSci Community: Ten Years of Open Research Software</a> by Adam Sparks. A look back at ten years of involvement with rOpenSci, from attending a Unconf to package development, peer review, editorial work, and building open science communities. Through stories of collaboration, learning, and lasting friendships, the post highlights how welcoming communities can shape careers and make open research software stronger. .</p>
</li>
<li>
<p><a href="https://ropensci.org/blog/2026/11/23/ibger" rel="nofollow" target="_blank">Splitting Large Queries to Brazil’s Official Statistics API with ibger</a> by André Leite, Marcos Wasiliew, Hugo Vasconcelos, Carlos Amorim, and Diogo Bezerra. How ibger estimates result sizes and splits large IBGE API queries automatically.</p>
</li>
</ul>
<figure class="center"><img src="https://i2.wp.com/ropensci.org/blog/2026/11/26/news-november-2026/soy-plot-1.png?w=400&#038;ssl=1"
alt="Line charts of Brazilian soybean production and of the number of producing municipalities, both rising from 2000 to 2025."  data-recalc-dims="1">
</figure>
<ul>
<li>
<p><a href="https://ropensci.org/blog/2026/11/02/champions-histories-carolina-pradier" rel="nofollow" target="_blank">Carolina Pradier, rOpenSci champion and mentor</a> by Yanina Bellini Saibene and Alejandra Bellini. This story is that of Carolina Pradier, main maintainer of the eph package. We review her participation in the Champions program and the impact of her work in different organizations and communities.</p>
</li>
<li>
<p><a href="https://ropensci.org/blog/2026/11/19/comm-call-openscapes" rel="nofollow" target="_blank">Making the incidental an invitation in building community</a> by Mara Averick, Hadley Wickham, Mark Padgham, Yanina Bellini Saibene, Julia Stewart Lowndes, Stefanie Butland, and Andy Teucher. Blog post summarizing Openscapes Community Call Open Communities in the age of AI.</p>
</li>
<li>
<p><a href="https://ropensci.org/blog/2026/11/20/hackeaR-LatinR2026" rel="nofollow" target="_blank">Hacking Two Hours of Contributions to R</a> by Yanina Bellini Saibene. What we did during HackeaR, a LatinR event where we got together to make contributions to our favorite programming language. Other languages: <a href='https://ropensci.org/es/blog/2026/11/20/hackeaR-LatinR2026' lang='es' rel="nofollow" target="_blank">Hackeando dos horas de contribuciones a R (es)</a>.</p>
</li>
</ul>
<h2>
Calls for contributions
</h2><p>Refer to our <a href="https://ropensci.org/help-wanted/" rel="nofollow" target="_blank">help wanted page</a> – before opening a PR, we recommend asking in the issue whether help is still needed.</p>
<h2>
Package development corner
</h2><p>Some useful information for R package developers. <img src="https://s.w.org/images/core/emoji/13.0.0/72x72/1f440.png" alt="👀" class="wp-smiley" style="height: 1em; max-height: 1em;" /></p>
<h3>
Coverage on GitHub Actions without codecov
</h3><p>How to get coverage information displayed without codecov? A roundup of current efforts:</p>
<ul>
<li>Earlier this year, Adam Sparks wrote up his <a href="https://adamhsparks.netlify.app/2026/01/24/look-ma-no-codecov-io/" rel="nofollow" target="_blank">strategy</a> for generating a README badge displaying test coverage, without using a third party such as codecov.io.</li>
<li>The <a href="https://github.com/dragosmg/covr2gh" rel="nofollow" target="_blank">covr2gh</a> package by Dragoș Moldovan-Grünfeld provides an automated way to summarise the impact of a pull request (PR) on test coverage directly within GitHub.</li>
<li>The development version of covr gained a <a href="https://covr.r-lib.org/dev/reference/to_badge.html" rel="nofollow" target="_blank"><code>to_badge()</code></a> function to create an svg badge of coverage.</li>
<li>Elio Campitelli added a <a href="https://github.com/eliocamp/tagger/commit/de390422d1abba16df328a0be4b34e25a88f3749" rel="nofollow" target="_blank">GitHub Actions workflow and script</a> to create a <a href="https://eliocamp.github.io/tagger/articles/coverage-report.html" rel="nofollow" target="_blank">coverage report for a package</a>.</li>
</ul>
<h3>
AI as Forklift: Andrew Heiss’ R + AI 2026 keynote
</h3><p>Andrew Heiss published a write up of his talk <a href="https://www.andrewheiss.com/blog/2026/11/10/r-ai-keynote-friction/" rel="nofollow" target="_blank">Friction Worth Keeping: What Keeps Us Human When AI Makes Everything Easy</a>, including a useful extension of the AI/forklift analogy. You can also <a href="https://www.youtube.com/watch?v=efwMAosu2-g" rel="nofollow" target="_blank">watch the recording</a>.</p>
<h3>
LLMs as last resort
</h3><p><a href="https://ropensci.org/author/basti%C3%A1n-olea-herrera/" rel="nofollow" target="_blank">Bastián Olea Herrera</a> shared a post by Ben Harrap: <a href="https://benharrap.com/post/2026-09-08-limited-learning-mode/" rel="nofollow" target="_blank">“Limited Learning Mode: Why LLMs are my last resort”</a>. One of the reasons is “People like to help”!</p>
<h2>
Last words
</h2><p>Thanks for reading! If you want to get involved with rOpenSci, check out our <a href="https://contributing.ropensci.org/" rel="nofollow" target="_blank">Contributing Guide</a>. This guide will help direct you to the right place, whether you want to make code contributions, non-code contributions, or contribute in other ways such as through sharing use cases. You can also support our work through <a href="https://ropensci.org/donate" rel="nofollow" target="_blank">donations</a>.</p>
<p>If you haven’t subscribed to our newsletter yet, you can <a href="https://ropensci.org/news/" rel="nofollow" target="_blank">do so through our signup form</a>. Until it’s time for our next newsletter, you can keep in touch with us through our <a href="https://ropensci.org/" rel="nofollow" target="_blank">website</a>, <a href="https://hachyderm.io/@rOpenSci" rel="nofollow" target="_blank">Mastodon</a>, or <a href="https://www.linkedin.com/company/ropensci/" rel="nofollow" target="_blank">LinkedIn</a>. See you soon!</p>
<div style="border: 1px solid; background: none repeat scroll 0 0 #EDEDED; margin: 1px; font-size: 13px;">
<div style="text-align: center;">To <strong>leave a comment</strong> for the author, please follow the link and comment on their blog: <strong><a href="https://ropensci.org/blog/2026/11/26/news-november-2026/"> rOpenSci - open tools for open science</a></strong>.</div>
<hr />
<a href="https://www.r-bloggers.com/" rel="nofollow">R-bloggers.com</a> offers <strong><a href="https://feedburner.google.com/fb/a/mailverify?uri=RBloggers" rel="nofollow">daily e-mail updates</a></strong> about <a title="The R Project for Statistical Computing" href="https://www.r-project.org/" rel="nofollow">R</a> news and tutorials about <a title="R tutorials" href="https://www.r-bloggers.com/how-to-learn-r-2/" rel="nofollow">learning R</a> and many other topics. <a title="Data science jobs" href="https://www.r-users.com/" rel="nofollow">Click here if you're looking to post or find an R/data-science job</a>.

<hr>Want to share your content on R-bloggers?<a href="https://www.r-bloggers.com/add-your-blog/" rel="nofollow"> click here</a> if you have a blog, or <a href="http://r-posts.com/" rel="nofollow"> here</a> if you don't.
</div><strong>Continue reading</strong>: <a href="https://www.r-bloggers.com/2026/11/ropensci-news-digest-november-2026/">rOpenSci News Digest, November 2026</a>]]></content:encoded>
					
		
		<enclosure url="" length="0" type="" />

		<post-id xmlns="com-wordpress:feed-additions:1">405101</post-id>	</item>
		<item>
		<title>Survivor Stats DB: the companion site to {survivoR}</title>
		<link>https://www.r-bloggers.com/2026/11/survivor-stats-db-the-companion-site-to-survivor/</link>
		
		<dc:creator><![CDATA[Daniel Oehm]]></dc:creator>
		<pubDate>Wed, 25 Nov 2026 16:54:23 +0000</pubDate>
				<category><![CDATA[R bloggers]]></category>
		<guid isPermaLink="false">https://gradientdescending.com/?p=3555</guid>

					<description><![CDATA[<p>The {survivoR} package has been the go-to home for Survivor data in R. It has 5 versions, 76 seasons, 1,198 […]<br />
The post Survivor Stats DB: the companion site to {survivoR} appeared first on Dan Oehm &#124; Gradient Descending.</p>
<strong>Continue reading</strong>: <a href="https://www.r-bloggers.com/2026/11/survivor-stats-db-the-companion-site-to-survivor/">Survivor Stats DB: the companion site to {survivoR}</a>]]></description>
										<content:encoded><![CDATA[<!-- 
<div style="min-height: 30px;">
[social4i size="small" align="align-left"]
</div>
-->

<div style="border: 1px solid; background: none repeat scroll 0 0 #EDEDED; margin: 1px; font-size: 12px;">
[This article was first published on  <strong><a href="http://gradientdescending.com/survivor-stats-db-the-companion-site-to-survivor/"> R Archives - Dan Oehm | Gradient Descending</a></strong>, and kindly contributed to <a href="https://www.r-bloggers.com/" rel="nofollow">R-bloggers</a>].  (You can report issue about the content on this page <a href="https://www.r-bloggers.com/contact-us/">here</a>)
<hr>Want to share your content on R-bloggers?<a href="https://www.r-bloggers.com/add-your-blog/" rel="nofollow"> click here</a> if you have a blog, or <a href="http://r-posts.com/" rel="nofollow"> here</a> if you don't.
</div>
<a href="http://gradientdescending.com/survivor-stats-db-the-companion-site-to-survivor/" title="Survivor Stats DB: the companion site to {survivoR}" rel="nofollow" target="_blank"><img loading="lazy" src="https://i2.wp.com/gradientdescending.com/wp-content/uploads/2026/11/og-image-1024x538.jpg?w=450" class="webfeedsFeaturedVisual wp-post-image" alt="" style="display: block; margin: auto; margin-bottom: 5px;max-width: 100%;" link_thumbnail="1" decoding="async" srcset_temp="https://i2.wp.com/gradientdescending.com/wp-content/uploads/2026/11/og-image-1024x538.jpg?w=450 1024w, http://gradientdescending.com/wp-content/uploads/2026/11/og-image-300x158.jpg 300w, http://gradientdescending.com/wp-content/uploads/2026/11/og-image-768x403.jpg 768w, http://gradientdescending.com/wp-content/uploads/2026/11/og-image.jpg 1200w" sizes="(max-width: 1024px) 100vw, 1024px" data-recalc-dims="1" /></a>
<p class="wp-block-paragraph">The <a href="https://github.com/doehm/survivoR" rel="nofollow" target="_blank">{survivoR}</a> package has been the go-to home for Survivor data in R. It has 5 versions, 76 seasons, 1,198 castaways, and 21 datasets covering everything from vote history to confessional counts. But to get at all that, you’ve needed to fire up R, load the package, and do the wrangling yourself.</p>



<p class="wp-block-paragraph">But if you just want quick stats you can head to the <strong><a href="https://survivorstatsdb.com/" rel="nofollow" target="_blank">Survivor Stats DB</a></strong> — the companion site to {survivoR}. When {survivoR} is updated, Survivor Stats DB is updated. It’s had a massive overhaul and there are now more stats and they’re easier to explore.</p>



<p class="wp-block-paragraph"><strong><a href="https://survivorstatsdb.com/" rel="nofollow" target="_blank"><img src="https://i0.wp.com/s.w.org/images/core/emoji/17.0.2/72x72/1f449.png?w=578&#038;ssl=1" alt="&#x1f449;" class="wp-smiley" style="height: 1em; max-height: 1em;" data-recalc-dims="1" /> Take me to Survivor Stats DB</a></strong></p>



<h2 class="wp-block-heading">What you’ll find on the site</h2>



<p class="wp-block-paragraph">The site covers all the international versions in the package — Survivor US (all 50 seasons), Australian Survivor, Survivor South Africa, Survivor New Zealand, and Survivor UK. Here’s the tour:</p>



<ul class="wp-block-list">
<li><strong>Leaderboards</strong> — ranked pages for every stat category: overall scores, individual challenge wins, voting accuracy, jury performance, confessionals (and confessionals per hour), advantage finds and plays, season rank, and episode rank.</li>



<li><strong>Castaway scores</strong> — a composite model that scores every castaway on placement, immunity wins, voting, advantages, jury votes, edit prominence, and community polls, then rolls it all into a career total for returning players.</li>



<li><strong>Season pages</strong> — overview, episode timelines with viewer counts and IMDB ratings, full boot order, challenge history, tribe swaps and merges, model-generated winner predictions, and a season rating.</li>



<li><strong>Castaway profiles</strong> — both single-season stats (vote history, challenge performance, confessionals, immunity wins) and career aggregates across every season a player has appeared in.</li>



<li><strong>Castaways map</strong> — an interactive map showing where castaways come from around the world.</li>



<li><strong>Fun stuff</strong> — where you’ll find your Survivor twin, who’s birthday it is, head-to-head polls, a personality test, a chance to upload your all time top 10, and more.</li>



<li><strong>Articles &#038; analysis</strong> — long-form, data-driven pieces, including a look at edit bias in confessionals and a deep dive into Survivor’s viewership rise and fall across all 50 US seasons.</li>



<li><strong>Confessional app</strong> — a tool to help you count / time confessionals.</li>



<li><strong>Change log</strong> — so you can keep up with data refreshes and new features.</li>
</ul>



<p class="wp-block-paragraph">And if you’d rather grab the raw numbers, you can still <a href="https://survivorstatsdb.com/download" rel="nofollow" target="_blank">download everything as an xlsx</a> or pull the <a href="https://github.com/doehm/survivoR/tree/master/dev/json" rel="nofollow" target="_blank">JSON</a> straight into your own app.</p>



<h2 class="wp-block-heading">Check it out</h2>



<p class="wp-block-paragraph">Find your favourite player’s stats, or just fall down a rabbit hole for an hour. Have a browse, vote in a few polls, and let me know what you think.</p>



<p class="wp-block-paragraph"><strong><a href="https://survivorstatsdb.com/" rel="nofollow" target="_blank">Explore Survivor Stats DB →</a></strong></p>



<p class="wp-block-paragraph">And if you’re an R user who wants the data at your fingertips, the <a href="https://github.com/doehm/survivoR" rel="nofollow" target="_blank">{survivoR} package</a> is on CRAN and ready to go:</p>


<pre>
install.packages(&quot;survivoR&quot;)
</pre>


<p class="wp-block-paragraph">and Github</p>


<pre>
devtools::install_github(&quot;doehm/survivoR&quot;)
</pre>


<p class="wp-block-paragraph">Installing from Github will get you the weekly updates from in progress seasons. For those that want to dive deep into the data the package has a number of convenient functions which makes it easier to do.</p>



<h2 class="wp-block-heading">Found an incorrect stat?</h2>



<p class="wp-block-paragraph">Log an issue on <a href="https://github.com/doehm/survivoR/issues" rel="nofollow" target="_blank">Git </a>and I’ll correct it within 24 hrs.</p>
<p>The post <a href="http://gradientdescending.com/survivor-stats-db-the-companion-site-to-survivor/" rel="nofollow" target="_blank">Survivor Stats DB: the companion site to {survivoR}</a> appeared first on <a href="http://gradientdescending.com/" rel="nofollow" target="_blank">Dan Oehm | Gradient Descending</a>.</p>

<div style="border: 1px solid; background: none repeat scroll 0 0 #EDEDED; margin: 1px; font-size: 13px;">
<div style="text-align: center;">To <strong>leave a comment</strong> for the author, please follow the link and comment on their blog: <strong><a href="http://gradientdescending.com/survivor-stats-db-the-companion-site-to-survivor/"> R Archives - Dan Oehm | Gradient Descending</a></strong>.</div>
<hr />
<a href="https://www.r-bloggers.com/" rel="nofollow">R-bloggers.com</a> offers <strong><a href="https://feedburner.google.com/fb/a/mailverify?uri=RBloggers" rel="nofollow">daily e-mail updates</a></strong> about <a title="The R Project for Statistical Computing" href="https://www.r-project.org/" rel="nofollow">R</a> news and tutorials about <a title="R tutorials" href="https://www.r-bloggers.com/how-to-learn-r-2/" rel="nofollow">learning R</a> and many other topics. <a title="Data science jobs" href="https://www.r-users.com/" rel="nofollow">Click here if you're looking to post or find an R/data-science job</a>.

<hr>Want to share your content on R-bloggers?<a href="https://www.r-bloggers.com/add-your-blog/" rel="nofollow"> click here</a> if you have a blog, or <a href="http://r-posts.com/" rel="nofollow"> here</a> if you don't.
</div><strong>Continue reading</strong>: <a href="https://www.r-bloggers.com/2026/11/survivor-stats-db-the-companion-site-to-survivor/">Survivor Stats DB: the companion site to {survivoR}</a>]]></content:encoded>
					
		
		<enclosure url="" length="0" type="" />

		<post-id xmlns="com-wordpress:feed-additions:1">405095</post-id>	</item>
		<item>
		<title>Permutation tests in R: let your data build its own null distribution</title>
		<link>https://www.r-bloggers.com/2026/11/permutation-tests-in-r-let-your-data-build-its-own-null-distribution/</link>
		
		<dc:creator><![CDATA[R on Stats and R]]></dc:creator>
		<pubDate>Wed, 25 Nov 2026 00:00:00 +0000</pubDate>
				<category><![CDATA[R bloggers]]></category>
		<guid isPermaLink="false">https://statsandr.com/blog/permutation-tests-in-r/</guid>

					<description><![CDATA[<div style = "width:60%; display: inline-block; float:left; ">
<p>Introduction<br />
Example 1: two independent groups (PlantGrowth)<br />
A small simulation study<br />
The difference in medians<br />
Example 2: paired data (sleep)<br />
When to use permutation tests, and when not to<br />
Conclusion</p>
<p>Note: This post has been written in collabo...</p></div>
<div style = "width: 40%; display: inline-block; float:right;"></div>
<div style="clear: both;"></div>
<strong>Continue reading</strong>: <a href="https://www.r-bloggers.com/2026/11/permutation-tests-in-r-let-your-data-build-its-own-null-distribution/">Permutation tests in R: let your data build its own null distribution</a>]]></description>
										<content:encoded><![CDATA[<!-- 
<div style="min-height: 30px;">
[social4i size="small" align="align-left"]
</div>
-->

<div style="border: 1px solid; background: none repeat scroll 0 0 #EDEDED; margin: 1px; font-size: 12px;">
[This article was first published on  <strong><a href="https://statsandr.com/blog/permutation-tests-in-r/"> R on Stats and R</a></strong>, and kindly contributed to <a href="https://www.r-bloggers.com/" rel="nofollow">R-bloggers</a>].  (You can report issue about the content on this page <a href="https://www.r-bloggers.com/contact-us/">here</a>)
<hr>Want to share your content on R-bloggers?<a href="https://www.r-bloggers.com/add-your-blog/" rel="nofollow"> click here</a> if you have a blog, or <a href="http://r-posts.com/" rel="nofollow"> here</a> if you don't.
</div>


<div id="TOC">
<ul>
<li><a href="https://statsandr.com/blog/permutation-tests-in-r/#introduction" id="toc-introduction" rel="nofollow" target="_blank">Introduction</a></li>
<li><a href="https://statsandr.com/blog/permutation-tests-in-r/#example-1-two-independent-groups-plantgrowth" id="toc-example-1-two-independent-groups-plantgrowth" rel="nofollow" target="_blank">Example 1: two independent groups (PlantGrowth)</a></li>
<li><a href="https://statsandr.com/blog/permutation-tests-in-r/#a-small-simulation-study" id="toc-a-small-simulation-study" rel="nofollow" target="_blank">A small simulation study</a></li>
<li><a href="https://statsandr.com/blog/permutation-tests-in-r/#the-difference-in-medians" id="toc-the-difference-in-medians" rel="nofollow" target="_blank">The difference in medians</a></li>
<li><a href="https://statsandr.com/blog/permutation-tests-in-r/#example-2-paired-data-sleep" id="toc-example-2-paired-data-sleep" rel="nofollow" target="_blank">Example 2: paired data (sleep)</a></li>
<li><a href="https://statsandr.com/blog/permutation-tests-in-r/#when-to-use-permutation-tests-and-when-not-to" id="toc-when-to-use-permutation-tests-and-when-not-to" rel="nofollow" target="_blank">When to use permutation tests, and when not to</a></li>
<li><a href="https://statsandr.com/blog/permutation-tests-in-r/#conclusion" id="toc-conclusion" rel="nofollow" target="_blank">Conclusion</a></li>
</ul>
</div>

<p><img src="https://i1.wp.com/statsandr.com/blog/permutation-tests-in-r/images/permutation-tests-in-r.jpg?w=578&#038;ssl=1" style="width:100.0%" data-recalc-dims="1" /></p>
<p><em>Note: This post has been written in collaboration with Waqar Ahmad, founder of CalcMega.</em></p>
<div id="introduction" class="section level1">
<h1>Introduction</h1>
<p>Every R user meets the same small anxiety early on. You have two groups, you want to know whether they really differ, and the <a href="https://statsandr.com/blog/student-s-t-test-in-r-and-by-hand-how-to-compare-two-groups-under-different-scenarios/" rel="nofollow" target="_blank">t-test</a> relies on a normal-model reference distribution for small-sample inference. With 200 observations per group, that approximation is often robust. With 10 plants, it deserves scrutiny: a normality test on 10 points has little power to rule out departures, and the central limit theorem is no automatic guarantee.</p>
<p>Permutation tests avoid a normal reference distribution, but they do not remove the need for assumptions. They were worked out in the 1930s, in the early days of modern statistics (Fisher’s <em>The Design of Experiments</em> appeared in 1935), and the idea is disarmingly simple: <strong>if the treatment did nothing, then the group labels are arbitrary, and shuffling them changes nothing that matters.</strong></p>
<p>That last clause is the key assumption, and it has a name: <em>exchangeability</em>. In a randomized experiment, permuting assignments allowed by the design gives an exact test of the sharp null that treatment affects no individual. Without randomization, validity instead requires exchangeability under the null; equality of means alone is not enough when group distributions differ. A permutation test turns exchangeability into a recipe:</p>
<ol style="list-style-type: decimal">
<li>Compute your test statistic on the data as observed, say, the difference in group means.</li>
<li>Shuffle the group labels at random and recompute the statistic.</li>
<li>Repeat step 2 many times. The collection of shuffled statistics is the <em>permutation distribution</em>: what your statistic looks like when the labels mean nothing.</li>
<li>The p-value is the proportion of shuffles producing a statistic at least as extreme as the one you actually observed.</li>
</ol>
<p>No normal reference distribution is invoked. When the design or exchangeability assumptions hold, this can provide valid inference with small or skewed samples; small sample size does not make arbitrary shuffling safe, and it can limit power and p-value resolution. One clarification before we start, because it is the most common misunderstanding of the method: a permutation p-value is <em>not</em> “the probability that the null hypothesis is true.” It is the proportion of allowed rearrangements that produce a statistic at least as extreme as yours, a statement about how surprising your data would be under the specified null. That is the same careful interpretation a t-test’s <a href="https://statsandr.com/blog/hypothesis-test-by-hand/" rel="nofollow" target="_blank">p-value</a> demands; permutation tests replace a distributional assumption with design or exchangeability assumptions rather than removing assumptions.</p>
<p>In this article we work two complete examples: an independent two-sample test on the <code>PlantGrowth</code> dataset, and a paired test on the <code>sleep</code> dataset, where the shuffling turns into something even neater: flipping signs.</p>
</div>
<div id="example-1-two-independent-groups-plantgrowth" class="section level1">
<h1>Example 1: two independent groups (PlantGrowth)</h1>
<p><code>PlantGrowth</code> is one of R’s built-in datasets. Thirty plants were grown under three conditions, a control group and two treatments, and their dried weights recorded. We compare the control group against the first treatment, <code>trt1</code>, ten plants each.</p>
<p>The label shuffling below is design-exact only if these group assignments were randomized under the sharp no-effect null. Otherwise, it relies on the groups being exchangeable under the null; the <a href="https://stat.ethz.ch/R-manual/R-devel/library/datasets/html/PlantGrowth.html" rel="nofollow" target="_blank">built-in dataset description</a> does not specify the assignment procedure.</p>
<pre>data(PlantGrowth)

ctrl &lt;- PlantGrowth$weight[PlantGrowth$group == &quot;ctrl&quot;]
trt1 &lt;- PlantGrowth$weight[PlantGrowth$group == &quot;trt1&quot;]

length(ctrl)
## [1] 10
length(trt1)
## [1] 10
mean(ctrl)
## [1] 5.032
mean(trt1)
## [1] 4.661
sd(ctrl)
## [1] 0.5830914
sd(trt1)
## [1] 0.7936757</pre>
<p>The control plants average 5.032 grams against 4.661 for <code>trt1</code>. (If you would like to double-check the group means outside R, a <a href="https://calcmega.com/statistics-calculator" rel="nofollow" target="_blank">statistics calculator</a> confirms them in seconds.) Our test statistic is the difference in means, treated minus control:</p>
<pre>observed_diff &lt;- mean(trt1) - mean(ctrl)
observed_diff
## [1] -0.371</pre>
<p>The treated plants came out 0.371 grams <em>lighter</em> on average. Is that gap unusual under the exchangeable-label null? To find out, pool all 20 weights, shuffle the labels, and see what differences the null model generates. One shuffle, step by step:</p>
<pre>weights &lt;- c(ctrl, trt1)
labels &lt;- rep(c(&quot;ctrl&quot;, &quot;trt1&quot;), each = 10)

set.seed(1)
shuffled &lt;- sample(labels)
mean(weights[shuffled == &quot;trt1&quot;]) - mean(weights[shuffled == &quot;ctrl&quot;])
## [1] -0.349</pre>
<p>That shuffle produced a difference of -0.349, nearly as large as the gap we actually observed, from exactly the same 20 numbers with nothing changed but the labels. A single shuffle proves nothing, of course; it simply shows the mechanism. The evidence comes from doing it thousands of times and asking how often chance alone produces a gap like ours:</p>
<pre>set.seed(123)
n_perm &lt;- 9999

perm_diffs &lt;- replicate(n_perm, {
  shuffled &lt;- sample(labels)
  mean(weights[shuffled == &quot;trt1&quot;]) - mean(weights[shuffled == &quot;ctrl&quot;])
})

# install.packages(&quot;ggplot2&quot;)
library(ggplot2)

ggplot(data.frame(diff = perm_diffs), aes(x = diff)) +
  geom_histogram(bins = 40, fill = &quot;grey85&quot;, colour = &quot;white&quot;) +
  geom_vline(xintercept = observed_diff, colour = &quot;red&quot;, linewidth = 1) +
  labs(
    title = &quot;Permutation distribution of the difference in means&quot;,
    x = &quot;Difference in means (trt1 - ctrl) after shuffling labels&quot;,
    y = &quot;Frequency&quot;
  ) +
  theme_minimal()</pre>
<p><img src="https://i1.wp.com/statsandr.com/blog/permutation-tests-in-r/index_files/figure-html/unnamed-chunk-5-1.png?w=450&#038;ssl=1" alt="" style="display: block; margin: auto;" data-recalc-dims="1" /></p>
<p>The shuffled differences centre on zero under the exchangeable-label null, with most lying within about half a gram of zero. Our observed difference, marked in red, sits well inside that spread: noticeable, but not out in the tail where chance rarely ventures. The p-value counts how much of the distribution is at least as far from zero as what we saw, in either direction:</p>
<pre>p_perm &lt;- (sum(abs(perm_diffs) &gt;= abs(observed_diff) - 1e-10) + 1) / (n_perm + 1)
p_perm
## [1] 0.2513</pre>
<p>The <code>+ 1</code> in the numerator and denominator treats the observed arrangement as one additional member alongside the random shuffles. This standard Monte Carlo correction prevents a zero estimate. Here it barely matters. The permutation p-value is about 0.251, so differences this large turn up in roughly a quarter of the simulated shuffles. The data do not provide enough evidence to conclude that <code>trt1</code> changes the weight.</p>
<p>A word on how many shuffles are enough. A simulated p-value is itself an estimate, with Monte Carlo error attached: with 9,999 permutations and a true p-value near 0.25, its standard error is about <span class="math inline">\(\sqrt{0.25 \times 0.75 / 9999} \approx 0.0043\)</span>. Treat the last few thousandths as simulation noise, not as exact digits. If an estimate is close to a threshold you care about, 0.048 against a 0.05 cut-off, say, use more permutations (or enumerate exactly when feasible) and report the number of permutations; do not overinterpret a decision when the Monte Carlo uncertainty spans the cutoff.</p>
<p>Because 20 plants split into two groups of 10 in only <span class="math inline">\(\binom{20}{10}\)</span> = 184,756 ways, we can even skip the simulation and enumerate <em>every</em> split:</p>
<pre>combos &lt;- combn(20, 10)

exact_diffs &lt;- apply(combos, 2, function(idx) {
  mean(weights[idx]) - mean(weights[-idx])
})
# the tiny tolerance catches splits that tie with the observed difference
# but land a hair below it through floating-point rounding
p_exact &lt;- mean(abs(exact_diffs) &gt;= abs(observed_diff) - 1e-10)
p_exact
## [1] 0.247927</pre>
<p>The exact p-value, 0.248, matches the simulated one to two decimal places, a good reminder that 9,999 shuffles already pin the answer down tightly.</p>
<p>One more cross-check, this time against a packaged implementation. The <code>coin</code> package runs permutation tests of exactly this kind, so its answer on the same two groups should land in the same place as our hand-rolled shuffle:</p>
<pre># install.packages(&quot;coin&quot;)
library(coin)

set.seed(123)
pg2 &lt;- droplevels(PlantGrowth[PlantGrowth$group != &quot;trt2&quot;, ])

coin_test &lt;- oneway_test(weight ~ group,
  data = pg2,
  distribution = approximate(nresample = 9999)
)

coin_test
## 
## 	Approximative Two-Sample Fisher-Pitman Permutation Test
## 
## data:  weight by group (ctrl, trt1)
## Z = 1.1783, p-value = 0.2449
## alternative hypothesis: true mu is not equal to 0</pre>
<p>It does: the packaged p-value, 0.245, agrees with our exact 0.248 to within simulation noise, which is reassuring about both.</p>
<p>How does the classical test compare?</p>
<pre>welch &lt;- t.test(trt1, ctrl)
welch
## 
## 	Welch Two Sample t-test
## 
## data:  trt1 and ctrl
## t = -1.1913, df = 16.524, p-value = 0.2504
## alternative hypothesis: true difference in means is not equal to 0
## 95 percent confidence interval:
##  -1.0295162  0.2875162
## sample estimates:
## mean of x mean of y 
##     4.661     5.032</pre>
<p>The Welch t-test gives a p-value of about 0.25, close to the permutation results here. The two methods rely on different conditions: Welch’s test uses an approximate t reference distribution and allows unequal variances, while the unstudentized permutation test shown here relies on exchangeability. Neither test is automatically more trustworthy when they disagree. In particular, both tests based on means can be sensitive to outliers, and a raw permutation test need not be valid for a null hypothesis of equal means alone when variances differ. The next section compares their behaviour in several specific scenarios.</p>
</div>
<div id="a-small-simulation-study" class="section level1">
<h1>A small simulation study</h1>
<p>Claims about which test to trust are usually traded as folklore. They do not have to be: a simulation can put both tests in situations where the truth is known, because we generated the data ourselves. Here is a small one. Each scenario below generates 10,000 datasets; on every dataset, Welch’s t-test and a permutation test on the difference in means (999 shuffles, the same recipe as Example 1) each get one attempt, and we count how often each rejects at the 5% level. The permutation p-value is itself estimated from those 999 shuffles, so the results describe this Monte Carlo implementation rather than an exact permutation test.</p>
<pre>perm_p &lt;- function(x, y, B = 999) {
  pooled &lt;- c(x, y)
  n1 &lt;- length(x)
  N &lt;- length(pooled)
  total &lt;- sum(pooled)
  obs &lt;- mean(y) - mean(x)
  shuffles &lt;- replicate(B, sample(pooled))
  s1 &lt;- colSums(shuffles[seq_len(n1), , drop = FALSE])
  diffs &lt;- (total - s1) / (N - n1) - s1 / n1
  (sum(abs(diffs) &gt;= abs(obs) - 1e-10) + 1) / (B + 1)
}

run_scenario &lt;- function(gen, n_sim = 10000) {
  hits_perm &lt;- 0
  hits_welch &lt;- 0
  for (i in seq_len(n_sim)) {
    d &lt;- gen()
    if (perm_p(d$x, d$y) &lt; 0.05) hits_perm &lt;- hits_perm + 1
    if (t.test(d$x, d$y)$p.value &lt; 0.05) hits_welch &lt;- hits_welch + 1
  }
  c(permutation = hits_perm / n_sim, welch = hits_welch / n_sim)
}</pre>
<p><strong>Scenario 1: no difference, skewed data.</strong> Both groups are drawn from the same lognormal distribution, a right-skewed shape seen in incomes, weights and waiting times, with 10 observations each. The null hypothesis is true, so a well-behaved test should reject close to 5% of the time.</p>
<pre>set.seed(20261118)

gen_same &lt;- function() {
  list(
    x = rlnorm(10, meanlog = 0, sdlog = 1),
    y = rlnorm(10, meanlog = 0, sdlog = 1)
  )
}

sim_same &lt;- run_scenario(gen_same)
sim_same
## permutation       welch 
##      0.0508      0.0272</pre>
<p><strong>Scenario 2: a real difference.</strong> The same skewed distribution, but the second group is shifted up by 1.5. Now we count power: how often each test finds a difference that is really there.</p>
<pre>set.seed(20261119)

gen_shift &lt;- function() {
  list(
    x = rlnorm(10, meanlog = 0, sdlog = 1),
    y = rlnorm(10, meanlog = 0, sdlog = 1) + 1.5
  )
}

sim_shift &lt;- run_scenario(gen_shift)
sim_shift
## permutation       welch 
##      0.5654      0.5221</pre>
<p><strong>Scenario 3: no difference in means, but unequal spreads and sizes.</strong> This is the case the end of Example 1 warned about. To isolate it, the skew goes away: both groups are normal with the same mean of zero, but the small group (10 observations) has standard deviation 2 and the large group (30 observations) has standard deviation 1. The means are identical. Welch’s test is designed to maintain its level in this setting, but the raw permutation test need not: the labels carry information about spread, even though they carry none about location.</p>
<pre>set.seed(20261120)

gen_unequal &lt;- function() {
  list(
    x = rnorm(10, mean = 0, sd = 2),
    y = rnorm(30, mean = 0, sd = 1)
  )
}

sim_unequal &lt;- run_scenario(gen_unequal)
sim_unequal
## permutation       welch 
##      0.1536      0.0507
sim_table &lt;- data.frame(
  scenario = c(
    &quot;1. No difference, skewed, 10 vs 10&quot;,
    &quot;2. Real shift of 1.5, skewed, 10 vs 10&quot;,
    &quot;3. No mean difference, sd 2 vs 1, 10 vs 30&quot;
  ),
  permutation = c(
    sim_same[[&quot;permutation&quot;]], sim_shift[[&quot;permutation&quot;]],
    sim_unequal[[&quot;permutation&quot;]]
  ),
  welch = c(
    sim_same[[&quot;welch&quot;]], sim_shift[[&quot;welch&quot;]],
    sim_unequal[[&quot;welch&quot;]]
  )
)

knitr::kable(sim_table,
  digits = 3,
  col.names = c(&quot;Scenario&quot;, &quot;Permutation&quot;, &quot;Welch&quot;)
)</pre>
<table>
<thead>
<tr class="header">
<th align="left">Scenario</th>
<th align="right">Permutation</th>
<th align="right">Welch</th>
</tr>
</thead>
<tbody>
<tr class="odd">
<td align="left">1. No difference, skewed, 10 vs 10</td>
<td align="right">0.051</td>
<td align="right">0.027</td>
</tr>
<tr class="even">
<td align="left">2. Real shift of 1.5, skewed, 10 vs 10</td>
<td align="right">0.565</td>
<td align="right">0.522</td>
</tr>
<tr class="odd">
<td align="left">3. No mean difference, sd 2 vs 1, 10 vs 30</td>
<td align="right">0.154</td>
<td align="right">0.051</td>
</tr>
</tbody>
</table>
<p>These rejection rates are estimates. With 10,000 simulated datasets, the Monte Carlo standard error of a rate <span class="math inline">\(\hat p\)</span> is approximately <span class="math inline">\(\sqrt{\hat p(1-\hat p)/10000}\)</span>; near 5%, that is about 0.22 percentage points. Differences of only a few tenths of a percentage point should not be overread.</p>
<p>Read the table from the top. In scenario 1 the permutation test rejects in 5.1% of runs, close to its nominal level and consistent with exchangeability under the common lognormal distribution. Welch’s test rejects in 2.7% of runs, showing conservatism in this particular small-sample, skewed setting. In scenario 2, the estimated power for the chosen shift of 1.5 is 56.5% for the permutation test and 52.2% for Welch’s test. These are scenario-specific estimates; the lower null rejection rate in scenario 1 does not by itself explain or predict the power difference.</p>
<p>Scenario 3 is the reversal. The raw permutation test rejects a true equal-means null in 15.4% of runs, while Welch rejects in 5.1%. Shuffling pools the two spreads, making the null distribution of the unstudentized difference narrower than its sampling distribution under these unequal variances and group sizes; the observed differences therefore look too extreme. Welch estimates each group’s variance separately and adjusts for the unequal sizes. In this simulation it stays close to 5%, but that result is specific to these normal populations and sample sizes.</p>
<p>Taken together, the scenarios show why neither method is universally preferable. Under the common-distribution null in scenario 1, the permutation test is calibrated by exchangeability; in scenario 3, the same unstudentized test is liberal for an equal-means null with unequal variances and sizes. For that latter setting, Welch or a studentized permutation procedure is preferable to the raw shuffle used here.</p>
</div>
<div id="the-difference-in-medians" class="section level1">
<h1>The difference in medians</h1>
<p>Every test so far has shuffled one statistic: the difference in means. Nothing in the recipe ties it to means. Go back to the PlantGrowth weights and swap in a different statistic: the difference in medians, treated minus control, exactly as before:</p>
<pre>obs_med &lt;- median(trt1) - median(ctrl)
obs_med
## [1] -0.605
set.seed(123)

perm_meds &lt;- replicate(n_perm, {
  shuffled &lt;- sample(labels)
  median(weights[shuffled == &quot;trt1&quot;]) - median(weights[shuffled == &quot;ctrl&quot;])
})

p_med &lt;- (sum(abs(perm_meds) &gt;= abs(obs_med) - 1e-10) + 1) / (n_perm + 1)
p_med
## [1] 0.1168</pre>
<p>The observed difference in medians is -0.605 grams, further from zero than the difference in means, because a median ignores how far the heaviest and lightest plants sit from the middle of their group. Its permutation p-value is 0.117, so this statistic lands further into the simulated tail than the difference in means, without crossing the 5% line. The two statistics are answering slightly different questions about the same twenty plants, so they are under no obligation to agree exactly.</p>
<p>Two things are worth noticing. The machinery did not change at all: the same pooled weights, the same shuffles, the same counting; only the statistic moved. And the question changed with it. A difference in medians describes whether the typical plant in one group outweighs the typical plant in the other, and it is less affected by extreme values than a difference in means. With ten plants per group it is also a coarser instrument: the median of ten values is the average of the middle two, so the shuffled differences take relatively few distinct values and ties are common. This permutation calibration is exact under exchangeability; it does not, in general, test equality of population medians alone when the group distributions otherwise differ. Choose a statistic that matches the question you want answered, and check that the permutation null matches it too.</p>
</div>
<div id="example-2-paired-data-sleep" class="section level1">
<h1>Example 2: paired data (sleep)</h1>
<p>The second classic dataset is smaller and stranger. <code>sleep</code> records the effect of two soporific drugs on 10 patients: each patient has an observation under both drugs, and <code>extra</code> is the increase in hours of sleep over control. Because the same patient appears in both groups, the observations come in pairs, and pairing changes the permutation logic completely.</p>
<pre>data(sleep)
head(sleep)
##   extra group ID
## 1   0.7     1  1
## 2  -1.6     1  2
## 3  -0.2     1  3
## 4  -1.2     1  4
## 5  -0.1     1  5
## 6   3.4     1  6
sleep_wide &lt;- reshape(sleep,
  idvar = &quot;ID&quot;, timevar = &quot;group&quot;,
  direction = &quot;wide&quot;
)</pre>
<p>The right way to look at paired data is through the within-patient differences, drug 2 minus drug 1:</p>
<pre>d &lt;- sleep_wide$extra.2 - sleep_wide$extra.1
d
##  [1] 1.2 2.4 1.3 1.3 0.0 1.0 1.8 0.8 4.6 1.4
mean(d)
## [1] 1.58</pre>
<p>Drug 2 had 1.58 more extra hours of sleep on average in this sample. A sign-flip test needs its own justification: if drug order was randomized within each patient, under the sharp no-effect null the two labels could be swapped with equal probability. Otherwise, the test requires the paired differences to be symmetric around zero under the null. The <a href="https://stat.ethz.ch/R-manual/R-devel/library/datasets/html/sleep.html" rel="nofollow" target="_blank"><code>sleep</code> dataset documentation</a> confirms repeated measurements on the same patients but does not state that drug order was randomized, so we use sign symmetry as the working assumption here. Instead of shuffling labels between patients, we <strong>flip the signs of the differences at random</strong>, keeping each patient’s pair intact. One random flip:</p>
<pre>set.seed(2)
d * sample(c(-1, 1), size = length(d), replace = TRUE)
##  [1] -1.2 -2.4  1.3  1.3  0.0  1.0 -1.8 -0.8 -4.6  1.4</pre>
<p>With 10 patients there are <span class="math inline">\(2^{10}\)</span> = 1,024 possible sign combinations, few enough to enumerate completely without simulation:</p>
<pre>signs &lt;- expand.grid(rep(list(c(-1, 1)), length(d)))
all_sums &lt;- apply(signs, 1, function(s) sum(s * d))

observed_sum &lt;- sum(d)
# the same small tolerance as in Example 1, so that a sum which ties with
# the observed one is not lost to floating-point rounding
n_extreme &lt;- sum(abs(all_sums) &gt;= abs(observed_sum) - 1e-10)
p_paired_exact &lt;- n_extreme / length(all_sums)
p_paired_exact
## [1] 0.00390625
n_extreme
## [1] 4</pre>
<p>The observed sum of differences is 15.8. Of all 1,024 sign combinations, only 4 produce a sum at least that extreme in absolute value. The p-value is exactly 4/1024, about 0.0039. This is evidence against the sign-symmetry null (or, with randomized order, the sharp no-effect null); it is not an exact test of a zero mean alone without those conditions. One detail is worth noticing: patient 5’s difference is exactly 0, and flipping the sign of zero changes nothing, so every distinct sum in this enumeration appears twice. Zero differences carry no information about which drug is better; some implementations drop them before testing (leaving <span class="math inline">\(2^9\)</span> combinations here), which is defensible, but keeping them, as above, is exact and simpler to explain.</p>
<p>A picture, and then the simulation version for comparison:</p>
<pre>ggplot(data.frame(sum = all_sums), aes(x = sum)) +
  geom_histogram(bins = 40, fill = &quot;grey85&quot;, colour = &quot;white&quot;) +
  geom_vline(
    xintercept = c(-observed_sum, observed_sum),
    colour = &quot;red&quot;, linewidth = 1
  ) +
  labs(
    title = &quot;Exact permutation distribution of signed differences&quot;,
    x = &quot;Sum of differences after sign-flipping&quot;,
    y = &quot;Frequency&quot;
  ) +
  theme_minimal()</pre>
<p><img src="https://i0.wp.com/statsandr.com/blog/permutation-tests-in-r/index_files/figure-html/unnamed-chunk-20-1.png?w=450&#038;ssl=1" alt="" style="display: block; margin: auto;" data-recalc-dims="1" /></p>
<pre>set.seed(123)

n_perm &lt;- 9999
perm_sums &lt;- replicate(n_perm, sum(d * sample(c(-1, 1), length(d), replace = TRUE)))

p_paired_sim &lt;- (sum(abs(perm_sums) &gt;= abs(observed_sum) - 1e-10) + 1) / (n_perm + 1)
p_paired_sim
## [1] 0.0043</pre>
<p>The simulation lands at about 0.0043, right next to the exact 0.0039, as it should, since it is sampling from the very distribution we enumerated. And the <a href="https://statsandr.com/blog/student-s-t-test-in-r-and-by-hand-how-to-compare-two-groups-under-different-scenarios/" rel="nofollow" target="_blank">paired t-test</a>?</p>
<pre>paired_tt &lt;- t.test(sleep_wide$extra.2, sleep_wide$extra.1,
  paired = TRUE
)

paired_tt
## 
## 	Paired t-test
## 
## data:  sleep_wide$extra.2 and sleep_wide$extra.1
## t = 4.0621, df = 9, p-value = 0.002833
## alternative hypothesis: true mean difference is not equal to 0
## 95 percent confidence interval:
##  0.7001142 2.4598858
## sample estimates:
## mean difference 
##            1.58</pre>
<p>The paired t-test estimates a mean difference of 1.58 hours and gives a p-value of about 0.0028. Its small-sample reference is exact if the paired differences are independent and normally distributed; with only 10 patients, that assumption is difficult to assess. Both procedures point to a positive difference here, but the paired t-test tests a zero mean under its model, whereas the sign-flip test uses the symmetry or randomization null described above. Patient-to-patient variability is removed by taking within-patient differences, and both analyses preserve that pairing.</p>
</div>
<div id="when-to-use-permutation-tests-and-when-not-to" class="section level1">
<h1>When to use permutation tests, and when not to</h1>
<p>Permutation tests earn their place when:</p>
<ul>
<li><strong>The sample is small and normality is uncertain.</strong> Permutation methods avoid a normal reference distribution, but small sample size alone does not make a shuffle valid and can limit power and p-value resolution.</li>
<li><strong>The data are skewed or heavy-tailed</strong>, and a normal reference distribution is questionable. Exchangeability can still justify permutation calibration without normality; choose a statistic that answers the question of interest. For ordinal data, a rank-based test such as the <a href="https://statsandr.com/blog/wilcoxon-test-in-r-how-to-compare-2-groups-under-the-non-normality-assumption/" rel="nofollow" target="_blank">Wilcoxon test</a> may be more appropriate, but it does not necessarily test the same hypothesis as a test of means.</li>
<li><strong>Your statistic has no convenient classical test.</strong> You can permute a difference in medians, a trimmed mean, a ratio, or another summary, but the statistic must be paired with a defensible assignment or exchangeability null.</li>
<li><strong>The data come from a randomized experiment.</strong> Permuting assignments allowed by the design gives an exact test under the sharp null of no treatment effect on any unit.</li>
</ul>
<p>And their limits deserve equal honesty:</p>
<ul>
<li><strong>Exchangeability is an assumption, not a magic word.</strong> If observations are dependent, as with repeated measures shuffled as if independent, clustered data or time series, naive shuffling breaks the structure and invalidates the reference distribution. Preserve the design (for example, flip signs within pairs only when justified), or use a different method.</li>
<li><strong>Permutation does not cure confounding.</strong> In observational data, unrestricted label shuffling is generally not justified unless exchangeability under the null is defensible, possibly conditional on covariates. Even a valid test of association does not establish that the grouping <em>caused</em> the outcome.</li>
<li><strong>A raw permutation test on means is not generally an exact test of equal means alone.</strong> Its usual finite-sample justification is exchangeability (or a sharp randomization null). If spreads differ, especially with unbalanced group sizes, a significant result may reflect differences beyond the means; a studentized procedure or Welch’s test may be more suitable.</li>
<li><strong>Tiny samples have a floor.</strong> For a two-sided sign-flip test with <span class="math inline">\(n\)</span> pairs, the theoretical minimum is <span class="math inline">\(2/2^n\)</span>, reached only when the two extreme sign patterns are the only ones as extreme as observed; ties or zero differences can make the minimum larger. With 10 pairs the floor is 2/1024 ≈ 0.00195. With 5 pairs it is 2/32 = 0.0625, so a p-value below 0.05 is impossible. Know the resolution before you start.</li>
<li><strong>Huge enumerations need simulation.</strong> When exact enumeration is impractical, sample 9,999 or 99,999 shuffles, use the (+1)/(B+1) correction, and report the number of shuffles and Monte Carlo uncertainty. Set a seed for reproducibility within the same random-number-generator setup.</li>
</ul>
</div>
<div id="conclusion" class="section level1">
<h1>Conclusion</h1>
<p>A permutation test builds a null reference from the assignments or sign changes justified by the design or exchangeability assumptions, then asks where the observed statistic falls inside it. On <code>PlantGrowth</code> it agreed with Welch’s t-test; the data do not provide enough evidence to conclude that <code>trt1</code> changed the weight, but that is not evidence that the effect is zero. On <code>sleep</code>, the exact sign-flip calculation found only four of 1,024 assignments as extreme as the one observed. This is evidence against the sign-symmetry null (or a randomized sharp no-effect null), not an exact test of zero mean alone. Both examples set seeds for their Monte Carlo steps; results are reproducible with the same R and random-number-generator setup. For a new dataset, first check whether the design and null justify the shuffle, then choose a statistic that answers the scientific question.</p>
<p>As always, if you have a question or a suggestion related to the topic covered in this article, please add it as a comment so other readers can benefit from the discussion.</p>
</div>

<div style="border: 1px solid; background: none repeat scroll 0 0 #EDEDED; margin: 1px; font-size: 13px;">
<div style="text-align: center;">To <strong>leave a comment</strong> for the author, please follow the link and comment on their blog: <strong><a href="https://statsandr.com/blog/permutation-tests-in-r/"> R on Stats and R</a></strong>.</div>
<hr />
<a href="https://www.r-bloggers.com/" rel="nofollow">R-bloggers.com</a> offers <strong><a href="https://feedburner.google.com/fb/a/mailverify?uri=RBloggers" rel="nofollow">daily e-mail updates</a></strong> about <a title="The R Project for Statistical Computing" href="https://www.r-project.org/" rel="nofollow">R</a> news and tutorials about <a title="R tutorials" href="https://www.r-bloggers.com/how-to-learn-r-2/" rel="nofollow">learning R</a> and many other topics. <a title="Data science jobs" href="https://www.r-users.com/" rel="nofollow">Click here if you're looking to post or find an R/data-science job</a>.

<hr>Want to share your content on R-bloggers?<a href="https://www.r-bloggers.com/add-your-blog/" rel="nofollow"> click here</a> if you have a blog, or <a href="http://r-posts.com/" rel="nofollow"> here</a> if you don't.
</div><strong>Continue reading</strong>: <a href="https://www.r-bloggers.com/2026/11/permutation-tests-in-r-let-your-data-build-its-own-null-distribution/">Permutation tests in R: let your data build its own null distribution</a>]]></content:encoded>
					
		
		<enclosure url="" length="0" type="" />

		<post-id xmlns="com-wordpress:feed-additions:1">405093</post-id>	</item>
		<item>
		<title>Is the Glass Half Filled or Almost Empty?</title>
		<link>https://www.r-bloggers.com/2026/11/is-the-glass-half-filled-or-almost-empty/</link>
		
		<dc:creator><![CDATA[Ilya Kashnitsky]]></dc:creator>
		<pubDate>Tue, 24 Nov 2026 23:00:00 +0000</pubDate>
				<category><![CDATA[R bloggers]]></category>
		<guid isPermaLink="false">https://ikashnitsky.phd/2026/half-empty/</guid>

					<description><![CDATA[<div style = "width:60%; display: inline-block; float:left; "> Today I saw a fascinating dataviz (mis)interpretation case that featured a plot from a recent Stripe data analysis that claims that agentic commerce is on the rise and is very “sticky”.<br />
A very compelling story, supported by a nice upward facing line… At least that’s the first impression. ...</div>
<div style = "width: 40%; display: inline-block; float:right;"></div>
<div style="clear: both;"></div>
<strong>Continue reading</strong>: <a href="https://www.r-bloggers.com/2026/11/is-the-glass-half-filled-or-almost-empty/">Is the Glass Half Filled or Almost Empty?</a>]]></description>
										<content:encoded><![CDATA[<!-- 
<div style="min-height: 30px;">
[social4i size="small" align="align-left"]
</div>
-->

<div style="border: 1px solid; background: none repeat scroll 0 0 #EDEDED; margin: 1px; font-size: 12px;">
[This article was first published on  <strong><a href="https://ikashnitsky.phd/2026/half-empty/"> Ilya Kashnitsky</a></strong>, and kindly contributed to <a href="https://www.r-bloggers.com/" rel="nofollow">R-bloggers</a>].  (You can report issue about the content on this page <a href="https://www.r-bloggers.com/contact-us/">here</a>)
<hr>Want to share your content on R-bloggers?<a href="https://www.r-bloggers.com/add-your-blog/" rel="nofollow"> click here</a> if you have a blog, or <a href="http://r-posts.com/" rel="nofollow"> here</a> if you don't.
</div>
 <p>Today I saw a <a href="https://lnkd.in/p/e7xdAvba" rel="nofollow" target="_blank">fascinating dataviz (mis)interpretation case</a> that featured a plot from a recent <a href="https://substack.com/@ernietedeschi/note/c-392796478" rel="nofollow" target="_blank">Stripe data analysis</a> that claims that agentic commerce is on the rise and is very “sticky”.</p>
<p>A very compelling story, supported by a nice upward facing line… At least that’s the first impression. We are apparently seeing an emerging success story for AI-driven commerce.</p>
<p><img src="https://i2.wp.com/ikashnitsky.phd/2026/half-empty/stripe-plot.jpg?w=578&#038;ssl=1" class="img-fluid" data-recalc-dims="1"></p>
<p>Among customers who made one purchase, 56% made a second. Among those who reached nine purchases, 78% went on to make a tenth. The curve climbs steadily from 56% to 78%, subtly nudging the reader toward the impression that customer retention strengthens as people get hooked on agentic shopping.</p>
<p>Except…Those who ever saw markovian processes immediately spot the issue here. A very common example of such a process is is a sequence of <strong>birth parity progression probabilities</strong>, the metric demographers use to measure the proportion of women with a specific number children who go on to have the next one.</p>
<p>Plotting conditional probabilities creates a classic selection illusion because the reader (being just a human) cannot immediately see how each successive step along the probability line is shrinking the pool of the remaining people who are subject to experiencing the next transition probability.</p>
<p>How can we better represent the data? One way is to turn it into a survival curve showing explicitly the process of dropping out of the initial pool.</p>
<p>Let’s run the numbers in R:</p>
<div class="cell">
<pre>library(tidyverse)
library(gt)

df_survival &lt;- tibble(
  order = 1:10,
  p_continue = c(0.56, 0.63, 0.67, 0.70, 0.73, 0.74, 0.75, 0.77, 0.78, NA)
) |&gt;
  mutate(
    survival = lag(cumprod(p_continue), default = 1),
    drop_off = survival - lead(survival)
  )


df_survival |&gt;
  gt::gt() |&gt;
  gt::fmt_percent(columns = c(p_continue, survival, drop_off), decimals = 1) |&gt;
  gt::sub_missing(missing_text = &quot;—&quot;) |&gt;
  gt::cols_label(
    order = &quot;Order&quot;,
    p_continue = &quot;Conditional P(next)&quot;,
    survival = &quot;Cohort surviving&quot;,
    drop_off = &quot;Drop-off&quot;
  )</pre>
<div class="cell-output-display">
<div id="qkzkkoeiqi" style="padding-left:0px;padding-right:0px;padding-top:10px;padding-bottom:10px;overflow-x:auto;overflow-y:auto;width:auto;height:auto;">
<style>#qkzkkoeiqi table {
  font-family: system-ui, 'Segoe UI', Roboto, Helvetica, Arial, sans-serif, 'Apple Color Emoji', 'Segoe UI Emoji', 'Segoe UI Symbol', 'Noto Color Emoji';
  -webkit-font-smoothing: antialiased;
  -moz-osx-font-smoothing: grayscale;
}

#qkzkkoeiqi thead, #qkzkkoeiqi tbody, #qkzkkoeiqi tfoot, #qkzkkoeiqi tr, #qkzkkoeiqi td, #qkzkkoeiqi th {
  border-style: none;
}

#qkzkkoeiqi p {
  margin: 0;
  padding: 0;
}

#qkzkkoeiqi .gt_table {
  display: table;
  border-collapse: collapse;
  line-height: normal;
  margin-left: auto;
  margin-right: auto;
  color: #333333;
  font-size: 16px;
  font-weight: normal;
  font-style: normal;
  background-color: #FFFFFF;
  width: auto;
  border-top-style: solid;
  border-top-width: 2px;
  border-top-color: #A8A8A8;
  border-right-style: none;
  border-right-width: 2px;
  border-right-color: #D3D3D3;
  border-bottom-style: solid;
  border-bottom-width: 2px;
  border-bottom-color: #A8A8A8;
  border-left-style: none;
  border-left-width: 2px;
  border-left-color: #D3D3D3;
}

#qkzkkoeiqi .gt_caption {
  padding-top: 4px;
  padding-bottom: 4px;
}

#qkzkkoeiqi .gt_title {
  color: #333333;
  font-size: 125%;
  font-weight: initial;
  padding-top: 4px;
  padding-bottom: 4px;
  padding-left: 5px;
  padding-right: 5px;
  border-bottom-color: #FFFFFF;
  border-bottom-width: 0;
}

#qkzkkoeiqi .gt_subtitle {
  color: #333333;
  font-size: 85%;
  font-weight: initial;
  padding-top: 3px;
  padding-bottom: 5px;
  padding-left: 5px;
  padding-right: 5px;
  border-top-color: #FFFFFF;
  border-top-width: 0;
}

#qkzkkoeiqi .gt_heading {
  background-color: #FFFFFF;
  text-align: center;
  border-bottom-color: #FFFFFF;
  border-left-style: none;
  border-left-width: 1px;
  border-left-color: #D3D3D3;
  border-right-style: none;
  border-right-width: 1px;
  border-right-color: #D3D3D3;
}

#qkzkkoeiqi .gt_bottom_border {
  border-bottom-style: solid;
  border-bottom-width: 2px;
  border-bottom-color: #D3D3D3;
}

#qkzkkoeiqi .gt_col_headings {
  border-top-style: solid;
  border-top-width: 2px;
  border-top-color: #D3D3D3;
  border-bottom-style: solid;
  border-bottom-width: 2px;
  border-bottom-color: #D3D3D3;
  border-left-style: none;
  border-left-width: 1px;
  border-left-color: #D3D3D3;
  border-right-style: none;
  border-right-width: 1px;
  border-right-color: #D3D3D3;
}

#qkzkkoeiqi .gt_col_heading {
  color: #333333;
  background-color: #FFFFFF;
  font-size: 100%;
  font-weight: normal;
  text-transform: inherit;
  border-left-style: none;
  border-left-width: 1px;
  border-left-color: #D3D3D3;
  border-right-style: none;
  border-right-width: 1px;
  border-right-color: #D3D3D3;
  vertical-align: bottom;
  padding-top: 5px;
  padding-bottom: 6px;
  padding-left: 5px;
  padding-right: 5px;
  overflow-x: hidden;
}

#qkzkkoeiqi .gt_column_spanner_outer {
  color: #333333;
  background-color: #FFFFFF;
  font-size: 100%;
  font-weight: normal;
  text-transform: inherit;
  padding-top: 0;
  padding-bottom: 0;
  padding-left: 4px;
  padding-right: 4px;
}

#qkzkkoeiqi .gt_column_spanner_outer:first-child {
  padding-left: 0;
}

#qkzkkoeiqi .gt_column_spanner_outer:last-child {
  padding-right: 0;
}

#qkzkkoeiqi .gt_column_spanner {
  border-bottom-style: solid;
  border-bottom-width: 2px;
  border-bottom-color: #D3D3D3;
  vertical-align: bottom;
  padding-top: 5px;
  padding-bottom: 5px;
  overflow-x: hidden;
  display: inline-block;
  width: 100%;
}

#qkzkkoeiqi .gt_spanner_row {
  border-bottom-style: hidden;
}

#qkzkkoeiqi .gt_group_heading {
  padding-top: 8px;
  padding-bottom: 8px;
  padding-left: 5px;
  padding-right: 5px;
  color: #333333;
  background-color: #FFFFFF;
  font-size: 100%;
  font-weight: initial;
  text-transform: inherit;
  border-top-style: solid;
  border-top-width: 2px;
  border-top-color: #D3D3D3;
  border-bottom-style: solid;
  border-bottom-width: 2px;
  border-bottom-color: #D3D3D3;
  border-left-style: none;
  border-left-width: 1px;
  border-left-color: #D3D3D3;
  border-right-style: none;
  border-right-width: 1px;
  border-right-color: #D3D3D3;
  vertical-align: middle;
  text-align: left;
}

#qkzkkoeiqi .gt_empty_group_heading {
  padding: 0.5px;
  color: #333333;
  background-color: #FFFFFF;
  font-size: 100%;
  font-weight: initial;
  border-top-style: solid;
  border-top-width: 2px;
  border-top-color: #D3D3D3;
  border-bottom-style: solid;
  border-bottom-width: 2px;
  border-bottom-color: #D3D3D3;
  vertical-align: middle;
}

#qkzkkoeiqi .gt_from_md > :first-child {
  margin-top: 0;
}

#qkzkkoeiqi .gt_from_md > :last-child {
  margin-bottom: 0;
}

#qkzkkoeiqi .gt_row {
  padding-top: 8px;
  padding-bottom: 8px;
  padding-left: 5px;
  padding-right: 5px;
  margin: 10px;
  border-top-style: solid;
  border-top-width: 1px;
  border-top-color: #D3D3D3;
  border-left-style: none;
  border-left-width: 1px;
  border-left-color: #D3D3D3;
  border-right-style: none;
  border-right-width: 1px;
  border-right-color: #D3D3D3;
  vertical-align: middle;
  overflow-x: hidden;
}

#qkzkkoeiqi .gt_stub {
  color: #333333;
  background-color: #FFFFFF;
  font-size: 100%;
  font-weight: initial;
  text-transform: inherit;
  border-right-style: solid;
  border-right-width: 2px;
  border-right-color: #D3D3D3;
  padding-left: 5px;
  padding-right: 5px;
}

#qkzkkoeiqi .gt_stub_row_group {
  color: #333333;
  background-color: #FFFFFF;
  font-size: 100%;
  font-weight: initial;
  text-transform: inherit;
  border-right-style: solid;
  border-right-width: 2px;
  border-right-color: #D3D3D3;
  padding-left: 5px;
  padding-right: 5px;
  vertical-align: top;
}

#qkzkkoeiqi .gt_row_group_first td {
  border-top-width: 2px;
}

#qkzkkoeiqi .gt_row_group_first th {
  border-top-width: 2px;
}

#qkzkkoeiqi .gt_summary_row {
  color: #333333;
  background-color: #FFFFFF;
  text-transform: inherit;
  padding-top: 8px;
  padding-bottom: 8px;
  padding-left: 5px;
  padding-right: 5px;
}

#qkzkkoeiqi .gt_first_summary_row {
  border-top-style: solid;
  border-top-color: #D3D3D3;
}

#qkzkkoeiqi .gt_first_summary_row.thick {
  border-top-width: 2px;
}

#qkzkkoeiqi .gt_last_summary_row {
  padding-top: 8px;
  padding-bottom: 8px;
  padding-left: 5px;
  padding-right: 5px;
  border-bottom-style: solid;
  border-bottom-width: 2px;
  border-bottom-color: #D3D3D3;
}

#qkzkkoeiqi .gt_grand_summary_row {
  color: #333333;
  background-color: #FFFFFF;
  text-transform: inherit;
  padding-top: 8px;
  padding-bottom: 8px;
  padding-left: 5px;
  padding-right: 5px;
}

#qkzkkoeiqi .gt_first_grand_summary_row {
  padding-top: 8px;
  padding-bottom: 8px;
  padding-left: 5px;
  padding-right: 5px;
  border-top-style: double;
  border-top-width: 6px;
  border-top-color: #D3D3D3;
}

#qkzkkoeiqi .gt_last_grand_summary_row_top {
  padding-top: 8px;
  padding-bottom: 8px;
  padding-left: 5px;
  padding-right: 5px;
  border-bottom-style: double;
  border-bottom-width: 6px;
  border-bottom-color: #D3D3D3;
}

#qkzkkoeiqi .gt_striped {
  background-color: rgba(128, 128, 128, 0.05);
}

#qkzkkoeiqi .gt_table_body {
  border-top-style: solid;
  border-top-width: 2px;
  border-top-color: #D3D3D3;
  border-bottom-style: solid;
  border-bottom-width: 2px;
  border-bottom-color: #D3D3D3;
}

#qkzkkoeiqi .gt_footnotes {
  color: #333333;
  background-color: #FFFFFF;
  border-bottom-style: none;
  border-bottom-width: 2px;
  border-bottom-color: #D3D3D3;
  border-left-style: none;
  border-left-width: 2px;
  border-left-color: #D3D3D3;
  border-right-style: none;
  border-right-width: 2px;
  border-right-color: #D3D3D3;
}

#qkzkkoeiqi .gt_footnote {
  margin: 0px;
  font-size: 90%;
  padding-top: 4px;
  padding-bottom: 4px;
  padding-left: 5px;
  padding-right: 5px;
}

#qkzkkoeiqi .gt_sourcenotes {
  color: #333333;
  background-color: #FFFFFF;
  border-bottom-style: none;
  border-bottom-width: 2px;
  border-bottom-color: #D3D3D3;
  border-left-style: none;
  border-left-width: 2px;
  border-left-color: #D3D3D3;
  border-right-style: none;
  border-right-width: 2px;
  border-right-color: #D3D3D3;
}

#qkzkkoeiqi .gt_sourcenote {
  font-size: 90%;
  padding-top: 4px;
  padding-bottom: 4px;
  padding-left: 5px;
  padding-right: 5px;
}

#qkzkkoeiqi .gt_left {
  text-align: left;
}

#qkzkkoeiqi .gt_center {
  text-align: center;
}

#qkzkkoeiqi .gt_right {
  text-align: right;
  font-variant-numeric: tabular-nums;
}

#qkzkkoeiqi .gt_font_normal {
  font-weight: normal;
}

#qkzkkoeiqi .gt_font_bold {
  font-weight: bold;
}

#qkzkkoeiqi .gt_font_italic {
  font-style: italic;
}

#qkzkkoeiqi .gt_super {
  font-size: 65%;
}

#qkzkkoeiqi .gt_footnote_marks {
  font-size: 75%;
  vertical-align: 0.4em;
  position: initial;
}

#qkzkkoeiqi .gt_asterisk {
  font-size: 100%;
  vertical-align: 0;
}

#qkzkkoeiqi .gt_indent_1 {
  text-indent: 5px;
}

#qkzkkoeiqi .gt_indent_2 {
  text-indent: 10px;
}

#qkzkkoeiqi .gt_indent_3 {
  text-indent: 15px;
}

#qkzkkoeiqi .gt_indent_4 {
  text-indent: 20px;
}

#qkzkkoeiqi .gt_indent_5 {
  text-indent: 25px;
}

#qkzkkoeiqi .katex-display {
  display: inline-flex !important;
  margin-bottom: 0.75em !important;
}

#qkzkkoeiqi div.Reactable > div.rt-table > div.rt-thead > div.rt-tr.rt-tr-group-header > div.rt-th-group:after {
  height: 0px !important;
}
</style>
<table class="gt_table caption-top table table-sm table-striped small" data-quarto-bootstrap="false">
<thead><tr class="gt_col_headings header">
<th id="order" class="gt_col_heading gt_columns_bottom_border gt_right" data-quarto-table-cell-role="th" scope="col">Order</th>
<th id="p_continue" class="gt_col_heading gt_columns_bottom_border gt_right" data-quarto-table-cell-role="th" scope="col">Conditional P(next)</th>
<th id="survival" class="gt_col_heading gt_columns_bottom_border gt_right" data-quarto-table-cell-role="th" scope="col">Cohort surviving</th>
<th id="drop_off" class="gt_col_heading gt_columns_bottom_border gt_right" data-quarto-table-cell-role="th" scope="col">Drop-off</th>
</tr></thead>
<tbody class="gt_table_body">
<tr class="odd">
<td class="gt_row gt_right" headers="order">1</td>
<td class="gt_row gt_right" headers="p_continue">56.0%</td>
<td class="gt_row gt_right" headers="survival">100.0%</td>
<td class="gt_row gt_right" headers="drop_off">44.0%</td>
</tr>
<tr class="even">
<td class="gt_row gt_right" headers="order">2</td>
<td class="gt_row gt_right" headers="p_continue">63.0%</td>
<td class="gt_row gt_right" headers="survival">56.0%</td>
<td class="gt_row gt_right" headers="drop_off">20.7%</td>
</tr>
<tr class="odd">
<td class="gt_row gt_right" headers="order">3</td>
<td class="gt_row gt_right" headers="p_continue">67.0%</td>
<td class="gt_row gt_right" headers="survival">35.3%</td>
<td class="gt_row gt_right" headers="drop_off">11.6%</td>
</tr>
<tr class="even">
<td class="gt_row gt_right" headers="order">4</td>
<td class="gt_row gt_right" headers="p_continue">70.0%</td>
<td class="gt_row gt_right" headers="survival">23.6%</td>
<td class="gt_row gt_right" headers="drop_off">7.1%</td>
</tr>
<tr class="odd">
<td class="gt_row gt_right" headers="order">5</td>
<td class="gt_row gt_right" headers="p_continue">73.0%</td>
<td class="gt_row gt_right" headers="survival">16.5%</td>
<td class="gt_row gt_right" headers="drop_off">4.5%</td>
</tr>
<tr class="even">
<td class="gt_row gt_right" headers="order">6</td>
<td class="gt_row gt_right" headers="p_continue">74.0%</td>
<td class="gt_row gt_right" headers="survival">12.1%</td>
<td class="gt_row gt_right" headers="drop_off">3.1%</td>
</tr>
<tr class="odd">
<td class="gt_row gt_right" headers="order">7</td>
<td class="gt_row gt_right" headers="p_continue">75.0%</td>
<td class="gt_row gt_right" headers="survival">8.9%</td>
<td class="gt_row gt_right" headers="drop_off">2.2%</td>
</tr>
<tr class="even">
<td class="gt_row gt_right" headers="order">8</td>
<td class="gt_row gt_right" headers="p_continue">77.0%</td>
<td class="gt_row gt_right" headers="survival">6.7%</td>
<td class="gt_row gt_right" headers="drop_off">1.5%</td>
</tr>
<tr class="odd">
<td class="gt_row gt_right" headers="order">9</td>
<td class="gt_row gt_right" headers="p_continue">78.0%</td>
<td class="gt_row gt_right" headers="survival">5.2%</td>
<td class="gt_row gt_right" headers="drop_off">1.1%</td>
</tr>
<tr class="even">
<td class="gt_row gt_right" headers="order">10</td>
<td class="gt_row gt_right" headers="p_continue">—</td>
<td class="gt_row gt_right" headers="survival">4.0%</td>
<td class="gt_row gt_right" headers="drop_off">—</td>
</tr>
</tbody>
</table>
</div>
</div>
</div>
<p>Already here, in the table representation of the data, we can see the main point. Of those who tried agentic shopping, half never bothered again, and so on. When you represent the progression as a survival line, only 4% of the initial pool reached 10th order.</p>
<p>Let’s plot it:</p>
<div class="cell page-columns page-full">
<pre>df_survival |&gt;
  ggplot(aes(x = order, y = survival)) +
  geom_step(linewidth = 1, color = &quot;#269292&quot;) +
  geom_point(size = 2.5, color = &quot;#269292&quot;) +
  geom_text(
    aes(label = scales::percent(survival, accuracy = 0.1)),
    vjust = -1.1,
    hjust = -.1,
    size = 5
  ) +
  scale_x_continuous(breaks = 1:10) +
  scale_y_continuous(
    labels = scales::percent_format(accuracy = 1),
    limits = c(0, 1.08),
    expand = c(0, 0)
  ) +
  labs(
    title = &quot;Only 4% of initial buyers\nreach a 10th agentic order&quot;,
    subtitle = &quot;Share of first-time buyers surviving to at least the n-th purchase&quot;,
    x = &quot;Order number (n)&quot;,
    y = &quot;Initial cohort surviving&quot;,
    caption = &quot;Data: Stripe analysis (Nov 2026) | Graphic: @ikashnitsky.phd&quot;
  ) </pre>
<div class="cell-output-display page-columns page-full">
<div id="fig-survival" class="quarto-float quarto-figure quarto-figure-center anchored page-columns page-full">
<figure class="quarto-float quarto-float-fig figure page-columns page-full"><div aria-describedby="fig-survival-caption-0ceaefa1-69ba-4598-a22c-09a6ac19f8ca">
<img src="https://i2.wp.com/ikashnitsky.phd/2026/half-empty/index_files/figure-html/fig-survival-1.png?w=450&#038;ssl=1" class="img-fluid figure-img"  data-recalc-dims="1">
</div>
<figcaption class="quarto-float-caption-margin quarto-float-caption quarto-float-fig margin-caption" id="fig-survival-caption-0ceaefa1-69ba-4598-a22c-09a6ac19f8ca">
Figure 1: Cohort survival across repeat agentic purchases (recalculated from Stripe data)
</figcaption></figure>
</div>
</div>
</div>
<p>So, is the glass half filled or almost empty? <img src="https://s.w.org/images/core/emoji/13.0.0/72x72/1f643.png" alt="🙃" class="wp-smiley" style="height: 1em; max-height: 1em;" /></p>


<!-- -->


 
<div style="border: 1px solid; background: none repeat scroll 0 0 #EDEDED; margin: 1px; font-size: 13px;">
<div style="text-align: center;">To <strong>leave a comment</strong> for the author, please follow the link and comment on their blog: <strong><a href="https://ikashnitsky.phd/2026/half-empty/"> Ilya Kashnitsky</a></strong>.</div>
<hr />
<a href="https://www.r-bloggers.com/" rel="nofollow">R-bloggers.com</a> offers <strong><a href="https://feedburner.google.com/fb/a/mailverify?uri=RBloggers" rel="nofollow">daily e-mail updates</a></strong> about <a title="The R Project for Statistical Computing" href="https://www.r-project.org/" rel="nofollow">R</a> news and tutorials about <a title="R tutorials" href="https://www.r-bloggers.com/how-to-learn-r-2/" rel="nofollow">learning R</a> and many other topics. <a title="Data science jobs" href="https://www.r-users.com/" rel="nofollow">Click here if you're looking to post or find an R/data-science job</a>.

<hr>Want to share your content on R-bloggers?<a href="https://www.r-bloggers.com/add-your-blog/" rel="nofollow"> click here</a> if you have a blog, or <a href="http://r-posts.com/" rel="nofollow"> here</a> if you don't.
</div><strong>Continue reading</strong>: <a href="https://www.r-bloggers.com/2026/11/is-the-glass-half-filled-or-almost-empty/">Is the Glass Half Filled or Almost Empty?</a>]]></content:encoded>
					
		
		<enclosure url="https://ikashnitsky.phd/2026/half-empty/teaser.jpg" length="0" type="image/jpeg" />

		<post-id xmlns="com-wordpress:feed-additions:1">405091</post-id>	</item>
		<item>
		<title>Splitting Large Queries to Brazil&#8217;s Official Statistics API with ibger</title>
		<link>https://www.r-bloggers.com/2026/11/splitting-large-queries-to-brazils-official-statistics-api-with-ibger/</link>
		
		<dc:creator><![CDATA[rOpenSci]]></dc:creator>
		<pubDate>Mon, 23 Nov 2026 00:00:00 +0000</pubDate>
				<category><![CDATA[R bloggers]]></category>
		<guid isPermaLink="false">https://ropensci.org/blog/2026/11/23/ibger/</guid>

					<description><![CDATA[<p>The Brazilian Institute of Geography and Statistics (IBGE)<br />
produces Brazil’s official statistics: the demographic census, the IPCA<br />
inflation index1, municipal GDP, and dozens of recurring economic, social and<br />
agricultural surveys. Their results are pu...</p>
<strong>Continue reading</strong>: <a href="https://www.r-bloggers.com/2026/11/splitting-large-queries-to-brazils-official-statistics-api-with-ibger/">Splitting Large Queries to Brazil’s Official Statistics API with ibger</a>]]></description>
										<content:encoded><![CDATA[<!-- 
<div style="min-height: 30px;">
[social4i size="small" align="align-left"]
</div>
-->

<div style="border: 1px solid; background: none repeat scroll 0 0 #EDEDED; margin: 1px; font-size: 12px;">
[This article was first published on  <strong><a href="https://ropensci.org/blog/2026/11/23/ibger/"> rOpenSci - open tools for open science</a></strong>, and kindly contributed to <a href="https://www.r-bloggers.com/" rel="nofollow">R-bloggers</a>].  (You can report issue about the content on this page <a href="https://www.r-bloggers.com/contact-us/">here</a>)
<hr>Want to share your content on R-bloggers?<a href="https://www.r-bloggers.com/add-your-blog/" rel="nofollow"> click here</a> if you have a blog, or <a href="http://r-posts.com/" rel="nofollow"> here</a> if you don't.
</div>

<p>The Brazilian Institute of Geography and Statistics (<a href="https://www.ibge.gov.br/en/" rel="nofollow" target="_blank">IBGE</a>)
produces Brazil’s official statistics: the demographic census, the IPCA
inflation index<sup id="fnref:1"><a href="https://ropensci.org/blog/2026/11/23/ibger/#fn:1" class="footnote-ref" role="doc-noteref" rel="nofollow" target="_blank">1</a></sup>, municipal GDP, and dozens of recurring economic, social and
agricultural surveys. Their results are published as thousands of aggregate
tables in SIDRA, IBGE’s data retrieval system, and exposed through the
<a href="https://servicodados.ibge.gov.br/api/docs/agregados?versao=3" rel="nofollow" target="_blank">IBGE Aggregates API</a>.</p>
<p><a href="https://docs.ropensci.org/ibger/" rel="nofollow" target="_blank">ibger</a> is an R client for that API. It lets
you discover tables, inspect their metadata, and retrieve data as tidy
tibbles. The package recently passed
<a href="https://github.com/ropensci/software-review/issues/787" rel="nofollow" target="_blank">rOpenSci software peer review</a>,
and version 0.2.1 is on CRAN.</p>
<p>ibger grew out of everyday work. We are part of the Strategic Monitoring
Data Science Team of the Pernambuco state government, in northeastern
Brazil, which builds R-based tools to monitor state public
policies<sup id="fnref:2"><a href="https://ropensci.org/blog/2026/11/23/ibger/#fn:2" class="footnote-ref" role="doc-noteref" rel="nofollow" target="_blank">2</a></sup>. Our dashboards and reports draw on IBGE indicators, and they
are updated by scripts that pull the same tables again and again, often for
every municipality and for many years at once. We wanted that access to be
scripted, validated and reproducible, rather than a series of manual
downloads from the SIDRA website. Less than a week after the first CRAN
release, <a href="https://github.com/danielvartan" rel="nofollow" target="_blank">Daniel Vartanian</a> opened an
<a href="https://github.com/ropensci/ibger/issues/1" rel="nofollow" target="_blank">issue</a> explaining that he
split his calls into smaller chunks by hand to get around the API’s
limits, and suggested submitting the package to rOpenSci. Both ideas
stuck.</p>
<p>This tech note is about one problem that every heavy user of the API runs
into sooner or later: the limit on how many values a single request can
return, and how ibger works around it.</p>
<h2>
The request limit
</h2><p>Each SIDRA table crosses variables, periods, geographic units and
classification categories, so results grow multiplicatively. A modest
question such as “how much soybean did each of Brazil’s 5,570
municipalities produce in each year since 2000?” already means more than
140,000 values.</p>
<p>The API documentation states a limit of 100,000 values per request. In
practice, requests start to fail well before that: while developing ibger we
saw a request for 44,560 values succeed and one for 50,130 values fail. And
when a request is too large, the API does not say so. It answers with a
generic HTTP 500 error.</p>
<p>Here is what happens if we send the soybean query in a single request, with
automatic splitting turned off (<code>chunk = FALSE</code>). We use table 1612
(municipal crop production), variable 214 (quantity produced), category 2713
of classification 81 (soybeans) and the municipal level <code>&quot;N6&quot;</code>:</p>
<pre>library(ibger)

soy &lt;- ibge_variables(
 1612,
 variable = 214,
 periods = 2000:2025,
 localities = &quot;N6&quot;,
 classification = list(&quot;81&quot; = 2713),
 chunk = FALSE
)

Error:
! Failed to access the IBGE API.
&#x2716; HTTP 500 Internal Server Error. &#x2139; The API returned error 500. This usually
means the query exceeds the API's result-size limit (documented as 100,000
values, in practice around 50,000). Try reducing localities, periods or
categories, or let `chunk = TRUE` split the request automatically.
&#x2139; URL:
&lt;https://servicodados.ibge.gov.br/api/v3/agregados/1612/periodos/2000|2001|2002|2003|2004|2005|2006|2007|2008|2009|2010|2011|2012|2013|2014|2015|2016|2017|2018|2019|2020|2021|2022|2023|2024|2025/variaveis/214&gt;
</pre>
<p>The usual workaround is to split the query by hand into several smaller
requests, guess sizes that will work, and bind the results back together.
ibger does this for you.</p>
<h2>
Estimating the size before asking
</h2><p>Before sending a data request, ibger estimates the size of the result as the
product of the number of variables, periods, localities and categories
involved. Most of the numbers come straight from the arguments. The ones
that do not, such as “all municipalities” or “the last six periods”, are
resolved from the table metadata: <code>ibge_metadata()</code> lists a table’s
variables and classifications, and the period and locality endpoints list
what each table covers. These lookups are cached, so each one is made only
once per table in a session.</p>
<p>The same metadata powers ibger’s validation: invalid variables, periods,
geographic levels or categories are caught before any data request is sent,
with an error that lists the allowed values.</p>
<h2>
Splitting the request
</h2><p>If the estimate exceeds the limit, ibger splits the query into chunks:
first by periods and then, if a single period is still too large, by
localities. Locality chunks are also capped at 500 codes per request to keep
URLs at a safe length. Each chunk is requested in turn and the results are
combined into a single tibble.</p>
<p>With the default <code>chunk = TRUE</code>, the same soybean query just works:</p>
<pre>soy &lt;- ibge_variables(
 1612,
 variable = 214,
 periods = 2000:2025,
 localities = &quot;N6&quot;,
 classification = list(&quot;81&quot; = 2713)
)

&#x2714; Aggregate 1612: 8 variables,
1 classification, 45 categories (cached).
&#x2139; Fetching N6 localities for aggregate 1612 from IBGE API...
&#x2714; Fetching N6 localities for aggregate 1612 from IBGE API... [149ms]
&#x2139; Fetching period list for aggregate 1612 from IBGE API...
&#x2714; Fetching period list for aggregate 1612 from IBGE API... [101ms]
&#x2139; Estimated result exceeds the API limit (50000 values);
splitting into 4 requests.
&#x2139; Fetching chunk 1/4 for aggregate 1612 from IBGE API...
&#x2714; Fetching chunk 1/4 for aggregate 1612 from IBGE API... [237ms]
&#x2139; Fetching chunk 2/4 for aggregate 1612 from IBGE API...
&#x2714; Fetching chunk 2/4 for aggregate 1612 from IBGE API... [230ms]
&#x2139; Fetching chunk 3/4 for aggregate 1612 from IBGE API...
&#x2714; Fetching chunk 3/4 for aggregate 1612 from IBGE API... [285ms]
&#x2139; Fetching chunk 4/4 for aggregate 1612 from IBGE API...
&#x2714; Fetching chunk 4/4 for aggregate 1612 from IBGE API... [280ms]
&#x2714; 144664 records retrieved.

soy

# A tibble: 144,664 × 9
variable_id variable_name variable_unit classification_81 locality_id
&lt;chr&gt; &lt;chr&gt; &lt;chr&gt; &lt;chr&gt; &lt;chr&gt;
1 214 Quantidade produzida Toneladas Soja (em grão) 1100015
2 214 Quantidade produzida Toneladas Soja (em grão) 1100015
3 214 Quantidade produzida Toneladas Soja (em grão) 1100015
4 214 Quantidade produzida Toneladas Soja (em grão) 1100015
5 214 Quantidade produzida Toneladas Soja (em grão) 1100015
6 214 Quantidade produzida Toneladas Soja (em grão) 1100015
7 214 Quantidade produzida Toneladas Soja (em grão) 1100015
8 214 Quantidade produzida Toneladas Soja (em grão) 1100015
9 214 Quantidade produzida Toneladas Soja (em grão) 1100023
10 214 Quantidade produzida Toneladas Soja (em grão) 1100023
# &#x2139; 144,654 more rows
# &#x2139; 4 more variables: locality_name &lt;chr&gt;, locality_level &lt;chr&gt;, period &lt;chr&gt;,
# value &lt;chr&gt;
</pre>
<p>The estimate was 26 periods × 5,564 municipalities, about 145,000 values,
so ibger fetched up to eight years per request, four requests in all.</p>
<p>If you need smaller requests, for example on an unstable connection, pass
your own limit, as in <code>chunk = 20000</code>. With <code>chunk = FALSE</code> the query is
sent as is.</p>
<h2>
From values to a picture
</h2><p>The <code>value</code> column is character, because IBGE uses special codes for
values that are zero after rounding (<code>-</code>), not applicable (<code>..</code>), not
available (<code>...</code>) or suppressed for confidentiality (<code>X</code>).
<code>parse_ibge_value()</code> converts them to numbers or <code>NA</code>. With that, the
145,000 values summarise into a picture of two decades of soybean expansion
in Brazil:</p>
<pre>library(dplyr)
library(ggplot2)

by_year &lt;- soy |&gt;
 mutate(
 year = as.integer(period),
 tonnes = parse_ibge_value(value)
 ) |&gt;
 group_by(year) |&gt;
 summarise(
 `Number of producing municipalities` = sum(tonnes &gt; 0, na.rm = TRUE),
 `Production (million metric tons)` = sum(tonnes, na.rm = TRUE) / 1e6
 ) |&gt;
 tidyr::pivot_longer(-year)

# first and last year of each series, to label the endpoints
ends &lt;- by_year |&gt;
 filter(year %in% range(year)) |&gt;
 mutate(first = year == min(year))

ggplot(by_year, aes(year, value)) +
 geom_line(linewidth = 1, colour = &quot;#2a7f62&quot;) +
 geom_point(data = ends, size = 2.5, colour = &quot;#2a7f62&quot;) +
 geom_text(
 aes(
 label = scales::comma(value, accuracy = 1),
 hjust = ifelse(first, -0.3, 1),
 vjust = ifelse(first, 1, -1)
 ),
 data = ends
 ) +
 facet_wrap(~name, scales = &quot;free_y&quot;) +
 scale_y_continuous(expand = expansion(mult = c(0.1, 0.2))) +
 labs(
 title = &quot;Growth in soybean production and geographic expansion (2000–2025)&quot;,
 x = NULL, y = NULL
 ) +
 theme_minimal(base_size = 13) +
 theme(plot.title.position = &quot;plot&quot;)
</pre><figure><img src="https://i2.wp.com/ropensci.org/blog/2026/11/23/ibger/soy-plot-1.png?w=578&#038;ssl=1"
alt="Two line charts for 2000 to 2025. Left: the number of municipalities producing soybeans grows from about 1,450 to about 2,640. Right: Brazilian soybean production grows from about 33 to about 165 million metric tons. The first and last values of each line are labelled." data-recalc-dims="1"><figcaption>
<p>Soybean production and producing municipalities in Brazil, 2000 to 2025 (IBGE, Produção Agrícola Municipal, table 1612).</p>
</figcaption>
</figure>
<p>Production grew about fivefold over the period, while the number of
municipalities producing it nearly doubled, from about 1,450 to over 2,600.</p>
<h2>
Learning more
</h2><p>ibger also translates URLs from the legacy SIDRA API, such as those
produced by the SIDRA Query Builder or used in existing scripts, into
equivalent calls with <code>parse_sidra_url()</code> and <code>fetch_sidra_url()</code>, and ships
an interactive Shiny explorer for browsing the table catalog
(<code>ibge_explorer()</code>). The
<a href="https://docs.ropensci.org/ibger/articles/getting-started.html" rel="nofollow" target="_blank">getting started vignette</a>
and the vignette on
<a href="https://docs.ropensci.org/ibger/articles/api-concepts.html" rel="nofollow" target="_blank">the concepts behind the IBGE API</a>
are good places to start. If you work in Python, the sibling package
<a href="https://strategicprojects.github.io/ibgepy/" rel="nofollow" target="_blank">ibgepy</a> offers the same
functions.</p>
<p>We are grateful to the editor <a href="https://github.com/beatrizmilz" rel="nofollow" target="_blank">Beatriz Milz</a>
and to the reviewers <a href="https://github.com/allanvc" rel="nofollow" target="_blank">Allan Quadros</a> and
<a href="https://github.com/ddiannae" rel="nofollow" target="_blank">Diana García-Cortés</a>, whose review, run
against the live API, made ibger much better. Bug reports, questions and ideas are welcome in the
<a href="https://github.com/ropensci/ibger/issues" rel="nofollow" target="_blank">issue tracker</a>.</p>
<div class="footnotes" role="doc-endnotes">
<hr>
<ol>
<li id="fn:1">
<p>IPCA stands for <em>Índice Nacional de Preços ao Consumidor Amplo</em> (Extended National Consumer Price Index), Brazil’s official inflation measure and the reference for the central bank’s inflation target. <a href="https://ropensci.org/blog/2026/11/23/ibger/#fnref:1" class="footnote-backref" role="doc-backlink" rel="nofollow" target="_blank"><img src="https://s.w.org/images/core/emoji/13.0.0/72x72/21a9.png" alt="↩" class="wp-smiley" style="height: 1em; max-height: 1em;" />︎</a></p>
</li>
<li id="fn:2">
<p>Medeiros, H. A. V., Wanderley, A. L., Bezerra, D. de C., Amorim Filho, C. A. G. de, Nóbrega, R. Z. da, &#038; Ferreira, F. G. de M. (2025). Government Data Science Teams: A Framework for Implementing Strategic Monitoring Solutions. dg.o 2025: 26th Annual International Conference on Digital Government Research. <a href="https://doi.org/10.59490/dgo.2025.925" rel="nofollow" target="_blank">https://doi.org/10.59490/dgo.2025.925</a> <a href="https://ropensci.org/blog/2026/11/23/ibger/#fnref:2" class="footnote-backref" role="doc-backlink" rel="nofollow" target="_blank"><img src="https://s.w.org/images/core/emoji/13.0.0/72x72/21a9.png" alt="↩" class="wp-smiley" style="height: 1em; max-height: 1em;" />︎</a></p>
</li>
</ol>
</div>
<div style="border: 1px solid; background: none repeat scroll 0 0 #EDEDED; margin: 1px; font-size: 13px;">
<div style="text-align: center;">To <strong>leave a comment</strong> for the author, please follow the link and comment on their blog: <strong><a href="https://ropensci.org/blog/2026/11/23/ibger/"> rOpenSci - open tools for open science</a></strong>.</div>
<hr />
<a href="https://www.r-bloggers.com/" rel="nofollow">R-bloggers.com</a> offers <strong><a href="https://feedburner.google.com/fb/a/mailverify?uri=RBloggers" rel="nofollow">daily e-mail updates</a></strong> about <a title="The R Project for Statistical Computing" href="https://www.r-project.org/" rel="nofollow">R</a> news and tutorials about <a title="R tutorials" href="https://www.r-bloggers.com/how-to-learn-r-2/" rel="nofollow">learning R</a> and many other topics. <a title="Data science jobs" href="https://www.r-users.com/" rel="nofollow">Click here if you're looking to post or find an R/data-science job</a>.

<hr>Want to share your content on R-bloggers?<a href="https://www.r-bloggers.com/add-your-blog/" rel="nofollow"> click here</a> if you have a blog, or <a href="http://r-posts.com/" rel="nofollow"> here</a> if you don't.
</div><strong>Continue reading</strong>: <a href="https://www.r-bloggers.com/2026/11/splitting-large-queries-to-brazils-official-statistics-api-with-ibger/">Splitting Large Queries to Brazil’s Official Statistics API with ibger</a>]]></content:encoded>
					
		
		<enclosure url="" length="0" type="" />

		<post-id xmlns="com-wordpress:feed-additions:1">405077</post-id>	</item>
		<item>
		<title>R Project Sprint 2027</title>
		<link>https://www.r-bloggers.com/2026/11/r-project-sprint-2027/</link>
		
		<dc:creator><![CDATA[Ella Kaye]]></dc:creator>
		<pubDate>Mon, 23 Nov 2026 00:00:00 +0000</pubDate>
				<category><![CDATA[R bloggers]]></category>
		<guid isPermaLink="false">https://forwards.github.io/blog/2026/r-project-sprint-2027/</guid>

					<description><![CDATA[<div style = "width:60%; display: inline-block; float:left; ">
<p>We are pleased to announce another R Project Sprint, to be hosted in Boston, USA, for 3 days in the week of Monday April 12, 2027 (exact dates TBD). Novice and experienced contributors are encouraged to apply for a place, with funding availabl...</p></div>
<div style = "width: 40%; display: inline-block; float:right;"></div>
<div style="clear: both;"></div>
<strong>Continue reading</strong>: <a href="https://www.r-bloggers.com/2026/11/r-project-sprint-2027/">R Project Sprint 2027</a>]]></description>
										<content:encoded><![CDATA[<!-- 
<div style="min-height: 30px;">
[social4i size="small" align="align-left"]
</div>
-->

<div style="border: 1px solid; background: none repeat scroll 0 0 #EDEDED; margin: 1px; font-size: 12px;">
[This article was first published on  <strong><a href="https://forwards.github.io/blog/2026/r-project-sprint-2027/"> Forwards</a></strong>, and kindly contributed to <a href="https://www.r-bloggers.com/" rel="nofollow">R-bloggers</a>].  (You can report issue about the content on this page <a href="https://www.r-bloggers.com/contact-us/">here</a>)
<hr>Want to share your content on R-bloggers?<a href="https://www.r-bloggers.com/add-your-blog/" rel="nofollow"> click here</a> if you have a blog, or <a href="http://r-posts.com/" rel="nofollow"> here</a> if you don't.
</div>
 






<p><img src="https://i1.wp.com/forwards.github.io/blog/2026/r-project-sprint-2027/group_friday.jpg?w=578&#038;ssl=1" class="img-fluid" alt="A photo of 38 in-person participants and two online participants on day 3 of the sprint in 2023." data-recalc-dims="1"></p>
<p>We are pleased to announce another R Project Sprint, to be hosted in <strong>Boston, USA, for 3 days in the week of Monday April 12, 2027</strong> (exact dates TBD). Novice and experienced contributors are encouraged to apply for a place, with funding available for travel and accommodation. Remote participation is also possible.</p>
<p>Apply by Friday 4 December (midnight Anywhere on Earth) to join this event to collaborate on contributions to base R and R Project infrastructure. Applications from Africa, the Middle East and Asia are particularly encouraged.</p>
<p>For further details and a link to the application form, see <a href="https://contributor.r-project.org/r-project-sprint-2027" class="uri" rel="nofollow" target="_blank">https://contributor.r-project.org/r-project-sprint-2027</a>.</p>


<!-- -->


 
<div style="border: 1px solid; background: none repeat scroll 0 0 #EDEDED; margin: 1px; font-size: 13px;">
<div style="text-align: center;">To <strong>leave a comment</strong> for the author, please follow the link and comment on their blog: <strong><a href="https://forwards.github.io/blog/2026/r-project-sprint-2027/"> Forwards</a></strong>.</div>
<hr />
<a href="https://www.r-bloggers.com/" rel="nofollow">R-bloggers.com</a> offers <strong><a href="https://feedburner.google.com/fb/a/mailverify?uri=RBloggers" rel="nofollow">daily e-mail updates</a></strong> about <a title="The R Project for Statistical Computing" href="https://www.r-project.org/" rel="nofollow">R</a> news and tutorials about <a title="R tutorials" href="https://www.r-bloggers.com/how-to-learn-r-2/" rel="nofollow">learning R</a> and many other topics. <a title="Data science jobs" href="https://www.r-users.com/" rel="nofollow">Click here if you're looking to post or find an R/data-science job</a>.

<hr>Want to share your content on R-bloggers?<a href="https://www.r-bloggers.com/add-your-blog/" rel="nofollow"> click here</a> if you have a blog, or <a href="http://r-posts.com/" rel="nofollow"> here</a> if you don't.
</div><strong>Continue reading</strong>: <a href="https://www.r-bloggers.com/2026/11/r-project-sprint-2027/">R Project Sprint 2027</a>]]></content:encoded>
					
		
		<enclosure url="https://forwards.github.io/blog/2026/r-project-sprint-2027/group_friday.jpg" length="0" type="image/jpeg" />

		<post-id xmlns="com-wordpress:feed-additions:1">405060</post-id>	</item>
		<item>
		<title>gratia 0.12.1</title>
		<link>https://www.r-bloggers.com/2026/11/gratia-0-12-1/</link>
		
		<dc:creator><![CDATA[Gavin Simpson]]></dc:creator>
		<pubDate>Sun, 22 Nov 2026 23:00:00 +0000</pubDate>
				<category><![CDATA[R bloggers]]></category>
		<guid isPermaLink="false">https://fromthebottomoftheheap.net/2026/11/23/gratia-0-12-1/</guid>

					<description><![CDATA[<div style = "width:60%; display: inline-block; float:left; ">
<p>A new version of gratia, 0.12.1, is now available on CRAN. This is a major new release, with a tonne of new features, improvements and bug fixes. There are so many changes in this version that ~1/2 of the Change log is dedicated to this version....</p></div>
<div style = "width: 40%; display: inline-block; float:right;"></div>
<div style="clear: both;"></div>
<strong>Continue reading</strong>: <a href="https://www.r-bloggers.com/2026/11/gratia-0-12-1/">gratia 0.12.1</a>]]></description>
										<content:encoded><![CDATA[<!-- 
<div style="min-height: 30px;">
[social4i size="small" align="align-left"]
</div>
-->

<div style="border: 1px solid; background: none repeat scroll 0 0 #EDEDED; margin: 1px; font-size: 12px;">
[This article was first published on  <strong><a href="https://fromthebottomoftheheap.net/2026/11/23/gratia-0-12-1/"> From the bottom of the heap — R posts</a></strong>, and kindly contributed to <a href="https://www.r-bloggers.com/" rel="nofollow">R-bloggers</a>].  (You can report issue about the content on this page <a href="https://www.r-bloggers.com/contact-us/">here</a>)
<hr>Want to share your content on R-bloggers?<a href="https://www.r-bloggers.com/add-your-blog/" rel="nofollow"> click here</a> if you have a blog, or <a href="http://r-posts.com/" rel="nofollow"> here</a> if you don't.
</div>






<!-- Confirm the announcement date and series dates once 0.12.1 is on CRAN. -->
<div class="no-row-height column-margin column-container"></div><p>A new version of gratia, 0.12.1, is now available on CRAN. This is a major new release, with a tonne of new features, improvements and bug fixes. There are so many changes in this version that ~1/2 of the <a href="https://gavinsimpson.github.io/gratia/news/index.html" rel="nofollow" target="_blank">Change log</a> is dedicated to this version.</p>
<p>This release adds ways to compare predictions, describe the spread of a response, and check whether a fitted model can generate data like those we observed. There are new plots, too, and a few changes to check before you rerun scripts written for earlier versions.</p>
<div class="cell">
<pre>install.packages(&quot;gratia&quot;)</pre>
</div>
<p>You’ll need R 4.4.0 or later now to use gratia. This release also requires mgcv 1.9-4 or later, ggplot2 4.0.3 or later, and patchwork 1.3.2 or later. The full list of changes is in the <a href="https://gavinsimpson.github.io/gratia/news/" rel="nofollow" target="_blank">release notes</a>.</p>
<p>In this post I’ll cover a couple of new features, and over the next few days I plan to drop feed posts on all the new features as time allows.</p>
<section id="putting-a-seasonal-smooth-on-a-circle" class="level2">
<h2 data-anchor-id="putting-a-seasonal-smooth-on-a-circle">Putting a seasonal smooth on a circle</h2>
<p>Here’s one new feature to try straight away. If you’ve fitted a cyclic smooth, <code>draw()</code> can show it in polar coordinates. I’ll simulate a year of temperature measurements, fit a cyclic smooth, and draw the same effect on linear and polar axes.</p>
<div class="cell">
<pre>library(&quot;mgcv&quot;)
library(&quot;gratia&quot;)

set.seed(12)
day &lt;- seq(0, 365, by = 3)
temperature &lt;- 10 - 8 * cos(2 * pi * day / 365) +
  rnorm(length(day), sd = 1.5)
seasonal &lt;- gam(
  temperature ~ s(day, bs = &quot;cc&quot;),
  knots = list(day = c(0, 365)), method = &quot;REML&quot;
)</pre>
</div>
<p>The usual partial effect plot for a cyclic smooth was the same as other univariate smooths. This remains the default, but from 0.12.1, you can choose to plot these using polar coordinates, which maps the smooth to a circle, with distance from centre encoding the partial effect. This is chosen using the <code>cyclic = &quot;polar&quot;</code> argument to <code>draw()</code>. I select <code>s(day)</code> in both calls and use <code>wrap = FALSE</code> so I can label each plot before combining them.</p>
<div class="cell">
<pre>linear &lt;- draw(
  seasonal, select = &quot;s(day)&quot;, rug = FALSE, wrap = FALSE
)[[1L]]
polar &lt;- draw(
  seasonal, select = &quot;s(day)&quot;, cyclic = &quot;polar&quot;, rug = FALSE, wrap = FALSE
)[[1L]]

axis_labels &lt;- ggplot2::labs(x = &quot;Day of year&quot;, y = &quot;Temperature effect (°C)&quot;)
patchwork::wrap_plots(linear + axis_labels, polar + axis_labels)</pre>
<div class="cell-output-display">
<div class="quarto-figure quarto-figure-center">
<figure class="figure">
<p><img src="https://i0.wp.com/fromthebottomoftheheap.net/2026/11/23/gratia-0-12-1/index_files/figure-html/seasonal-plots-1.png?w=450&#038;ssl=1" class="img-fluid figure-img" alt="The linear plot shows a summer peak and low values at both ends of the year. The polar plot joins those two ends."  data-recalc-dims="1"></p>
<figcaption>The fitted seasonal temperature effect on linear (left) and polar (right) axes.</figcaption>
</figure>
</div>
</div>
</div>
<p>The fitted cycle boundaries put the end of December next to the start of January. The polar view changes the presentation of the same estimated temperature effect and its interval.</p>
</section>
<section id="drawing-a-tensor-product-smooth-in-3d" class="level2">
<h2 data-anchor-id="drawing-a-tensor-product-smooth-in-3d">Drawing a tensor product smooth in 3D</h2>
<p>Another new feature is one that I have gone back and forth on over several years: 3D surface plots of bivariate smooths. In previous versions of gratia, you could only visualise these as 2D surface plots with <code>geom_raster()</code> or <code>geom_tile()</code>. 3D plots are a bit <em>blingy</em>, and largely antithetical to the layered grammar of graphics implement in ggplot2. But still, man users find it difficult to visualise the fitted surface when it is shown as a flat surface. Then along came ggcube, and my mind was made up.</p>
<p>In this example, I’ll use <code>data_sim(&quot;bivariate_surface&quot;)</code>, the new descriptive name for <code>&quot;eg2&quot;</code>. It simulates a response that depends jointly on two covariates, <code>x</code> and <code>z</code>. I’ll fit a tensor product smooth with <code>te(x, z)</code>, which allows the response to change with <code>x</code> in different ways at different values of <code>z</code>.</p>
<div class="cell">
<pre>surface_data &lt;- data_sim(&quot;bivariate_surface&quot;, n = 400, scale = 0.2, seed = 2)
surface_fit &lt;- gam(
  y ~ te(x, z, k = c(15, 15)),
  data = surface_data, method = &quot;REML&quot;
)</pre>
</div>
<p>To draw the surface in three dimensions, you’ll need ggcube (version 0.3.0 or later).</p>
<p>The default <code>draw()</code> plot uses colour and contours to show the estimated effect on a flat grid. With <code>surface = &quot;3d&quot;</code>, you can also see the effect as height above the <code>x</code>–<code>z</code> plane. Here I’ve turned the view with <code>yaw</code> and used a parallel projection with <code>persp = FALSE</code>.</p>
<div class="cell">
<pre>draw(
  surface_fit, surface = &quot;3d&quot;,
  surface_3d = list(yaw = 45, persp = FALSE)
)</pre>
<div class="cell-output-display">
<div class="quarto-figure quarto-figure-center">
<figure class="figure">
<p><img src="https://i1.wp.com/fromthebottomoftheheap.net/2026/11/23/gratia-0-12-1/index_files/figure-html/tensor-surface-3d-1.png?w=450&#038;ssl=1" class="img-fluid figure-img" alt="A tilted surface over x and z with orange peaks and a blue low region. Contours trace the surface, and grey dots on the floor show where observations were taken."  data-recalc-dims="1"></p>
<figcaption>The fitted tensor product smooth viewed in three dimensions. Height and colour show the smooth contribution to the linear predictor.</figcaption>
</figure>
</div>
</div>
</div>
<p>With <code>ci_3d = TRUE</code>, gratia draws two translucent surfaces at the lower and upper pointwise interval limits. I tilt the view closer to the side and use a dark blue-grey fill so the bounds stand out against the grey background.</p>
<div class="cell">
<pre>draw(
  surface_fit, surface = &quot;3d&quot;, ci_3d = TRUE, rug = TRUE,
  surface_3d = list(yaw = 45, roll = -78, persp = FALSE)
) &
  ggplot2::theme(
    geom.gratia.surface.interval = ggplot2::element_geom(fill = &quot;#344054&quot;),
    gratia.alpha.surface.interval = 0.42
  )</pre>
<div class="cell-output-display">
<div class="quarto-figure quarto-figure-center">
<figure class="figure">
<p><img src="https://i1.wp.com/fromthebottomoftheheap.net/2026/11/23/gratia-0-12-1/index_files/figure-html/tensor-surface-3d-intervals-1.png?w=450&#038;ssl=1" class="img-fluid figure-img" alt="Blue-grey sheets sit above and below the coloured fitted surface and spread apart near the edges. Grey dots on the floor show the observation locations."  data-recalc-dims="1"></p>
<figcaption>The fitted smooth viewed from a lower angle. The translucent blue-grey sheets mark the lower and upper pointwise interval limits.</figcaption>
</figure>
</div>
</div>
</div>
</section>
<section id="what-else-is-new" class="level2">
<h2 data-anchor-id="what-else-is-new">What else is new?</h2>
<ul>
<li><strong>More control over effect plots.</strong> Style smooths, intervals, and diagnostic plots through ggplot2 component themes. Overlay or separate factor-related curves, draw parametric interactions, or display a surface in 3D with the optional ggcube package.</li>
<li><strong>Ways to ask more of a fitted GAM.</strong> Use <code>conditional_differences()</code> to compare complete predictions between treatments and <code>compare_smooths()</code> to compare smooth contributions from separate models. Plot conditional prediction surfaces, look at how response variability changes with a covariate using <code>conditional_moments()</code>, or use <code>ale()</code> to estimate accumulated local effects.</li>
<li><strong>More model checks and sampling tools.</strong> Try posterior predictive plots, scalable diagnostic displays, residual plots against covariates, or new simulation-based and categorical residuals. Posterior sampling can retain several chains and report coefficient sampling diagnostics. Supported GAMs can also use the new likelihood, LOO, and WAIC methods.</li>
<li><strong>Wider model support.</strong> The release expands support for models fitted with scam, gamm4, glmmTMB, sdmTMB, and GJRM. It also adds interval tools for supported shape-constrained <code>mgcv::scasm()</code> smooths. The available operations and uncertainty calculations depend on the model class.</li>
</ul>
</section>
<section id="what-to-check-when-upgrading" class="level2">
<h2 data-anchor-id="what-to-check-when-upgrading">What to check when upgrading</h2>
<table class="caption-top table">
<colgroup>
<col style="width: 50%">
<col style="width: 50%">
</colgroup>
<thead>
<tr class="header">
<th>If your code does this</th>
<th>Check this in 0.12.1</th>
</tr>
</thead>
<tbody>
<tr class="odd">
<td>Generates posterior draws</td>
<td>Name the sampling controls and supply <code>n_draws</code> explicitly when generating coefficient or sample draws. Use <code>n_grid</code> to set the resolution of an automatic smooth or derivative grid.</td>
</tr>
<tr class="even">
<td>Uses <code>fitted_samples()</code> as draws of the expected response</td>
<td>It now returns distribution parameters by default. Request <code>quantity = &quot;expectation&quot;</code> for expected responses where available. Check any code that uses parameter names.</td>
</tr>
<tr class="odd">
<td>Assembles a figure from <code>draw()</code> or <code>assemble()</code></td>
<td>An unselected GAM plot can now include parametric terms. Set <code>parametric = FALSE</code> for the old layout. Parametric plots use model-scale coordinates by default. Use <code>back_transform = TRUE</code> for the original covariate scale where supported.</td>
</tr>
<tr class="even">
<td>Sets plot colours and widths in <code>draw()</code>, or uses <code>grouped_by</code></td>
<td>Move appearance settings into <code>theme()</code> and use <code>grouped</code> for curve overlays. The old arguments are deprecated.</td>
</tr>
<tr class="odd">
<td>Calls <code>gratia::fixef()</code></td>
<td>Use <code>gratia::fixed_effects()</code> for supported models. For fits from nlme or lme4, use the fitting package’s <code>fixef()</code>.</td>
</tr>
</tbody>
</table>
<p>If you rely on a fixed seed to regenerate simulated responses, <code>posterior_samples()</code> still gives reproducible results, but its response draws for that seed can differ from those in earlier releases.</p>
<p>Over the next few posts I’ll work through plot themes, updating sampling scripts, treatment contrasts, and the difference between fitted distribution parameters and response moments. They’ll appear with the other <a href="https://fromthebottomoftheheap.net/tag/gratia/" rel="nofollow" target="_blank">gratia posts</a>.</p>


</section>

 
<div style="border: 1px solid; background: none repeat scroll 0 0 #EDEDED; margin: 1px; font-size: 13px;">
<div style="text-align: center;">To <strong>leave a comment</strong> for the author, please follow the link and comment on their blog: <strong><a href="https://fromthebottomoftheheap.net/2026/11/23/gratia-0-12-1/"> From the bottom of the heap — R posts</a></strong>.</div>
<hr />
<a href="https://www.r-bloggers.com/" rel="nofollow">R-bloggers.com</a> offers <strong><a href="https://feedburner.google.com/fb/a/mailverify?uri=RBloggers" rel="nofollow">daily e-mail updates</a></strong> about <a title="The R Project for Statistical Computing" href="https://www.r-project.org/" rel="nofollow">R</a> news and tutorials about <a title="R tutorials" href="https://www.r-bloggers.com/how-to-learn-r-2/" rel="nofollow">learning R</a> and many other topics. <a title="Data science jobs" href="https://www.r-users.com/" rel="nofollow">Click here if you're looking to post or find an R/data-science job</a>.

<hr>Want to share your content on R-bloggers?<a href="https://www.r-bloggers.com/add-your-blog/" rel="nofollow"> click here</a> if you have a blog, or <a href="http://r-posts.com/" rel="nofollow"> here</a> if you don't.
</div><strong>Continue reading</strong>: <a href="https://www.r-bloggers.com/2026/11/gratia-0-12-1/">gratia 0.12.1</a>]]></content:encoded>
					
		
		<enclosure url="" length="0" type="" />

		<post-id xmlns="com-wordpress:feed-additions:1">405062</post-id>	</item>
		<item>
		<title>Seeing nucleotides as images</title>
		<link>https://www.r-bloggers.com/2026/11/seeing-nucleotides-as-images/</link>
		
		<dc:creator><![CDATA[Michał Maj]]></dc:creator>
		<pubDate>Sun, 22 Nov 2026 00:00:00 +0000</pubDate>
				<category><![CDATA[R bloggers]]></category>
		<guid isPermaLink="false">https://datascienceguts.com/posts/2026-11-22-nucleotides-as-images/</guid>

					<description><![CDATA[<div style = "width:60%; display: inline-block; float:left; ">
<p>In 2022 I spent a few months on a problem far from anything I had done before: finding single letters in the tails of RNA molecules, from the electric current of a nanopore sequencer. The network I built then is the classifier inside Ninetails,...</p></div>
<div style = "width: 40%; display: inline-block; float:right;"></div>
<div style="clear: both;"></div>
<strong>Continue reading</strong>: <a href="https://www.r-bloggers.com/2026/11/seeing-nucleotides-as-images/">Seeing nucleotides as images</a>]]></description>
										<content:encoded><![CDATA[<!-- 
<div style="min-height: 30px;">
[social4i size="small" align="align-left"]
</div>
-->

<div style="border: 1px solid; background: none repeat scroll 0 0 #EDEDED; margin: 1px; font-size: 12px;">
[This article was first published on  <strong><a href="https://datascienceguts.com/posts/2026-11-22-nucleotides-as-images/"> Data Science Guts</a></strong>, and kindly contributed to <a href="https://www.r-bloggers.com/" rel="nofollow">R-bloggers</a>].  (You can report issue about the content on this page <a href="https://www.r-bloggers.com/contact-us/">here</a>)
<hr>Want to share your content on R-bloggers?<a href="https://www.r-bloggers.com/add-your-blog/" rel="nofollow"> click here</a> if you have a blog, or <a href="http://r-posts.com/" rel="nofollow"> here</a> if you don't.
</div>
 






<p>In 2022 I spent a few months on a problem far from anything I had done before: finding single letters in the tails of RNA molecules, from the electric current of a nanopore sequencer. The network I built then is the classifier inside <a href="https://github.com/LRB-IIMCB/ninetails" rel="nofollow" target="_blank">Ninetails</a>, an R package from <a href="https://www.linkedin.com/in/natalia-gumi%C5%84ska-49b162115/" rel="nofollow" target="_blank">Natalia Gumińska</a> and her colleagues at the IIMCB in Warsaw. The paper describing it came out in 2025 (<a href="https://www.nature.com/articles/s41467-025-57787-6" rel="nofollow" target="_blank">Gumińska et al., Nature Communications</a>).</p>
<p>I am not a geneticist, and this post does not pretend otherwise. What hooked me was the computer vision: the signal is a time series, the trick that made it work was to turn it into images, and that trick is worth knowing well beyond biology.</p>
<p>This is the first post of a short series. Here: just enough biology to follow along, what the images are, and the whole pipeline again &#8211; from public raw data to a trained network &#8211; to check that the 2022 result holds up.</p>
<section id="the-biology-briefly" class="level2">
<h2 class="anchored" data-anchor-id="the-biology-briefly">The biology, briefly</h2>
<p>A gene’s instructions travel from DNA to the protein-making machinery of a cell as messenger RNA (mRNA): a chain of four kinds of nucleotides, written A, C, G and U. Most mRNAs end in a <em>poly(A) tail</em> &#8211; tens to a couple of hundred As in a row. The tail is not part of the message; it is closer to a fuse. It protects the molecule and influences how long it lives and how much protein is made from it.</p>
<p>The tail is not always pure A. It can also contain nucleotides other than adenosine &#8211; for example C, G or U, slipped in by the enzymes that build and rebuild it &#8211; and these <em>non-adenosines</em> are linked to how long an mRNA survives. That makes them interesting far beyond basic research: the Ninetails paper follows, among others, the tails of the Moderna mRNA-1273 vaccine after it enters immune cells.</p>
<p>To count them, one needs to read the tail itself, letter by letter. That is where the nanopore comes in.</p>
</section>
<section id="how-a-nanopore-reads-rna" class="level2">
<h2 class="anchored" data-anchor-id="how-a-nanopore-reads-rna">How a nanopore reads RNA</h2>
<p>In <em>direct RNA sequencing</em> (Oxford Nanopore), a single RNA molecule is pulled through a protein pore in a membrane, tail first. A voltage drives ions through the same pore, and the nucleotides sitting in it &#8211; about five at a time in the pore used for this data; Oxford Nanopore says about nine for its newer pores, without publishing the details &#8211; partly block that ionic current. The instrument records the current a few thousand times per second. A <em>basecaller</em>, itself a neural network, translates the current back into letters.</p>
<p>Inside a long run of As, the current is nearly flat: the pore holds As, then more As. A single C, G or U disturbs it for the few moments it passes through. Here is what that looks like in four molecules from the training data, one per construct: a pure-A tail, and tails with one C, G or U.</p>
<div class="cell" data-layout-align="center">
<details class="code-fold">
<summary>Plot code</summary>
<pre>reads &lt;- read.delim(&quot;reads.tsv&quot;)
signals &lt;- read.csv(&quot;signals.csv&quot;)
hz &lt;- 3012                                     # samples per second
signals$t &lt;- signals$sample / hz
reads$t0 &lt;- reads$polya_start / hz
reads$t1 &lt;- reads$transcript_start / hz
reads$tx &lt;- reads$x_pos / hz

ggplot(signals, aes(t, pA)) +
  geom_rect(aes(xmin = t0, xmax = t1, ymin = -Inf, ymax = Inf,
                fill = class), data = reads, inherit.aes = FALSE,
            alpha = 0.15) +
  geom_line(linewidth = 0.25, colour = &quot;grey25&quot;) +
  geom_point(aes(tx, 140, fill = class), data = reads[!is.na(reads$tx), ],
             shape = 25, size = 2.6, colour = &quot;white&quot;, inherit.aes = FALSE) +
  facet_wrap(~ class, ncol = 1, scales = &quot;free_x&quot;,
             labeller = as_labeller(c(A = &quot;pure A&quot;, C = &quot;one C&quot;,
                                      G = &quot;one G&quot;, U = &quot;one U&quot;))) +
  scale_fill_manual(values = cls_col, guide = &quot;none&quot;) +
  coord_cartesian(ylim = c(40, 145)) +
  labs(x = &quot;time (s)&quot;, y = &quot;current (pA)&quot;)</pre>
</details>
</div>
<div class="cell" data-layout-align="center">
<div class="cell-output-display">
<div id="fig-reads" class="quarto-float quarto-figure quarto-figure-center anchored" data-fig-align="center">
<figure class="quarto-float quarto-float-fig figure">
<div aria-describedby="fig-reads-caption-0ceaefa1-69ba-4598-a22c-09a6ac19f8ca">
<img src="https://i1.wp.com/datascienceguts.com/posts/2026-11-22-nucleotides-as-images/index_files/figure-html/fig-reads-1.png?w=450&#038;ssl=1" class="img-fluid quarto-figure quarto-figure-center figure-img"  data-recalc-dims="1">
</div>
<figcaption class="quarto-float-caption-bottom quarto-float-caption quarto-float-fig" id="fig-reads-caption-0ceaefa1-69ba-4598-a22c-09a6ac19f8ca">
Figure 1: Raw current of four molecules from the training data. The shaded band is the poly(A) tail; it comes first because the molecule enters the pore tail first. The triangle marks where the basecaller placed the C, G or U.
</figcaption>
</figure>
</div>
</div>
</div>
<p>In each panel the shaded part is the tail, and it is the calmest stretch of the read. The non-A is visible as a short spike or dip in the middle of it - in this case at the same place in every construct, because the molecules were made to order (more on that below).</p>
<p>The basecaller is of little help here. Long runs of a single letter are its weak spot, and it was never trained to look for one odd letter inside them. Ninetails looks at the current instead.</p>
</section>
<section id="from-a-current-to-fragments" class="level2">
<h2 class="anchored" data-anchor-id="from-a-current-to-fragments">From a current to fragments</h2>
<p>Ninetails does not classify a whole tail. It simplifies the tail’s signal (outliers clipped, then every five samples merged into one point), looks for places where the current jumps away from its running mean, and cuts a 100-point fragment centred on each such place. The network only ever sees these fragments.</p>
<div class="cell" data-layout-align="center">
<details class="code-fold">
<summary>Plot code</summary>
<pre>tails &lt;- read.csv(&quot;tails.csv&quot;)
frags &lt;- read.csv(&quot;fragments.csv&quot;)
win &lt;- unique(frags[c(&quot;class&quot;, &quot;start&quot;)])
win$end &lt;- win$start + 99

ggplot(tails, aes(i, value)) +
  geom_rect(aes(xmin = start, xmax = end, ymin = -Inf, ymax = Inf,
                fill = class), data = win, inherit.aes = FALSE,
            alpha = 0.2) +
  geom_line(linewidth = 0.3, colour = &quot;grey25&quot;) +
  geom_point(data = tails[tails$pseudomove != 0, ], size = 0.9,
             colour = &quot;grey5&quot;) +
  facet_wrap(~ class, ncol = 2, scales = &quot;free&quot;) +
  scale_fill_manual(values = cls_col, guide = &quot;none&quot;) +
  labs(x = &quot;point in the simplified tail&quot;, y = &quot;signal (raw units)&quot;)</pre>
</details>
</div>
<div class="cell" data-layout-align="center">
<div class="cell-output-display">
<div id="fig-tails" class="quarto-float quarto-figure quarto-figure-center anchored" data-fig-align="center">
<figure class="quarto-float quarto-float-fig figure">
<div aria-describedby="fig-tails-caption-0ceaefa1-69ba-4598-a22c-09a6ac19f8ca">
<img src="https://i0.wp.com/datascienceguts.com/posts/2026-11-22-nucleotides-as-images/index_files/figure-html/fig-tails-1.png?w=450&#038;ssl=1" class="img-fluid quarto-figure quarto-figure-center figure-img"  data-recalc-dims="1">
</div>
<figcaption class="quarto-float-caption-bottom quarto-float-caption quarto-float-fig" id="fig-tails-caption-0ceaefa1-69ba-4598-a22c-09a6ac19f8ca">
Figure 2: The four tails as Ninetails sees them. Black dots are points where the signal leaves its running mean by more than 3.5 standard deviations; a run of at least five of them gives a fragment (shaded, 100 points). The pure-A tail has no such run; its fragment here is simply the middle of the tail, as the training set uses fragments like it.
</figcaption>
</figure>
</div>
</div>
</div>
<p>A 100-point fragment is a tiny time series: a flat line with, in three of the four classes, a bump somewhere near the middle. A 1D model could read that directly. In 2022 I went another way.</p>
</section>
<section id="a-time-series-as-an-image" class="level2">
<h2 class="anchored" data-anchor-id="a-time-series-as-an-image">A time series as an image</h2>
<p>The <em>Gramian Angular Field</em> (GAF; <a href="https://arxiv.org/abs/1506.00327" rel="nofollow" target="_blank">Wang and Oates, 2015</a>) is a recipe for turning a series of <img src="https://latex.codecogs.com/png.latex?n"> values into an <img src="https://latex.codecogs.com/png.latex?n%20%5Ctimes%20n"> image, so that a 2D convolutional network can look at it. “GAF” is the name of the recipe; it comes in two flavours, <strong>GASF</strong> and <strong>GADF</strong>, which share the first two steps and differ only in the last one:</p>
<ol type="1">
<li>Rescale the series to <img src="https://latex.codecogs.com/png.latex?%5B-1,%201%5D">; call the result <img src="https://latex.codecogs.com/png.latex?%5Ctilde%7Bx%7D">.</li>
<li>Read each value as the cosine of an angle: <img src="https://latex.codecogs.com/png.latex?%5Cphi_i%20=%20%5Carccos(%5Ctilde%7Bx%7D_i)">. Together with time as the radius, this places the series on a half circle (Figure 3).</li>
<li>Fill an <img src="https://latex.codecogs.com/png.latex?n%20%5Ctimes%20n"> image: pixel <img src="https://latex.codecogs.com/png.latex?(i,%20j)"> combines the angle of moment <img src="https://latex.codecogs.com/png.latex?i"> with the angle of moment <img src="https://latex.codecogs.com/png.latex?j">.
<ul>
<li><strong>GASF</strong> (<em>Summation</em> field): <img src="https://latex.codecogs.com/png.latex?%5Ccos(%5Cphi_i%20+%20%5Cphi_j)"></li>
<li><strong>GADF</strong> (<em>Difference</em> field): <img src="https://latex.codecogs.com/png.latex?%5Csin(%5Cphi_i%20-%20%5Cphi_j)"></li>
</ul></li>
</ol>
<p>So from one fragment you get two images, built from the same angles. Every pixel compares two moments of the series. In a flat stretch all moments look alike, and so do their pixels; the one odd moment differs from all the others, so its whole row and column stand out - a cross. Ninetails computes both images and gives them to the network together.</p>
<div class="cell" data-layout-align="center">
<details class="code-fold">
<summary>Plot code</summary>
<pre>rescale &lt;- function(x) (2 * x - max(x) - min(x)) / (max(x) - min(x))
g &lt;- frags[frags$class == &quot;G&quot;, ]
phi &lt;- acos(rescale(g$value))                  # angle
polar &lt;- data.frame(x = g$i * cos(phi), y = g$i * sin(phi))
rings &lt;- expand.grid(r = c(25, 50, 75, 100),
                     a = seq(0, pi, length.out = 181))

ggplot(polar, aes(x, y)) +
  geom_path(aes(r * cos(a), r * sin(a), group = r), data = rings,
            colour = &quot;grey85&quot;) +
  annotate(&quot;text&quot;, x = c(25, 50, 75, 100), y = -5, size = 3.2,
           label = c(25, 50, 75, 100), colour = &quot;grey40&quot;) +
  annotate(&quot;text&quot;, x = c(110, 0, -110), y = c(0, 108, 0), size = 4,
           label = c(&quot;0&quot;, &quot;π/2&quot;, &quot;π&quot;), colour = &quot;grey30&quot;) +
  geom_path(colour = cls_col[[&quot;G&quot;]], linewidth = 0.3, alpha = 0.35) +
  geom_point(colour = cls_col[[&quot;G&quot;]], size = 1.4) +
  coord_equal() +
  theme_void()</pre>
</details>
</div>
<div class="cell" data-layout-align="center">
<div class="cell-output-display">
<div id="fig-polar" class="quarto-float quarto-figure quarto-figure-center anchored" data-fig-align="center">
<figure class="quarto-float quarto-float-fig figure">
<div aria-describedby="fig-polar-caption-0ceaefa1-69ba-4598-a22c-09a6ac19f8ca">
<img src="https://i1.wp.com/datascienceguts.com/posts/2026-11-22-nucleotides-as-images/index_files/figure-html/fig-polar-1.png?w=450&#038;ssl=1" class="img-fluid quarto-figure quarto-figure-center figure-img"  data-recalc-dims="1">
</div>
<figcaption class="quarto-float-caption-bottom quarto-float-caption quarto-float-fig" id="fig-polar-caption-0ceaefa1-69ba-4598-a22c-09a6ac19f8ca">
Figure 3: The G fragment in polar coordinates: the angle comes from the rescaled value, the distance from the centre from the position (grey rings: points 25 to 100). The A stretches stay in one narrow band of angles; around point 50 the G throws the series out to the edges of the half circle and back.
</figcaption>
</figure>
</div>
</div>
</div>
<p>In code, both are a few lines. Here they are as they ship in Ninetails (<code>ninetails::create_gaf</code>), written out. The second function is not quite the textbook GADF - more on that below, once it matters:</p>
<div class="cell" data-layout-align="center">
<pre>rescale &lt;- function(x) (2 * x - max(x) - min(x)) / (max(x) - min(x))
minmax &lt;- function(m) round((m - min(m)) / (max(m) - min(m)), 4)

gasf &lt;- function(x) {
  phi &lt;- acos(rescale(x))
  minmax(cos(outer(phi, phi, &quot;+&quot;)))
}
gadf &lt;- function(x) {
  psi &lt;- asin(rescale(x))
  minmax(sin(outer(psi, psi, &quot;+&quot;)))
}</pre>
</div>
<p>Each 100-point fragment becomes a pair of 100 x 100 images - the GASF and the GADF - stacked as two channels, the same shape as a small two-colour photograph:</p>
<div class="cell" data-layout-align="center">
<details class="code-fold">
<summary>Plot code</summary>
<pre>frags &lt;- read.csv(&quot;fragments.csv&quot;)
as_long &lt;- function(m, cls, field) {
  data.frame(i = rep(seq_len(nrow(m)), ncol(m)),
             j = rep(seq_len(ncol(m)), each = nrow(m)),
             value = as.vector(m), class = cls, field = field)
}
gafs &lt;- do.call(rbind, lapply(c(&quot;A&quot;, &quot;C&quot;, &quot;G&quot;, &quot;U&quot;), function(k) {
  x &lt;- frags$value[frags$class == k]
  rbind(as_long(gasf(x), k, &quot;GASF&quot;), as_long(gadf(x), k, &quot;GADF&quot;))
}))
gafs$field &lt;- factor(gafs$field, c(&quot;GASF&quot;, &quot;GADF&quot;))

ggplot(gafs, aes(j, i, fill = value)) +
  geom_raster() +
  facet_grid(field ~ class) +
  seq_fill +
  scale_y_reverse() +
  coord_equal() +
  theme_void(base_size = 13) +
  theme(strip.text = element_text(margin = margin(4, 4, 4, 4)))</pre>
</details>
</div>
<div class="cell" data-layout-align="center">
<div class="cell-output-display">
<div id="fig-gaf" class="quarto-float quarto-figure quarto-figure-center anchored" data-fig-align="center">
<figure class="quarto-float quarto-float-fig figure">
<div aria-describedby="fig-gaf-caption-0ceaefa1-69ba-4598-a22c-09a6ac19f8ca">
<img src="https://i1.wp.com/datascienceguts.com/posts/2026-11-22-nucleotides-as-images/index_files/figure-html/fig-gaf-1.png?w=450&#038;ssl=1" class="img-fluid quarto-figure quarto-figure-center figure-img"  data-recalc-dims="1">
</div>
<figcaption class="quarto-float-caption-bottom quarto-float-caption quarto-float-fig" id="fig-gaf-caption-0ceaefa1-69ba-4598-a22c-09a6ac19f8ca">
Figure 4: The four fragments as GASF (top) and GADF (bottom) images. A pure-A fragment is noise; a non-A draws a cross through the image at its position.
</figcaption>
</figure>
</div>
</div>
</div>
<p>The non-A is no longer a blip in a line: it is a cross through the image, at the row and column of its position, and its texture differs between C, G and U.</p>
<section id="why-two-images" class="level3">
<h3 class="anchored" data-anchor-id="why-two-images">Why two images</h3>
<p>A G pushes the current up; a C or a U pulls it down (Figure 1). Their fragments are close to mirror images of each other - and GASF cannot tell a series from its mirror. Flipping the sign of <img src="https://latex.codecogs.com/png.latex?%5Ctilde%7Bx%7D"> turns every <img src="https://latex.codecogs.com/png.latex?%5Cphi"> into <img src="https://latex.codecogs.com/png.latex?%5Cpi%20-%20%5Cphi">, and <img src="https://latex.codecogs.com/png.latex?%5Ccos(2%5Cpi%20-%20%5Cphi_i%20-%20%5Cphi_j)%20=%20%5Ccos(%5Cphi_i%20+%20%5Cphi_j)">: the image does not change. The second channel is there to break that symmetry.</p>
<div class="cell" data-layout-align="center">
<details class="code-fold">
<summary>Plot code</summary>
<pre>x &lt;- frags$value[frags$class == &quot;G&quot;]
mirror &lt;- rbind(
  as_long(gasf(x), &quot;G fragment&quot;, &quot;GASF&quot;),
  as_long(gasf(-x), &quot;the same, mirrored&quot;, &quot;GASF&quot;),
  as_long(gadf(x), &quot;G fragment&quot;, &quot;GADF&quot;),
  as_long(gadf(-x), &quot;the same, mirrored&quot;, &quot;GADF&quot;))
mirror$field &lt;- factor(mirror$field, c(&quot;GASF&quot;, &quot;GADF&quot;))

ggplot(mirror, aes(j, i, fill = value)) +
  geom_raster() +
  facet_grid(field ~ class) +
  seq_fill +
  scale_y_reverse() +
  coord_equal() +
  theme_void(base_size = 13) +
  theme(strip.text = element_text(margin = margin(4, 4, 4, 4)))</pre>
</details>
</div>
<div class="cell" data-layout-align="center">
<div class="cell-output-display">
<div id="fig-mirror" class="quarto-float quarto-figure quarto-figure-center anchored" data-fig-align="center">
<figure class="quarto-float quarto-float-fig figure">
<div aria-describedby="fig-mirror-caption-0ceaefa1-69ba-4598-a22c-09a6ac19f8ca">
<img src="https://i0.wp.com/datascienceguts.com/posts/2026-11-22-nucleotides-as-images/index_files/figure-html/fig-mirror-1.png?w=450&#038;ssl=1" class="img-fluid quarto-figure quarto-figure-center figure-img"  data-recalc-dims="1">
</div>
<figcaption class="quarto-float-caption-bottom quarto-float-caption quarto-float-fig" id="fig-mirror-caption-0ceaefa1-69ba-4598-a22c-09a6ac19f8ca">
Figure 5: The G fragment and its mirror image. GASF (top) is identical; the second channel (bottom) is inverted.
</figcaption>
</figure>
</div>
</div>
</div>
<div class="cell" data-layout-align="center">
<pre>x &lt;- frags$value[frags$class == &quot;G&quot;]
identical(gasf(x), gasf(-x))
#&gt; [1] TRUE
all.equal(gadf(-x), 1 - gadf(x))
#&gt; [1] TRUE</pre>
</div>
<p>Now the promised detail about Ninetails’ second channel. The textbook GADF is <img src="https://latex.codecogs.com/png.latex?%5Csin(%5Cphi_i%20-%20%5Cphi_j)">; Ninetails computes <img src="https://latex.codecogs.com/png.latex?%5Csin(%5Cpsi_i%20+%20%5Cpsi_j)"> with <img src="https://latex.codecogs.com/png.latex?%5Cpsi%20=%20%5Carcsin(%5Ctilde%7Bx%7D)"> instead. It is a slightly different image: symmetric, where the textbook one is antisymmetric, and with a non-zero diagonal. But it does the one job the second channel is there for - a mirrored fragment gives the inverted image, so G and C/U look different, as the check above shows.</p>
</section>
<section id="other-ways-to-draw-a-series" class="level3">
<h3 class="anchored" data-anchor-id="other-ways-to-draw-a-series">Other ways to draw a series</h3>
<p>GAFs are not the only option. Two others are common, and each has its own recipe.</p>
<p>The <strong>Markov Transition Field</strong> (MTF; from the same paper as GAF) does not look at the values themselves, but at how the series <em>moves</em> between levels:</p>
<ol type="1">
<li>Split the range of values into <img src="https://latex.codecogs.com/png.latex?Q"> bins by quantiles (here <img src="https://latex.codecogs.com/png.latex?Q%20=%208">), so that every moment gets a state from 1 to 8.</li>
<li>Count how often the series goes from state <img src="https://latex.codecogs.com/png.latex?a"> to state <img src="https://latex.codecogs.com/png.latex?b"> between one moment and the next, and turn the counts into probabilities. This is a <img src="https://latex.codecogs.com/png.latex?Q%20%5Ctimes%20Q"> <em>Markov transition matrix</em> <img src="https://latex.codecogs.com/png.latex?W"> - the parent of the image. It is a compact summary, but it has forgotten <em>when</em> anything happened.</li>
<li>Spread <img src="https://latex.codecogs.com/png.latex?W"> back over time: pixel <img src="https://latex.codecogs.com/png.latex?(i,%20j)"> is <img src="https://latex.codecogs.com/png.latex?W_%7Bs_i,%20s_j%7D">, the probability of moving from the state of moment <img src="https://latex.codecogs.com/png.latex?i"> to the state of moment <img src="https://latex.codecogs.com/png.latex?j">.</li>
</ol>
<p>The <strong>recurrence plot</strong> (<a href="https://doi.org/10.1209/0295-5075/4/9/004" rel="nofollow" target="_blank">Eckmann et al., 1987</a>) is older and simpler still:</p>
<ol type="1">
<li>Rescale the series to <img src="https://latex.codecogs.com/png.latex?%5B0,%201%5D">.</li>
<li>Pixel <img src="https://latex.codecogs.com/png.latex?(i,%20j)"> is 1 if moments <img src="https://latex.codecogs.com/png.latex?i"> and <img src="https://latex.codecogs.com/png.latex?j"> have nearly the same value (<img src="https://latex.codecogs.com/png.latex?%7C%5Ctilde%7Bx%7D_i%20-%20%5Ctilde%7Bx%7D_j%7C%20%3C%20%5Cvarepsilon">, here <img src="https://latex.codecogs.com/png.latex?%5Cvarepsilon%20=%200.1">), and 0 otherwise.</li>
</ol>
<div class="cell" data-layout-align="center">
<pre>states &lt;- function(x, q = 8) {
  cut(x, unique(quantile(x, 0:q / q)), include.lowest = TRUE,
      labels = FALSE)
}
transitions &lt;- function(s) {           # Q x Q, rows sum to 1
  k &lt;- max(s)
  w &lt;- table(factor(head(s, -1), 1:k), factor(tail(s, -1), 1:k))
  unclass(w / pmax(rowSums(w), 1))
}
mtf &lt;- function(x, q = 8) {
  s &lt;- states(x, q)
  minmax(transitions(s)[s, s])         # pixel (i, j) = W[s_i, s_j]
}
recurrence &lt;- function(x, eps = 0.1) {
  z &lt;- (x - min(x)) / (max(x) - min(x))
  (abs(outer(z, z, &quot;-&quot;)) &lt; eps) * 1
}</pre>
</div>
<p>Here are the first two MTF steps for the C fragment:</p>
<div class="cell" data-layout-align="center">
<details class="code-fold">
<summary>Plot code</summary>
<pre>x &lt;- frags$value[frags$class == &quot;C&quot;]
s &lt;- states(x)
breaks &lt;- unique(quantile(x, 0:8 / 8))
ggplot(data.frame(i = seq_along(x), x = x, state = s), aes(i, x)) +
  geom_hline(yintercept = breaks, colour = &quot;grey85&quot;) +
  geom_line(linewidth = 0.3, colour = &quot;grey60&quot;) +
  geom_point(aes(colour = state), size = 1.6) +
  scale_colour_gradient(low = &quot;#9ec5f4&quot;, high = &quot;#123f78&quot;,
                        breaks = 1:8) +
  labs(x = &quot;point in the fragment&quot;, y = &quot;signal&quot;) +
  theme(panel.grid = element_blank())

w &lt;- transitions(s)
wd &lt;- data.frame(from = factor(rep(1:8, 8)), to = factor(rep(1:8, each = 8)),
                 p = as.vector(w))
wd$from &lt;- factor(wd$from, 8:1)
ggplot(wd, aes(to, from, fill = p)) +
  geom_tile(colour = &quot;white&quot;, linewidth = 0.8) +
  geom_text(aes(label = ifelse(p &gt; 0, sprintf(&quot;%.2f&quot;, p), &quot;&quot;),
                colour = p &gt; 0.5), size = 3) +
  scale_colour_manual(values = c(&quot;grey20&quot;, &quot;white&quot;), guide = &quot;none&quot;) +
  seq_fill +
  coord_equal() +
  labs(x = &quot;to state&quot;, y = &quot;from state&quot;) +
  theme(legend.position = &quot;none&quot;, panel.grid = element_blank())</pre>
</details>
</div>
<div id="fig-mtf-steps" class="quarto-layout-panel">
<figure class="quarto-float quarto-float-fig figure">
<div aria-describedby="fig-mtf-steps-caption-0ceaefa1-69ba-4598-a22c-09a6ac19f8ca">
<div class="quarto-layout-row">
<div class="cell-output-display quarto-layout-cell-subref quarto-layout-cell" data-ref-parent="fig-mtf-steps" style="flex-basis: 50.0%;justify-content: center;">
<div id="fig-mtf-steps-1" class="quarto-float quarto-figure quarto-figure-center anchored" data-fig-align="center">
<figure class="quarto-float quarto-subfloat-fig figure">
<div aria-describedby="fig-mtf-steps-1-caption-0ceaefa1-69ba-4598-a22c-09a6ac19f8ca">
<img src="https://i1.wp.com/datascienceguts.com/posts/2026-11-22-nucleotides-as-images/index_files/figure-html/fig-mtf-steps-1.png?w=441&#038;ssl=1" class="img-fluid quarto-figure quarto-figure-center figure-img" data-ref-parent="fig-mtf-steps"  data-recalc-dims="1">
</div>
<figcaption class="quarto-float-caption-bottom quarto-subfloat-caption quarto-subfloat-fig" id="fig-mtf-steps-1-caption-0ceaefa1-69ba-4598-a22c-09a6ac19f8ca">
(a) Step 1: every point gets a state, from its quantile bin (grey lines: bin edges). The flat A stretches spread over the upper states; the C dip is state 1.
</figcaption>
</figure>
</div>
</div>
<div class="cell-output-display quarto-layout-cell-subref quarto-layout-cell" data-ref-parent="fig-mtf-steps" style="flex-basis: 50.0%;justify-content: center;">
<div id="fig-mtf-steps-2" class="quarto-float quarto-figure quarto-figure-center anchored" data-fig-align="center">
<figure class="quarto-float quarto-subfloat-fig figure">
<div aria-describedby="fig-mtf-steps-2-caption-0ceaefa1-69ba-4598-a22c-09a6ac19f8ca">
<img src="https://i0.wp.com/datascienceguts.com/posts/2026-11-22-nucleotides-as-images/index_files/figure-html/fig-mtf-steps-2.png?w=441&#038;ssl=1" class="img-fluid quarto-figure quarto-figure-center figure-img" data-ref-parent="fig-mtf-steps"  data-recalc-dims="1">
</div>
<figcaption class="quarto-float-caption-bottom quarto-subfloat-caption quarto-subfloat-fig" id="fig-mtf-steps-2-caption-0ceaefa1-69ba-4598-a22c-09a6ac19f8ca">
(b) Step 2: the transition matrix. Noise makes the upper states jump between each other; once the series is in the dip, it tends to stay there.
</figcaption>
</figure>
</div>
</div>
</div>
</div>
<figcaption class="quarto-float-caption-bottom quarto-float-caption quarto-float-fig" id="fig-mtf-steps-caption-0ceaefa1-69ba-4598-a22c-09a6ac19f8ca">
Figure 6: The first two MTF steps for the C fragment.
</figcaption>
</figure>
</div>
<p>Step 3 turns this 8 x 8 matrix back into a 100 x 100 image. Here is the C fragment in all four forms:</p>
<div class="cell" data-layout-align="center">
<details class="code-fold">
<summary>Plot code</summary>
<pre>x &lt;- frags$value[frags$class == &quot;C&quot;]
forms &lt;- rbind(as_long(gasf(x), &quot;C&quot;, &quot;GASF&quot;),
               as_long(gadf(x), &quot;C&quot;, &quot;GADF (Ninetails)&quot;),
               as_long(mtf(x), &quot;C&quot;, &quot;Markov transition field&quot;),
               as_long(recurrence(x), &quot;C&quot;, &quot;recurrence plot&quot;))
forms$field &lt;- factor(forms$field, unique(forms$field))

ggplot(forms, aes(j, i, fill = value)) +
  geom_raster() +
  facet_wrap(~ field, nrow = 1) +
  seq_fill +
  scale_y_reverse() +
  coord_equal() +
  theme_void(base_size = 12) +
  theme(legend.position = &quot;none&quot;,
        strip.text = element_text(margin = margin(4, 4, 4, 4)))</pre>
</details>
</div>
<div class="cell" data-layout-align="center">
<div class="cell-output-display">
<div id="fig-others" class="quarto-float quarto-figure quarto-figure-center anchored" data-fig-align="center">
<figure class="quarto-float quarto-float-fig figure">
<div aria-describedby="fig-others-caption-0ceaefa1-69ba-4598-a22c-09a6ac19f8ca">
<img src="https://i0.wp.com/datascienceguts.com/posts/2026-11-22-nucleotides-as-images/index_files/figure-html/fig-others-1.png?w=450&#038;ssl=1" class="img-fluid quarto-figure quarto-figure-center figure-img"  data-recalc-dims="1">
</div>
<figcaption class="quarto-float-caption-bottom quarto-float-caption quarto-float-fig" id="fig-others-caption-0ceaefa1-69ba-4598-a22c-09a6ac19f8ca">
Figure 7: One C fragment, four images. All of them mark the position of the C; they differ in what else they encode.
</figcaption>
</figure>
</div>
</div>
</div>
<p>All four light up where the C is. Which of them works best for which signal is a question of its own, and one I want to measure properly some day. Ninetails uses GASF + GADF.</p>
</section>
</section>
<section id="the-whole-pipeline-from-public-data" class="level2">
<h2 class="anchored" data-anchor-id="the-whole-pipeline-from-public-data">The whole pipeline, from public data</h2>
<p>The molecules in Figure 1 are not from cells. They were made in the lab to a known design: a piece of a luciferase gene followed by a tail of about 60 nucleotides that is either all A or has a single C, G or U in the middle. With a known answer for every molecule, they are the training set. The raw data is public in the European Nucleotide Archive (run <a href="https://www.ebi.ac.uk/ena/browser/view/ERR12257477" rel="nofollow" target="_blank">ERR12257477</a>, 1.4 GB).</p>
<p>The heavy steps need a GPU and an afternoon, so they are not run in this post; the code is what I ran.</p>
<pre># raw current, FAST5 files in four folders (A, C, G, U constructs)
curl -O ftp.sra.ebi.ac.uk/vol1/run/ERR122/ERR12257477/syntheticRNA_training_CNN.tar.gz
tar xzf syntheticRNA_training_CNN.tar.gz

# FAST5 -&gt; POD5, then basecall with move tables (which sample is which base)
pod5 convert fast5 spikes_training_cnn/C_Rluc_CNN/*.fast5 --output C.pod5
dorado basecaller rna002_70bps_hac@v3 C.pod5 --emit-moves &gt; C.bam</pre>
<p>Two practical notes:</p>
<ul>
<li>The data was sequenced with the RNA002 chemistry, which current Dorado no longer supports. Version 0.9.6 is the last that does.</li>
<li>Ninetails expects the inputs of the older toolchain (Guppy-basecalled FAST5 files and tail positions from nanopolish). I found the tail in each read from Dorado’s move table and wrote those inputs myself.</li>
</ul>
<p>From there, Ninetails’ own functions cut the fragments and build the images:</p>
<pre>library(ninetails)
gafs_C &lt;- prepare_trainingset(
  &quot;C&quot;,
  nanopolish = &quot;C/nanopolish.tsv&quot;,
  sequencing_summary = &quot;C/sequencing_summary.txt&quot;,
  workspace = &quot;C/fast5&quot;
)</pre>
<p>The counts per class are not the paper’s, and should not be expected to be. The paper’s training set was built with Guppy and nanopolish and sampled to 9,440 fragments per class; here a different basecaller and my own tail boundaries decide which reads pass and where each tail starts and ends:</p>
<div class="cell" data-layout-align="center">
<details class="code-fold">
<summary>Plot code</summary>
<pre>counts &lt;- data.frame(class = c(&quot;A&quot;, &quot;C&quot;, &quot;G&quot;, &quot;U&quot;),
                     n = c(27773, 8376, 10969, 6670))
ggplot(counts, aes(class, n, fill = class)) +
  geom_col(width = 0.6) +
  geom_hline(yintercept = 9440, linetype = &quot;dashed&quot;, colour = &quot;grey35&quot;) +
  annotate(&quot;text&quot;, x = 1.5, y = 9440, label = &quot;paper: 9,440 per class&quot;,
           vjust = -0.6, hjust = 0, colour = &quot;grey25&quot;, size = 3.6) +
  scale_fill_manual(values = cls_col, guide = &quot;none&quot;) +
  scale_y_continuous(labels = scales::comma) +
  labs(x = NULL, y = &quot;fragments&quot;)</pre>
</details>
</div>
<div class="cell" data-layout-align="center">
<div class="cell-output-display">
<div id="fig-counts" class="quarto-float quarto-figure quarto-figure-center anchored" data-fig-align="center">
<figure class="quarto-float quarto-float-fig figure">
<div aria-describedby="fig-counts-caption-0ceaefa1-69ba-4598-a22c-09a6ac19f8ca">
<img src="https://i2.wp.com/datascienceguts.com/posts/2026-11-22-nucleotides-as-images/index_files/figure-html/fig-counts-1.png?w=450&#038;ssl=1" class="img-fluid quarto-figure quarto-figure-center figure-img"  data-recalc-dims="1">
</div>
<figcaption class="quarto-float-caption-bottom quarto-float-caption quarto-float-fig" id="fig-counts-caption-0ceaefa1-69ba-4598-a22c-09a6ac19f8ca">
Figure 8: Fragments per class from the public run, with Dorado and my tail boundaries. The paper’s training set, built with Guppy and nanopolish, was sampled to 9,440 per class.
</figcaption>
</figure>
</div>
</div>
</div>
<p>For training I balanced the classes to the smallest one.</p>
</section>
<section id="the-network" class="level2">
<h2 class="anchored" data-anchor-id="the-network">The network</h2>
<p>The model is small on purpose. A more elaborate network, tried first, overfit the modest amount of data; a VGG-style network of four convolutional blocks did better. Written out in R <code>keras</code> (the original was built in R):</p>
<pre>library(keras)
block &lt;- function(x, filters, kernel, padding) {
  x |&gt;
    layer_conv_2d(filters, kernel, padding = padding) |&gt;
    layer_batch_normalization() |&gt;
    layer_activation_relu() |&gt;
    layer_max_pooling_2d(2) |&gt;
    layer_dropout(0.5)
}
input &lt;- layer_input(c(100, 100, 2))
output &lt;- input |&gt;
  block(32, 5, &quot;valid&quot;) |&gt;
  block(32, 5, &quot;valid&quot;) |&gt;
  block(64, 3, &quot;same&quot;) |&gt;
  block(128, 3, &quot;same&quot;) |&gt;
  layer_flatten() |&gt;
  layer_dense(4, activation = &quot;softmax&quot;)
model &lt;- keras_model(input, output)      # 133,444 parameters</pre>
<p>I retrained it from scratch, with the architecture cloned from the model file that ships with Ninetails (in Python, <code>tf.keras.models.clone_model</code>): Adam with learning rate 0.001, batches of 64, early stopping on validation loss. The split is by <em>read</em>: all fragments of one molecule go to training, validation or test together, so the test set holds molecules the network has never seen.</p>
</section>
<section id="does-it-hold-up" class="level2">
<h2 class="anchored" data-anchor-id="does-it-hold-up">Does it hold up?</h2>
<div class="cell" data-layout-align="center">
<details class="code-fold">
<summary>Plot code</summary>
<pre>cm &lt;- matrix(c(727,   0,   4,   0,
                 4, 697,   5,  25,
                 0,   0, 731,   0,
                 5,  17,   1, 708), 4, byrow = TRUE,
             dimnames = list(true = c(&quot;A&quot;, &quot;C&quot;, &quot;G&quot;, &quot;U&quot;),
                             predicted = c(&quot;A&quot;, &quot;C&quot;, &quot;G&quot;, &quot;U&quot;)))
d &lt;- as.data.frame(as.table(cm), responseName = &quot;n&quot;)
d$share &lt;- d$n / rowSums(cm)[d$true]
d$true &lt;- factor(d$true, rev(levels(d$true)))

ggplot(d, aes(predicted, true, fill = share)) +
  geom_tile(colour = &quot;white&quot;, linewidth = 1) +
  geom_text(aes(label = n, colour = share &gt; 0.5), size = 4.2) +
  scale_colour_manual(values = c(&quot;grey20&quot;, &quot;white&quot;), guide = &quot;none&quot;) +
  seq_fill +
  coord_equal() +
  labs(x = &quot;predicted&quot;, y = &quot;true&quot;) +
  theme(legend.position = &quot;none&quot;, panel.grid = element_blank())</pre>
</details>
</div>
<div class="cell" data-layout-align="center">
<div class="cell-output-display">
<div id="fig-confusion" class="quarto-float quarto-figure quarto-figure-center anchored" data-fig-align="center">
<figure class="quarto-float quarto-float-fig figure">
<div aria-describedby="fig-confusion-caption-0ceaefa1-69ba-4598-a22c-09a6ac19f8ca">
<img src="https://i2.wp.com/datascienceguts.com/posts/2026-11-22-nucleotides-as-images/index_files/figure-html/fig-confusion-1.png?w=441&#038;ssl=1" class="img-fluid quarto-figure quarto-figure-center figure-img"  data-recalc-dims="1">
</div>
<figcaption class="quarto-float-caption-bottom quarto-float-caption quarto-float-fig" id="fig-confusion-caption-0ceaefa1-69ba-4598-a22c-09a6ac19f8ca">
Figure 9: Test fragments from molecules the network never saw (731 per class). Almost every mistake is C taken for U or U for C.
</figcaption>
</figure>
</div>
</div>
</div>
<p>Balanced accuracy on the test set is 0.979: A 0.995, C 0.954, G 1.000, U 0.969. Three repeats with a random split of fragments give 0.979-0.984, so splitting by molecule costs nothing here. The weak spot is the same as in the paper: C and U, whose signals are the most alike.</p>
<p>The paper reports more than 93% overall and above 85% for C and U. The two sets of numbers are not directly comparable - they come from different fragments, found with a different basecaller and different tail boundaries - so read mine as “the 2022 network still does its job with today’s tools”, not as an improvement on it.</p>
</section>
<section id="the-series-so-far" class="level2">
<h2 class="anchored" data-anchor-id="the-series-so-far">The series so far</h2>
<ol type="1">
<li><strong>Seeing nucleotides as images (this post)</strong> - the biology in brief, GASF and GADF, and the 2022 network rebuilt from public data.</li>
</ol>
<p>The next parts stay with nanopore signals seen through a computer vision lens; I will link them here as they come out.</p>


</section>

 
<div style="border: 1px solid; background: none repeat scroll 0 0 #EDEDED; margin: 1px; font-size: 13px;">
<div style="text-align: center;">To <strong>leave a comment</strong> for the author, please follow the link and comment on their blog: <strong><a href="https://datascienceguts.com/posts/2026-11-22-nucleotides-as-images/"> Data Science Guts</a></strong>.</div>
<hr />
<a href="https://www.r-bloggers.com/" rel="nofollow">R-bloggers.com</a> offers <strong><a href="https://feedburner.google.com/fb/a/mailverify?uri=RBloggers" rel="nofollow">daily e-mail updates</a></strong> about <a title="The R Project for Statistical Computing" href="https://www.r-project.org/" rel="nofollow">R</a> news and tutorials about <a title="R tutorials" href="https://www.r-bloggers.com/how-to-learn-r-2/" rel="nofollow">learning R</a> and many other topics. <a title="Data science jobs" href="https://www.r-users.com/" rel="nofollow">Click here if you're looking to post or find an R/data-science job</a>.

<hr>Want to share your content on R-bloggers?<a href="https://www.r-bloggers.com/add-your-blog/" rel="nofollow"> click here</a> if you have a blog, or <a href="http://r-posts.com/" rel="nofollow"> here</a> if you don't.
</div><strong>Continue reading</strong>: <a href="https://www.r-bloggers.com/2026/11/seeing-nucleotides-as-images/">Seeing nucleotides as images</a>]]></content:encoded>
					
		
		<enclosure url="https://datascienceguts.com/posts/2026-11-22-nucleotides-as-images/thumbnail.png" length="0" type="image/png" />

		<post-id xmlns="com-wordpress:feed-additions:1">405049</post-id>	</item>
		<item>
		<title>pyr.js: Python and R in HTML, documentation and examples</title>
		<link>https://www.r-bloggers.com/2026/11/pyr-js-python-and-r-in-html-documentation-and-examples/</link>
		
		<dc:creator><![CDATA[T. Moudiki]]></dc:creator>
		<pubDate>Sun, 22 Nov 2026 00:00:00 +0000</pubDate>
				<category><![CDATA[R bloggers]]></category>
		<guid isPermaLink="false">https://thierrymoudiki.github.io//blog/2026/11/22/python/r/javascript/py_js_2</guid>

					<description><![CDATA[<div style = "width:60%; display: inline-block; float:left; "> pyr.js runs Python and R code directly in HTML pages, in the browser, with one script tag: no server, no build step, no install. Pyodide and webR do the heavy lifting.</div>
<div style = "width: 40%; display: inline-block; float:right;"></div>
<div style="clear: both;"></div>
<strong>Continue reading</strong>: <a href="https://www.r-bloggers.com/2026/11/pyr-js-python-and-r-in-html-documentation-and-examples/">pyr.js: Python and R in HTML, documentation and examples</a>]]></description>
										<content:encoded><![CDATA[<!-- 
<div style="min-height: 30px;">
[social4i size="small" align="align-left"]
</div>
-->

<div style="border: 1px solid; background: none repeat scroll 0 0 #EDEDED; margin: 1px; font-size: 12px;">
[This article was first published on  <strong><a href="https://thierrymoudiki.github.io//blog/2026/11/22/python/r/javascript/py_js_2"> T. Moudiki's Webpage - R</a></strong>, and kindly contributed to <a href="https://www.r-bloggers.com/" rel="nofollow">R-bloggers</a>].  (You can report issue about the content on this page <a href="https://www.r-bloggers.com/contact-us/">here</a>)
<hr>Want to share your content on R-bloggers?<a href="https://www.r-bloggers.com/add-your-blog/" rel="nofollow"> click here</a> if you have a blog, or <a href="http://r-posts.com/" rel="nofollow"> here</a> if you don't.
</div>
<p>Last week, I wrote a post about <a href="https://thierrymoudiki.github.io/blog/2026/11/15/python/r/javascript/pyr_js" rel="nofollow" target="_blank"><code>pyr.js</code></a>, a library that allows you to run Python and R code directly in HTML pages, in the browser, with one script tag: no server, no build step, no install. Pyodide and webR do the heavy lifting.</p>

<p>Below are links to the documentation and examples of <a href="https://github.com/Techtonique/pyr.js" rel="nofollow" target="_blank"><code>pyr.js</code></a>:</p>

<ul>
  <li><a href="https://docs.techtonique.net/pyr.js/" rel="nofollow" target="_blank">https://docs.techtonique.net/pyr.js/</a></li>
  <li><a href="https://github.com/Techtonique/pyr.js/tree/main/examples" rel="nofollow" target="_blank">https://github.com/Techtonique/pyr.js/tree/main/examples</a></li>
</ul>

<p><img src="https://i2.wp.com/thierrymoudiki.github.io/images/2026-11-15/2026-11-15-image1.png?w=578&#038;ssl=1" alt="image-title-here" class="img-responsive" data-recalc-dims="1" /></p>


<div style="border: 1px solid; background: none repeat scroll 0 0 #EDEDED; margin: 1px; font-size: 13px;">
<div style="text-align: center;">To <strong>leave a comment</strong> for the author, please follow the link and comment on their blog: <strong><a href="https://thierrymoudiki.github.io//blog/2026/11/22/python/r/javascript/py_js_2"> T. Moudiki's Webpage - R</a></strong>.</div>
<hr />
<a href="https://www.r-bloggers.com/" rel="nofollow">R-bloggers.com</a> offers <strong><a href="https://feedburner.google.com/fb/a/mailverify?uri=RBloggers" rel="nofollow">daily e-mail updates</a></strong> about <a title="The R Project for Statistical Computing" href="https://www.r-project.org/" rel="nofollow">R</a> news and tutorials about <a title="R tutorials" href="https://www.r-bloggers.com/how-to-learn-r-2/" rel="nofollow">learning R</a> and many other topics. <a title="Data science jobs" href="https://www.r-users.com/" rel="nofollow">Click here if you're looking to post or find an R/data-science job</a>.

<hr>Want to share your content on R-bloggers?<a href="https://www.r-bloggers.com/add-your-blog/" rel="nofollow"> click here</a> if you have a blog, or <a href="http://r-posts.com/" rel="nofollow"> here</a> if you don't.
</div><strong>Continue reading</strong>: <a href="https://www.r-bloggers.com/2026/11/pyr-js-python-and-r-in-html-documentation-and-examples/">pyr.js: Python and R in HTML, documentation and examples</a>]]></content:encoded>
					
		
		<enclosure url="" length="0" type="" />

		<post-id xmlns="com-wordpress:feed-additions:1">405047</post-id>	</item>
		<item>
		<title>Classical Test Theory Analysis of the 16 Factor Personality Measure</title>
		<link>https://www.r-bloggers.com/2026/11/classical-test-theory-analysis-of-the-16-factor-personality-measure/</link>
		
		<dc:creator><![CDATA[Unknown]]></dc:creator>
		<pubDate>Sat, 21 Nov 2026 20:13:46 +0000</pubDate>
				<category><![CDATA[R bloggers]]></category>
		<guid isPermaLink="false">http://www.r-bloggers.com/?guid=2313ed640b06c62416b7227e4703e916</guid>

					<description><![CDATA[<div style = "width:60%; display: inline-block; float:left; "> In my<br />
last<br />
post, I talked through how to clean the dataset of careless<br />
responders, responders with too much missing data, and people older than<br />
time itself. Today, I’ll go through a classical test<br />
theory approach to psychometric analysis. If you’d like...</div>
<div style = "width: 40%; display: inline-block; float:right;"></div>
<div style="clear: both;"></div>
<strong>Continue reading</strong>: <a href="https://www.r-bloggers.com/2026/11/classical-test-theory-analysis-of-the-16-factor-personality-measure/">Classical Test Theory Analysis of the 16 Factor Personality Measure</a>]]></description>
										<content:encoded><![CDATA[<!-- 
<div style="min-height: 30px;">
[social4i size="small" align="align-left"]
</div>
-->

<div style="border: 1px solid; background: none repeat scroll 0 0 #EDEDED; margin: 1px; font-size: 12px;">
[This article was first published on  <strong><a href="http://www.deeplytrivial.com/2026/11/classical-test-theory-analysis-of-16.html"> Deeply Trivial</a></strong>, and kindly contributed to <a href="https://www.r-bloggers.com/" rel="nofollow">R-bloggers</a>].  (You can report issue about the content on this page <a href="https://www.r-bloggers.com/contact-us/">here</a>)
<hr>Want to share your content on R-bloggers?<a href="https://www.r-bloggers.com/add-your-blog/" rel="nofollow"> click here</a> if you have a blog, or <a href="http://r-posts.com/" rel="nofollow"> here</a> if you don't.
</div>
<p>In my
<a href="https://www.deeplytrivial.com/2026/11/preparing-data-cattells-16-factor.html" rel="nofollow" target="_blank">last
post</a>, I talked through how to clean the dataset of careless
responders, responders with too much missing data, and people older than
time itself. Today, I’ll go through a classical test
theory approach to psychometric analysis. If you’d like to go through
the cleaning process with the original dataset, I recommended going
through the last post. If you want, you can even change the cutoffs I
used for various flags and see how it changes the dataset and the
results going forward.</p>
<p>If, on the other hand, you want to start with the exact dataset I’m
using without going through the full cleaning process on your own, you
can download my clean copy
<a href="https://www.dropbox.com/scl/fi/3amnkkpr938w97yrcmnon/Cleaned-PF16-Data.csv?rlkey=47mkp8rm5ej7kxtoec9xtxe9a&#038;st=2cq47c8w&#038;dl=1" rel="nofollow" target="_blank">here</a>.
Just remember that inspecting and cleaning data is always part of the
process when analyzing a dataset.</p>
<pre>library(tidyverse)
## ── Attaching core tidyverse packages ──────────────────────── tidyverse 2.0.0 ──
## &#x2714; dplyr     1.2.1     &#x2714; readr     2.2.0
## &#x2714; forcats   1.0.1     &#x2714; stringr   1.6.0
## &#x2714; ggplot2   4.0.3     &#x2714; tibble    3.3.1
## &#x2714; lubridate 1.9.5     &#x2714; tidyr     1.3.2
## &#x2714; purrr     1.2.2     
## ── Conflicts ────────────────────────────────────────── tidyverse_conflicts() ──
## &#x2716; dplyr::filter() masks stats::filter()
## &#x2716; dplyr::lag()    masks stats::lag()
## &#x2139; Use the conflicted package (&lt;http://conflicted.r-lib.org/&gt;) to force all conflicts to become errors
PF16 &lt;- read_csv(&quot;Cleaned PF16 Data.csv&quot;)
## Rows: 46427 Columns: 171
## ── Column specification ────────────────────────────────────────────────────────
## Delimiter: &quot;,&quot;
## chr   (2): country, age_group
## dbl (169): A1, A2, A3, A4, A5, A6, A7, A8, A9, A10, B1, B2, B3, B4, B5, B6, ...
## 
## &#x2139; Use `spec()` to retrieve the full column specification for this data.
## &#x2139; Specify the column types or set `show_col_types = FALSE` to quiet this message.</pre>
<p>Classical test theory approaches are very much “what you see is what
you get.” What I mean by that is, the range of abilities (or more
specifically to a measure of traits, the range of how much of each trait
people possess) is defined entirely by the sample we selected, and how
well we can measure those traits is defined entirely by the items we
used (though we recognize there are other, potentially better items). We
can make assumptions that our sample is well representative of the full
range of presence of these traits, but subjecting a different sample to
this measure will likely produce very different results. This drawback
is one of the reasons psychometricians gravitate to item response theory
models, like Rasch, but the benefit of using CTT is that there are very
few statistical assumptions we need to meet to use these analyses. And
that sometimes makes CTT a better approach; it really depends on
context.</p>
<p>I’ll talk more about the assumptions of IRT in my next post. But the
key assumption in CTT is that a person’s observed score is the sum of
their true score (their underlying ability or how much of the trait they
actually posses - what we’re trying to measure) and error (caused by a
variety of factors that get in the way of obtaining that true score,
like distractions in the testing environment, a poorly written item,
lack of attention by the respondent, and so on). We want that error to
be 0, but we know in actual practice, it probably isn’t. So we work to
try to minimize that error: we use multiple items to measure the same
trait, hoping that will help cancel out some the error, and we conduct
analyses that help us measure that error and separate it from the true
score. We also use those analyses to identify the items that increase
measurement error, so that we can edit or remove them.</p>
<p>Now, in some cases IRT has influenced CTT. For instance, someone who
takes a purely CTT approach to psychometrics would treat rating scales
as continuous variables. In fact, CTT literature often states that
rating scales with at least 5 points can be treated as continuous
regardless. IRT would consider rating scales to be ordinal (that is,
until analysis converts them). Parametric statistics, like mean,
standard deviation, and Pearson’s correlation coefficient (stats that
assume normal distributions of the variable) are built specifically for
continuous variables, whereas ordinal variables would require
non-parametric approaches, like median, interquartile range, and
Spearman’s rank-order correlation coefficient, which don’t make any
assumptions about distributions. In my case, I’ll sometimes treat raw
ratings scales as continuous, if the parametric test I’m using is robust
with data that doesn’t quite meet assumptions, and sometimes as
ordinal.</p>
<p>First, I want to reverse code the negatively worded items. Then we
can start generating descriptive statistics by item and scale. The
number of negatively worded items varies by scale, so we’ll need to
specify the range for each scale, then use that list to reverse code the
correct variables. As I did in the last post, I’m using mutate across,
but this time we want it to use all items listed in ‘reverse’.
Subtracting each rating from 6 (number of options + 1) will reverse the
scale, so now 1 = 5, 2 = 4, and so on. 3, our midpoint ‘neutral’ option
will remain unchanged.</p>
<pre>reverse &lt;- list(paste0(&quot;A&quot;, 8:10), paste0(&quot;B&quot;, 9:13), paste0(&quot;C&quot;, 6:10),
                paste0(&quot;D&quot;, 7:10), paste0(&quot;E&quot;, 7:10), paste0(&quot;F&quot;, 6:10),
                paste0(&quot;G&quot;, 6:10), paste0(&quot;H&quot;, 7:10), paste0(&quot;I&quot;, 7:10),
                paste0(&quot;J&quot;, 8:10), paste0(&quot;K&quot;, 6:10), paste0(&quot;L&quot;, 8:10),
                paste0(&quot;M&quot;, 6:10), paste0(&quot;N&quot;, 8:10), paste0(&quot;O&quot;, 6:10),
                paste0(&quot;P&quot;, 8:10))

reverse &lt;- unlist(reverse)

PF16R &lt;- PF16 %&gt;% 
  mutate(across(all_of(reverse), ~ 6 - .x))</pre>
<p>I’d also like to have an index dataframe that contains the full name
of each scale and how many items each scale contains. When I start
generating statistics at the scale-level, I can add to this
dataframe.</p>
<pre>Scales &lt;- tibble(Code = c(toupper(letters[1:16])),
                     Name = c(&quot;Warmth&quot;,
                              &quot;Intellect&quot;,
                              &quot;Emotional Stability&quot;,
                              &quot;Assertiveness&quot;,
                              &quot;Gregariousness&quot;,
                              &quot;Dutifulness&quot;,
                              &quot;Friendliness&quot;,
                              &quot;Sensitivity&quot;,
                              &quot;Distrust&quot;,
                              &quot;Imagination&quot;,
                              &quot;Reserve&quot;,
                              &quot;Anxiety&quot;,
                              &quot;Complexity&quot;,
                              &quot;Introversion&quot;,
                              &quot;Orderliness&quot;,
                              &quot;Emotionality&quot;),
                     Items = c(10, 13, rep(10, 14)))</pre>
<p>I’ll start by generating means and standard deviations for each item.
(This is an instance of treating the rating scales as continuous.) Since
we want to aggregate, we’ll be using summarise instead of mutate, but we
can use summarise in very similar ways as mutate: such as summarizing
across a range of variables.</p>
<pre>ByItem &lt;- PF16R %&gt;%
  summarise(across(A1:P10, list(
    Mean =  ~mean(., na.rm = TRUE),
    SD = ~sd(.x, na.rm = TRUE))
  )) %&gt;%
  pivot_longer(everything(), names_to = c(&quot;Column&quot;, &quot;.value&quot;), names_sep = &quot;_&quot;)</pre>
<p>This first step of the code above creates a dataset with 1 row and 2
columns per item (163 * 2 = 326 columns), one with the item mean and the
other with standard deviation. The default is to name each column as
ColumnName_Function, so we’d have A1_Mean, A1_SD, A2_Mean, etc. Pivot
longer moves the column names to become row names, and “.value”,
combined with names_sep = “_” does two things: it removes _Mean and _SD
from the columns (leaving 163 rows, 1 for each item), and instead
creates 2 columns next to the list of items names, one for Mean and one
for SD. We can then add additional summary data to this file.</p>
<p>One of the big metrics used in CTT analyses is p-value, typically the
proportion of people responding to an item correctly or, if the measure
is a checklist, the proportion of people endorsing that item. But this
measure doesn’t have incorrect and correct answers, nor is it a
checklist. We can still generate a p-value-like measure, by dividing the
mean rating by the number of rating scale categories (5). Instead of
measuring percentage correct, it measures degree of aggreement with the
statment (on average). By itself, it isn’t extremely useful, but we can
examine it alongside other analyses to flag items that may not fit as
well on the measure.</p>
<pre>ByItem &lt;- ByItem %&gt;%
  mutate(pVal = Mean/5)</pre>
<p>Next, I’ll add counts selecting each rating scale option to the
ByItem data. Since the ByItem data is formatted as a row for each item,
I’ll create my counts of categories using pivot functions to put it in
the same format. In fact, for the next few analyses, I’ll want a set
that pivots my item response data into long form, so I’ll first create
that set.</p>
<p>This makes joining the two sets together very easy. I’ve also counted
the number of people who skipped each item, though I didn’t include them
when I calculated proportions selecting each option.</p>
<pre>Items &lt;- PF16R %&gt;%
  pivot_longer(
    cols = A1:P10,
    names_to = &quot;Item&quot;,
    values_to = &quot;Rating&quot;
  ) %&gt;%
  mutate(Code = substr(Item, 1, 1)) %&gt;%
  left_join(Scales, by = &quot;Code&quot;)

 CatCounts &lt;- Items %&gt;%
  count(Item, Rating) %&gt;%
  complete(Item, Rating = 1:5, fill = list(n = 0)) %&gt;%
  group_by(Item) %&gt;%
  pivot_wider(names_from = Rating, values_from = n)

ByItem &lt;- ByItem %&gt;%
  left_join(CatCounts, by = c(&quot;Column&quot; = &quot;Item&quot;))

ByItem &lt;- ByItem %&gt;%
  group_by(Column) %&gt;%
  mutate(TotalValid = sum(across(`1`:`5`)),
         StronglyDis = `1`/TotalValid,
         Disagree = `2`/TotalValid,
         Neither = `3`/TotalValid,
         Agree = `4`/TotalValid,
         StronglyAgr = `5`/TotalValid) %&gt;%
  ungroup()</pre>
<p>I’d also like to look at how well each item correlates to total scale
score on the remaining items. For knowledge tests and checklists, this
would be a point biserial, the correlation between a binary variable
(0/1, or incorrect/correct) and a continuous variable (score on
remaining items). But for a rating scale measure, we’ll be using
polyserial correlations, the correlation between an ordinal variable
(1-5 on the rating scale) and a continuous variable (score on the
remaining items). Since some respondents are missing an item from a
scale, we’ll compute total scores as averages of their ratings. Once we
have our scores, we can use the CTT package to compute polyserial
correlations by item.</p>
<pre>library(CTT)

Polyserials &lt;- Items %&gt;%
  group_by(ID, Code) %&gt;%
  mutate(Total = sum(Rating),
         Count = sum(!is.na(Rating)),
         Score = (Total - Rating)/(Count - 1)) %&gt;%
  group_by(Item) %&gt;%
  summarise(disc = polyserial(Score, Rating, ml = FALSE))

ByItem &lt;- ByItem %&gt;%
  left_join(Polyserials, by = c(&quot;Column&quot; = &quot;Item&quot;))</pre>
<p>I called our polyserial variable “disc” for “discrimination”, a
psychometric term for how well the item differentiates between people
who are high in the trait being measured and those low in the trait.</p>
<p>Lastly, I want to compute our scale reliabilities, as measured by
Cronbach’s alpha. This measures what is called internal consistency by
determining how much variance is attributable to true score variance -
that is, how much people naturally vary in the traits being measured -
by separating the variance shared by items (covariance) from total
variance, which would include both true scores and measurement error.
Alpha ranges from 0 to 1, and equals the proportion of variance
attributable to true scores; theoretically, an alpha of 1 means the
scale has no measurement error. In practice, it typically means
redundancy in items, multiple items that address the exact same concept
within a scale. For example, if I had a bunch of items measuring how
much you enjoy reading books as well as negatively worded items on how
much you don’t enjoy reading books. The scale would probably have a high
alpha, but it’s not giving you a lot of useful information, especially
if book reading is only one aspect of the concept I’m measuring.</p>
<p>There are multiple R packages that compute alpha, but we'd need to reformat the data. However, the formula for alpha is pretty simple:</p>
<div class="separator" style="clear: both; text-align: center;"><a href="https://i1.wp.com/blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEgYdfedwuKkpart7YxEmMSxUFk2RfOE9VbTYhwUr6mFf3rF3YfKlSJEOmb3LMzhqExqi_TZDeAXISzfbQDkZ-pgpA_-QWZyyGCTURiF7sZFKZFtFajNWHQDejVytlltInxavOdTFc5f36A_dZZBs0kfjTbBBK_PUBxIus8rYhFnwaF5T1CEyLIsWdEh6jpI/s1020/Cronbachs-Alpha.png?ssl=1" style="margin-left: 1em; margin-right: 1em;" rel="nofollow" target="_blank"><img loading="lazy" border="0" data-original-height="776" data-original-width="450" src="https://i0.wp.com/blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEgYdfedwuKkpart7YxEmMSxUFk2RfOE9VbTYhwUr6mFf3rF3YfKlSJEOmb3LMzhqExqi_TZDeAXISzfbQDkZ-pgpA_-QWZyyGCTURiF7sZFKZFtFajNWHQDejVytlltInxavOdTFc5f36A_dZZBs0kfjTbBBK_PUBxIus8rYhFnwaF5T1CEyLIsWdEh6jpI/s320/Cronbachs-Alpha.png?resize=450%2C776&#038;ssl=1" width="450" data-recalc-dims="1" /></a></div><br />
<p>I can easily compute the required variances, add them to my Scales
frame (which already includes number of items), and compute alpha for
each scale. For individual item variance, I already have standard
deviation, so I just need to square that value to get variance.
Generating total scores is a bit more involved: I’ve retained
respondents with up to 2 missing values, but I want a total score on the
same scale as respondents without missing values, so I’ll create a
corrected total score - the average score of the ratings they provided
(sum divided by number of items completed), multiplied by the number of
items on the full scale. Since I wanted to score my sample anyway, I
created a new dataframe of individual scores by scale, then aggregated
for the variance I need to generate my alphas.</p>
<pre>ByItem &lt;- ByItem %&gt;%
  mutate(Variance = SD^2)

Scores &lt;- Items %&gt;%
  ungroup() %&gt;%
  group_by(ID, Code) %&gt;%
  summarise(Total = sum(Rating, na.rm = TRUE),
            NItems = sum(!is.na(Rating))) %&gt;%
  ungroup() %&gt;%
  left_join(Scales, by = &quot;Code&quot;) %&gt;%
  mutate(Score = Total/NItems,
         CorTotal = Score*Items) 
## `summarise()` has regrouped the output.
## &#x2139; Summaries were computed grouped by ID and Code.
## &#x2139; Output is grouped by ID.
## &#x2139; Use `summarise(.groups = &quot;drop_last&quot;)` to silence this message.
## &#x2139; Use `summarise(.by = c(ID, Code))` for per-operation grouping
##   (`?dplyr::dplyr_by`) instead.
ByScale &lt;- Scores %&gt;%
  group_by(Code) %&gt;%
  summarise(Variance = var(CorTotal, na.rm = TRUE))

ByScale2 &lt;- ByItem %&gt;%
  ungroup() %&gt;%
  mutate(Code = substr(Column, 1, 1)) %&gt;%
  group_by(Code) %&gt;%
  summarise(EItemVar = sum(Variance))

Scales &lt;- Scales %&gt;%
  left_join(ByScale, by = &quot;Code&quot;) %&gt;%
  left_join(ByScale2, by = &quot;Code&quot;)

Scales &lt;- Scales %&gt;%
  mutate(Alpha = (Items/(Items-1)) * (1 - (EItemVar/Variance)))</pre>
<p>Now let’s go through these item-level and scale-level indices and
start flagging items that could be problematic.</p>
<p>I also have some information on the scales’ alphas from the
validation study, where 501 respondents completed both the original 16PF
and the IPIP version I’m using here. I can easily pull the table from
the webpage, though it needs a bit of cleaning to be useful.</p>
<pre>library(rvest)
## 
## Attaching package: 'rvest'
## The following object is masked from 'package:readr':
## 
##     guess_encoding
url &lt;- &quot;https://ipip.ori.org/new16PFTable.htm&quot;
page &lt;- read_html(url)
all_tables &lt;- html_table(page)

comptable &lt;- all_tables[[2]]

comptable &lt;- comptable %&gt;%
  rename(IPIPNames = X1,
         PF16Names = X2,
         IPIPItems = X3,
         PF16Items = X4,
         IPIPCor = X5,
         PF16Cor = X6,
         IPIPAlpha = X7,
         PF16Alpha = X8,
         Correlation = X9)

comptable &lt;- comptable[c(5:20), ]

ComparisonAlpha &lt;- comptable %&gt;%
  mutate(IPIPAlpha = as.numeric(IPIPAlpha)) %&gt;%
  select(IPIPNames, IPIPAlpha)

Scales &lt;- Scales %&gt;%
  left_join(ComparisonAlpha, by = c(&quot;Name&quot; = &quot;IPIPNames&quot;))

library(ggthemes)

Scales %&gt;%
  pivot_longer(
    cols = c(Alpha, IPIPAlpha), 
    names_to = &quot;source&quot;, 
    values_to = &quot;alpha&quot;
  ) %&gt;%
  ggplot(aes(x = Code, y = alpha, color = source)) +
  geom_point() +
  labs(y = &quot;Alpha&quot;, color = &quot;source&quot;) +
  theme_economist_white()</pre>
<div class="separator" style="clear: both;"><a href="https://i0.wp.com/blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEjyDh5DpmSfxUWX5G_RQtDuD9EmRwWciLeKaa7mT-50AyMNMnunOLcScXv5qOqlDIpPg_OGFaIBJ5YGGUrpR06ynCQgaaSppv7SlbN_mtZJb039V_nADQE-Z__Q5jm7XCmhj_89ob0rZ7PNMgSKWp70yJI2AiVX1uxv6nCcfhd8SHvNluMZgAigYAnF0_mC/s1400/Alpha%20Comparison.png?ssl=1" style="display: block; padding: 1em 0px; text-align: center;" rel="nofollow" target="_blank"><img alt="" border="0" data-original-height="865" data-original-width="450" src="https://i0.wp.com/blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEjyDh5DpmSfxUWX5G_RQtDuD9EmRwWciLeKaa7mT-50AyMNMnunOLcScXv5qOqlDIpPg_OGFaIBJ5YGGUrpR06ynCQgaaSppv7SlbN_mtZJb039V_nADQE-Z__Q5jm7XCmhj_89ob0rZ7PNMgSKWp70yJI2AiVX1uxv6nCcfhd8SHvNluMZgAigYAnF0_mC/s400/Alpha%20Comparison.png?resize=450%2C865&#038;ssl=1" width="450" data-recalc-dims="1" /></a></div>
<p>For 11 of the scales, this sample produced higher alphas than the
original validation sample. But what is a good alpha? The context of the
measure is important here. If it’s being used to make high stakes
decisions, like whether someone obtains a license or certificate or gets
diagnosed with a condition, reliability should be high, preferably in
the 0.9 range. But for a lower stakes measure, like this one, we can be
a bit more generous in what alphas are acceptable. I’ll consider 0.90
and greater to be excellent, 0.80 to 0.89 good, 0.70 to 0.79 acceptable,
and less than 0.70 questionable.</p>
<pre>Scales &lt;- Scales %&gt;%
  mutate(AlphaCat = cut(Alpha, breaks = c(0, 0.7, 0.8, 0.9, Inf),
                        labels = c(&quot;Questionable&quot;,
                                   &quot;Acceptable&quot;,
                                   &quot;Good&quot;,
                                   &quot;Excellent&quot;),
                        right = FALSE))

Scales %&gt;%
  ggplot(aes(x = Code, y = Alpha, colour = AlphaCat)) +
  geom_point() +
  theme_economist_white()</pre>
<div class="separator" style="clear: both;"><a href="https://i1.wp.com/blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEiIer9RNh46mVRyWerGwb_ZLKTgx_0aB0ib_LvZBe5H8eLKWTn8piyfGYRP2Co4TBTlFipaRcnBfW-7UgGhzRZyPspsJnI7TvV8Kp80SLxZIYJHQwv2QdMpVarkjuyusVrtWALRUY62c8dI57vPqIFRG4NHCECg-tktLUdZqu-osxuYq_4Ks_sl9Ly3vvY1/s1400/Alpha%20Categorized.png?ssl=1" style="display: block; padding: 1em 0px; text-align: center;" rel="nofollow" target="_blank"><img alt="" border="0" data-original-height="865" data-original-width="450" src="https://i1.wp.com/blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEiIer9RNh46mVRyWerGwb_ZLKTgx_0aB0ib_LvZBe5H8eLKWTn8piyfGYRP2Co4TBTlFipaRcnBfW-7UgGhzRZyPspsJnI7TvV8Kp80SLxZIYJHQwv2QdMpVarkjuyusVrtWALRUY62c8dI57vPqIFRG4NHCECg-tktLUdZqu-osxuYq_4Ks_sl9Ly3vvY1/s400/Alpha%20Categorized.png?resize=450%2C865&#038;ssl=1" width="450" data-recalc-dims="1" /></a></div>
<p>Overall, our alphas are fine, with the one exception being scale H,
sensitivity, which has an alpha of 0.67. Perhaps our item analysis will
help us determine the issue with this scale.</p>
<p>Let’s start with the p-value-like measure. It’s measuring average
degree of agreement with the item. Low agreement could just mean the
trait is rare. But if most of the items are easy to endorse in a scale,
and there are some exceptions, those items may not be measuring the
trait well. Let’s look at the items with a “p-value” of less than
0.5.</p>
<pre>ByItem %&gt;%
  filter(pVal &lt; 0.5) %&gt;%
  select(Column, Mean, pVal, StronglyDis:StronglyAgr)
## # A tibble: 7 × 8
##   Column  Mean  pVal StronglyDis Disagree Neither  Agree StronglyAgr
##   &lt;chr&gt;  &lt;dbl&gt; &lt;dbl&gt;       &lt;dbl&gt;    &lt;dbl&gt;   &lt;dbl&gt;  &lt;dbl&gt;       &lt;dbl&gt;
## 1 F8      2.43 0.487       0.252    0.387   0.135 0.126       0.0992
## 2 H4      2.27 0.455       0.286    0.384   0.151 0.126       0.0528
## 3 I6      2.11 0.422       0.344    0.362   0.167 0.0940      0.0332
## 4 K10     2.44 0.489       0.178    0.453   0.168 0.150       0.0515
## 5 N8      2.35 0.471       0.170    0.492   0.195 0.103       0.0401
## 6 P9      2.32 0.465       0.202    0.479   0.151 0.129       0.0389
## 7 P10     2.50 0.499       0.166    0.404   0.236 0.157       0.0374</pre>
<p>7 items showed low agreement, with average rating in the “disagree”
range, and disagree was the most frequent rating. So let’s add our first
flag to the item data.</p>
<pre>ByItem &lt;- ByItem %&gt;%
  mutate(Flag1 = ifelse(pVal &lt; 0.50, &quot;Low P&quot;, &quot;&quot;))</pre>
<p>Next is discrimination, how well the item differentiates between
people high and low in the trait, as measured by polyserials. We want
all of our polyserials to be positive - and we would expect that since
we reverse-coded the negatively worded items - so let’s see if any are 0
or negative. Since we probably don’t have any that are exactly 0, let’s
also include discrimination that would essentialy round down to 0.</p>
<pre>ByItem %&gt;%
  filter(disc &lt;= 0.004) %&gt;%
  select(Column, disc)
## # A tibble: 0 × 2
## # &#x2139; 2 variables: Column &lt;chr&gt;, disc &lt;dbl&gt;</pre>
<p>None of the items are negative or 0, which is good. But that doesn’t
mean they provide meaningful information. So let’s look at items with
positive, but low discrimination. We’ll use a cutoff of 0.20, or around
10% of the variance in scores.</p>
<pre>ByItem %&gt;%
  filter(disc &lt; 0.20) %&gt;%
  select(Column, disc)
## # A tibble: 1 × 2
##   Column   disc
##   &lt;chr&gt;   &lt;dbl&gt;
## 1 H4     0.0523</pre>
<p>Only one item has low discrimination: item 4 on the Sensitivity
scale, “Don’t like action movies”. This scale mostly deals with
enjoyment of the arts, such as movies, books, poetry, and dance.
Apparently sensitive people aren’t supposed to like action movies? But
since this item has minimal correlation with sensitivity, apparently you
can still be a sensitive artist who loves Die Hard.</p>
<pre>ByItem &lt;- ByItem %&gt;%
  mutate(Flag2 = ifelse(disc &lt; .20, &quot;Low Discrimination&quot;, &quot;&quot;))</pre>
<p>Let’s also look at rating scale function. Respondents have 5 options
to choose from for each statement: Strongly Disagree, Disagree, Neither
Agree nor Disagree, Agree, Strongly Agree. There’s disagreement in the
survey literature of whether agreement scales should provide a neutral
option or not, with strong arguments either way. But with psychometrics,
we typically make these types of decisions empirically - are people
using the neutral category and are they using it as intended? If so, we
keep the category. If not, we should consider revising the rating
scale.</p>
<p>Remember, we have 163 items, which gives us a lot of graphs to look
at. But we can at least make it less overwhelming by creating a grid of
each scale with all 10 (or 13, for scale B, intellect) items. I’d also
like the items to appear in order, and since the Item in the data is
alphanumeric, the 10+ item in the scale will appear after 1 instead of
9. So I’ll make a new numeric variable of item number. Then I’ll write a
function to create the charts (one for each scale using the filter
function, with a grid using facet_wrap of Item Number), and lastly,
apply them to each scale. The map function allows me use a list of
scales and apply them one-by-one to the plotting function. Note that the
list is called scale_names (plural) and the function uses scale_name
(singular).</p>
<pre>Items &lt;- Items %&gt;%
  mutate(Item_Num = substr(Item, 2, 3),
         Item_Num = as.numeric(Item_Num))

histogram_scale &lt;- function(scale_name) {
  Items %&gt;%
    filter(Name == scale_name) %&gt;%
    ggplot(aes(factor(Rating, levels = 1:5))) +
    geom_bar() +
    scale_x_discrete(drop = FALSE) +
    facet_wrap(vars(Item_Num)) +
    labs(title = scale_name, x = &quot;Rating&quot;, y = &quot;Count&quot;) +
    theme(plot.title = element_text(hjust = 0.5))
}

scale_names &lt;- unique(Items$Name)
scale_histograms &lt;- map(scale_names, histogram_scale) %&gt;% set_names(scale_names)</pre>
<p>Now I have a large list (scale_plots) containing the data for each
plot, and I can view each plot by referencing it. For instance, to view
scale B, Intellect:</p>
<pre>scale_histograms$Intellect</pre>
<div class="separator" style="clear: both;"><a href="https://i0.wp.com/blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEgQUuEqz0GXtD2MKBY1TmarOUBms7OH4_oOZHFpLoVcqQSVYbRye_rd-hpUEtihmFY-3YyQomdCAeCRltssYt0lKm5v2Prvc7uvc57csi-yWUvyIEbsYsxAixUOlYT03bvb6CyUdGvaxlOeKoQ08RWXn7IQItmNDHN8jIcYRtL_PBjsPIWDUYCByh-Y_pZc/s1558/Intellect_ScaleCounts.png?ssl=1" style="display: block; padding: 1em 0px; text-align: center;" rel="nofollow" target="_blank"><img alt="" border="0" data-original-height="1064" data-original-width="450" src="https://i1.wp.com/blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEgQUuEqz0GXtD2MKBY1TmarOUBms7OH4_oOZHFpLoVcqQSVYbRye_rd-hpUEtihmFY-3YyQomdCAeCRltssYt0lKm5v2Prvc7uvc57csi-yWUvyIEbsYsxAixUOlYT03bvb6CyUdGvaxlOeKoQ08RWXn7IQItmNDHN8jIcYRtL_PBjsPIWDUYCByh-Y_pZc/s400/Intellect_ScaleCounts.png?resize=450%2C1064&#038;ssl=1" width="450" data-recalc-dims="1" /></a></div>
<p>Across all items and scales, all response options are being used,
though in some cases strongly disagree and strongly agree aren’t heavily
used. But the bigger question is whether the rating scale is being used
as intended. That is, are people lower in the trait more likely to
select Strongly Disagree, middle of the trait more likely to select
Neither Agree nor Disagree, and so on? Our polyserial correlations tell
us some of this, and I’ll use some of the same code I did to compute
those correlations, but we can dig deeper into scale function by
visualizing that relationship. Specifically, I’d like to chart average
total score (excluding the current item) for each level of the rating
scale. If the categories are functioning properly, we should see an
increase in average score as we go up the rating scale. To create my
groups of scale graphs, I’ll do something similar as I did above.</p>
<pre>ScaleFunction &lt;- Items %&gt;%
  group_by(ID, Code) %&gt;%
  mutate(Total = sum(Rating),
         Count = sum(!is.na(Rating)),
         Score = (Total - Rating)/(Count - 1)) %&gt;%
  ungroup() %&gt;%
  group_by(Item, Rating) %&gt;%
  summarise(Code = first(Code),
            Name = first(Name),
            Item_Num = first(Item_Num),
            Score = mean(Score, na.rm = TRUE)) %&gt;%
  filter(!is.na(Rating)) %&gt;%
  ungroup()
## `summarise()` has regrouped the output.
## &#x2139; Summaries were computed grouped by Item and Rating.
## &#x2139; Output is grouped by Item.
## &#x2139; Use `summarise(.groups = &quot;drop_last&quot;)` to silence this message.
## &#x2139; Use `summarise(.by = c(Item, Rating))` for per-operation grouping
##   (`?dplyr::dplyr_by`) instead.
plot_scalefunction &lt;- function(scale_name) {
  ScaleFunction %&gt;%
    filter(Name == scale_name) %&gt;%
    ggplot(aes(Rating, Score)) +
    geom_point() +
    geom_smooth(method = &quot;lm&quot;) +
    facet_wrap(vars(Item_Num)) +
    labs(title = scale_name, x = &quot;Rating&quot;, y = &quot;Average Total Score&quot;) +
    theme(plot.title = element_text(hjust = 0.5))
}

scale_scalefunctions &lt;- map(scale_names, plot_scalefunction) %&gt;% set_names(scale_names)

scale_scalefunctions$Intellect
## `geom_smooth()` using formula = 'y ~ x'</pre>
<div class="separator" style="clear: both;"><a href="https://i1.wp.com/blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEg0l-6JCKY_AHzEbrBWS3IcWZ-VR2C4ICKIXEvqS2dS1MiGdYPo2A4UrpqAMpgY2BRjxE4JDcN0pko3Mwl8_A73S1EIiCZLZ07DEWB-iuNQcGc4qlkJgj7poLDFOoXdNDQEWABOOYGw7QgEajL89pzdISRSePEljaXixLRT1Gr98MvVKJPFK_QoG6jno-2m/s1558/Intellect_ScaleFunction.png?ssl=1" style="display: block; padding: 1em 0px; text-align: center;" rel="nofollow" target="_blank"><img alt="" border="0" data-original-height="1064" data-original-width="450" src="https://i2.wp.com/blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEg0l-6JCKY_AHzEbrBWS3IcWZ-VR2C4ICKIXEvqS2dS1MiGdYPo2A4UrpqAMpgY2BRjxE4JDcN0pko3Mwl8_A73S1EIiCZLZ07DEWB-iuNQcGc4qlkJgj7poLDFOoXdNDQEWABOOYGw7QgEajL89pzdISRSePEljaXixLRT1Gr98MvVKJPFK_QoG6jno-2m/s400/Intellect_ScaleFunction.png?resize=450%2C1064&#038;ssl=1" width="450" data-recalc-dims="1" /></a></div>
<p>The steepness of the slope is, of course, the polyserial correlation
for that item, so we could probably learn a lot from examining our
discrimination indices. But these figures show where a point on a rating
scale falls out of line - perhaps equal to or even lower than the point
below it. Going through the figures scale by scale, the following
variables show signs of scale dysfunction: A10, B1, B4, B8, D6, D8, E7,
E9, F3, H4, H9, H10, I5, J9, J10, K8, L8, M3, M6, M7, M8, M9, M10,
N7.</p>
<pre>Flag3 &lt;- list(&quot;A10&quot;, &quot;B1&quot;, &quot;B4&quot;, &quot;B8&quot;, &quot;D6&quot;, &quot;D8&quot;, &quot;E7&quot;, &quot;E9&quot;, &quot;F3&quot;, &quot;H4&quot;, &quot;H9&quot;, &quot;H10&quot;, &quot;I5&quot;, &quot;J9&quot;, &quot;J10&quot;, &quot;K8&quot;, &quot;L8&quot;, &quot;M3&quot;, &quot;M6&quot;, &quot;M7&quot;, &quot;M8&quot;, &quot;M9&quot;, &quot;M10&quot;, &quot;N7&quot;)

ByItem &lt;- ByItem %&gt;%
  mutate(Flag3 = ifelse(Column %in% Flag3, &quot;Scale Dysfunction&quot;, &quot;&quot;))</pre>
<p>Now it’s time to conduct our CFA. This isn’t necessarily required,
especially if you’re conducting item and scale analysis on an
established measure. It’s more necessary if you’re conducting the
validation study of a measure. But let’s go ahead and conduct one to be
thorough. I’ve blogged about using <a href="https://www.deeplytrivial.com/2018/04/f-is-for-confirmatory-factor-analysis.html" rel="nofollow" target="_blank">lavaan</a>
for CFA before, so check out that post for a bit more exposition. I
just need to specify my model and feed it into the cfa function.</p><pre>library(lavaan)
## This is lavaan 0.7-2
## lavaan is FREE software! Please report any bugs.
Factor16 &lt;- '
  &quot;Warmth&quot; =~ A1 + A2 + A3 + A4 + A5 + A6 + A7 + A8 + A9 + A10
  &quot;Intellect&quot; =~ B1 + B2 + B3 + B4 + B5 + B6 + B7 + B8 + B9 + B10 + B11 + B12 + B13
  &quot;EmotSta&quot; =~ C1 + C2 + C3 + C4 + C5 + C6 + C7 + C8 + C9 + C10
  &quot;Assert&quot; =~ D1 + D2 + D3 + D4 + D5 + D6 + D7 + D8 + D9 + D10
  &quot;Gregar&quot; =~ E1 + E2 + E3 + E4 + E5 + E6 + E7 + E8 + E9 + E10
  &quot;Duti&quot; =~ F1 + F2 + F3 + F4 + F5 + F6 + F7 + F8 + F9 + F10
  &quot;Friend&quot; =~ G1 + G2 + G3 + G4 + G5 + G6 + G7 + G8 + G9 + G10
  &quot;Sens&quot; =~ H1 + H2 + H3 + H4 + H5 + H6 + H7 + H8 + H9 + H10
  &quot;Dist&quot; =~ I1 + I2 + I3 + I4 + I5 + I6 + I7 + I8 + I9 + I10
  &quot;Imag&quot; =~ J1 + J2 + J3 + J4 + J5 + J6 + J7 + J8 + J9 + J10
  &quot;Reser&quot; =~ K1 + K2 + K3 + K4 + K5 + K6 + K7 + K8 + K9 + K10
  &quot;Anx&quot; =~ L1 + L2 + L3 + L4 + L5 + L6 + L7 + L8 + L9 + L10
  &quot;Complex&quot; =~ M1 + M2 + M3 + M4 + M5 + M6 + M7 + M8 + M9 + M10
  &quot;Intr&quot; =~ N1 + N2 + N3 + N4 + N5 + N6 + N7 + N8 + N9 + N10
  &quot;Order&quot; =~ O1 + O2 + O3 + O4 + O5 + O6 + O7 + O8 + O9 + O10
  &quot;Emot&quot; =~ P1 + P2 + P3 + P4 + P5 + P6 + P7 + P8 + P9 + P10
'

CFA16 &lt;- cfa(model = Factor16, data = PF16R)

summary(CFA16, fit.measures = TRUE)
## lavaan 0.7-2 ended normally after 229 iterations
## 
##   Estimator                                         ML
##   Optimization method                           NLMINB
##   Number of model parameters                       446
## 
##                                                   Used       Total
##   Number of observations                         35127       46427
## 
## Model Test User Model:
##                                                         
##   Test statistic                              825227.500
##   Degrees of freedom                               12920
##   P-value (Chi-square)                             0.000
## 
## Model Test Baseline Model:
## 
##   Test statistic                           2538331.585
##   Degrees of freedom                             13203
##   P-value                                        0.000
## 
## User Model versus Baseline Model:
## 
##   Comparative Fit Index (CFI)                    0.678
##   Tucker-Lewis Index (TLI)                       0.671
## 
## Loglikelihood and Information Criteria:
## 
##   Loglikelihood user model (H0)           -7709410.175
##   Loglikelihood unrestricted model (H1)   -7296796.425
##                                                       
##   Akaike (AIC)                            15419712.350
##   Bayesian (BIC)                          15423488.509
##   Sample-size adjusted Bayesian (SABIC)   15422071.122
## 
## Root Mean Square Error of Approximation:
## 
##   RMSEA                                          0.042
##   90 Percent confidence interval - lower         0.042
##   90 Percent confidence interval - upper         0.042
##   P-value H_0: RMSEA &lt;= 0.050                    1.000
##   P-value H_0: RMSEA &gt;= 0.080                    0.000
## 
## Standardized Root Mean Square Residual:
## 
##   SRMR                                           0.074
## 
## Goodness of Fit Index:
## 
##   Goodness of Fit Index (GFI)                    0.664
##   90 Percent confidence interval - lower         0.663
##   90 Percent confidence interval - upper         0.664
## 
## Parameter Estimates:
## 
##   Standard errors                             Standard
##   Information                                 Expected
##   Information saturated (h1) model          Structured
## 
## Latent Variables:
##                    Estimate  Std.Err  z-value  P(&gt;|z|)
##   Warmth =~                                           
##     A1                1.000                           
##     A2                0.907    0.008  116.796    0.000
##     A3                0.799    0.008   97.549    0.000
##     A4                0.819    0.008  104.850    0.000
##     A5                0.854    0.007  114.200    0.000
##     A6                0.788    0.007  108.222    0.000
##     A7                0.730    0.007  100.615    0.000
##     A8                0.620    0.009   70.406    0.000
##     A9                0.864    0.008  106.308    0.000
##     A10               0.501    0.008   60.932    0.000
##   Intellect =~                                        
##     B1                1.000                           
##     B2                1.107    0.014   76.995    0.000
##     B3                0.810    0.011   72.482    0.000
##     B4                0.887    0.010   85.535    0.000
##     B5                0.993    0.012   80.909    0.000
##     B6                0.760    0.013   59.640    0.000
##     B7                0.723    0.013   54.657    0.000
##     B8                0.692    0.012   57.775    0.000
##     B9                1.002    0.016   62.204    0.000
##     B10               1.190    0.016   75.870    0.000
##     B11               0.826    0.016   52.107    0.000
##     B12               1.136    0.014   80.092    0.000
##     B13               1.112    0.016   69.476    0.000
##   EmotSta =~                                          
##     C1                1.000                           
##     C2                1.294    0.015   84.880    0.000
##     C3                0.892    0.012   74.627    0.000
##     C4                1.007    0.014   74.003    0.000
##     C5                1.107    0.015   74.148    0.000
##     C6                1.401    0.017   82.245    0.000
##     C7                1.585    0.018   89.142    0.000
##     C8                1.568    0.018   87.897    0.000
##     C9                1.407    0.016   85.686    0.000
##     C10               1.351    0.016   86.058    0.000
##   Assert =~                                           
##     D1                1.000                           
##     D2                0.788    0.007  107.111    0.000
##     D3                0.595    0.007   82.615    0.000
##     D4                0.587    0.007   80.777    0.000
##     D5                0.832    0.006  130.873    0.000
##     D6                0.506    0.006   83.606    0.000
##     D7                0.953    0.007  134.242    0.000
##     D8                0.494    0.006   79.039    0.000
##     D9                0.787    0.007  113.375    0.000
##     D10               0.779    0.008   97.128    0.000
##   Gregar =~                                           
##     E1                1.000                           
##     E2                1.195    0.008  147.997    0.000
##     E3                0.502    0.007   76.939    0.000
##     E4                1.075    0.008  135.968    0.000
##     E5                0.389    0.005   72.376    0.000
##     E6                0.737    0.008   92.805    0.000
##     E7                0.243    0.007   34.327    0.000
##     E8                1.009    0.008  126.263    0.000
##     E9                0.182    0.007   27.905    0.000
##     E10               0.498    0.008   64.492    0.000
##   Duti =~                                             
##     F1                1.000                           
##     F2                1.281    0.014   94.733    0.000
##     F3                0.790    0.016   48.169    0.000
##     F4                1.526    0.016   97.453    0.000
##     F5                0.958    0.015   64.289    0.000
##     F6                1.485    0.015   96.367    0.000
##     F7                1.357    0.015   90.393    0.000
##     F8                0.716    0.014   52.375    0.000
##     F9                1.489    0.015   96.937    0.000
##     F10               0.864    0.012   70.283    0.000
##   Friend =~                                           
##     G1                1.000                           
##     G2                1.104    0.008  146.184    0.000
##     G3                0.850    0.008  111.975    0.000
##     G4                1.122    0.007  158.342    0.000
##     G5                1.049    0.007  157.691    0.000
##     G6                1.156    0.007  155.565    0.000
##     G7                1.003    0.007  135.526    0.000
##     G8                0.709    0.007   99.902    0.000
##     G9                1.007    0.007  137.614    0.000
##     G10               0.939    0.007  134.239    0.000
##   Sens =~                                             
##     H1                1.000                           
##     H2                0.436    0.005   89.926    0.000
##     H3                1.068    0.005  203.172    0.000
##     H4                0.072    0.006   11.678    0.000
##     H5                0.155    0.007   21.820    0.000
##     H6                0.212    0.006   36.384    0.000
##     H7                0.172    0.007   25.600    0.000
##     H8                0.397    0.006   63.360    0.000
##     H9                0.392    0.005   77.523    0.000
##     H10               0.158    0.006   26.655    0.000
##   Dist =~                                             
##     I1                1.000                           
##     I2                1.033    0.013   81.293    0.000
##     I3                0.869    0.012   74.463    0.000
##     I4                1.499    0.015   97.554    0.000
##     I5                0.780    0.012   67.351    0.000
##     I6                1.020    0.013   80.370    0.000
##     I7                1.152    0.013   90.327    0.000
##     I8                1.405    0.015   96.341    0.000
##     I9                1.124    0.012   91.269    0.000
##     I10               0.922    0.012   78.039    0.000
##   Imag =~                                             
##     J1                1.000                           
##     J2                1.328    0.014   91.827    0.000
##     J3                1.252    0.015   85.968    0.000
##     J4                1.252    0.014   90.596    0.000
##     J5                0.673    0.011   60.718    0.000
##     J6                0.659    0.011   58.507    0.000
##     J7                0.647    0.011   57.134    0.000
##     J8                0.590    0.011   53.147    0.000
##     J9                1.144    0.014   80.221    0.000
##     J10               1.058    0.014   77.027    0.000
##   Reser =~                                            
##     K1                1.000                           
##     K2                0.833    0.007  113.944    0.000
##     K3                0.767    0.007  103.698    0.000
##     K4                0.776    0.007  111.451    0.000
##     K5                0.798    0.007  121.476    0.000
##     K6                1.128    0.007  164.339    0.000
##     K7                1.087    0.007  164.699    0.000
##     K8                0.516    0.007   72.865    0.000
##     K9                0.940    0.007  134.376    0.000
##     K10               0.751    0.006  117.066    0.000
##   Anx =~                                              
##     L1                1.000                           
##     L2                0.958    0.009  106.417    0.000
##     L3                1.085    0.010  111.895    0.000
##     L4                0.923    0.008  108.930    0.000
##     L5                0.852    0.009   96.666    0.000
##     L6                0.700    0.009   74.979    0.000
##     L7                0.908    0.009  102.565    0.000
##     L8                0.835    0.009   88.412    0.000
##     L9                0.855    0.009   97.660    0.000
##     L10               0.885    0.009  101.337    0.000
##   Complex =~                                          
##     M1                1.000                           
##     M2                0.899    0.015   60.116    0.000
##     M3                0.801    0.012   65.360    0.000
##     M4                1.068    0.017   64.564    0.000
##     M5                0.625    0.015   40.985    0.000
##     M6                1.515    0.021   71.353    0.000
##     M7                1.190    0.019   62.960    0.000
##     M8                1.453    0.021   70.317    0.000
##     M9                1.235    0.018   68.609    0.000
##     M10               1.212    0.019   64.739    0.000
##   Intr =~                                             
##     N1                1.000                           
##     N2                0.775    0.007  108.927    0.000
##     N3                0.727    0.006  119.027    0.000
##     N4                0.936    0.007  131.165    0.000
##     N5                0.593    0.008   77.295    0.000
##     N6                0.761    0.007  107.645    0.000
##     N7                0.560    0.005  102.222    0.000
##     N8                0.727    0.007  107.999    0.000
##     N9                0.719    0.008   95.143    0.000
##     N10               0.623    0.008   78.019    0.000
##   Order =~                                            
##     O1                1.000                           
##     O2                2.543    0.050   50.422    0.000
##     O3                1.703    0.035   48.881    0.000
##     O4                1.518    0.034   45.129    0.000
##     O5                1.368    0.030   45.559    0.000
##     O6                1.773    0.039   46.024    0.000
##     O7                1.921    0.041   47.273    0.000
##     O8                3.013    0.059   51.243    0.000
##     O9                2.347    0.048   49.026    0.000
##     O10               1.887    0.039   47.884    0.000
##   Emot =~                                             
##     P1                1.000                           
##     P2                0.940    0.006  163.104    0.000
##     P3                0.530    0.006   88.216    0.000
##     P4                0.512    0.006   89.093    0.000
##     P5                0.437    0.005   84.117    0.000
##     P6                0.484    0.006   81.521    0.000
##     P7                0.396    0.006   63.895    0.000
##     P8                0.846    0.006  148.026    0.000
##     P9                0.435    0.006   76.558    0.000
##     P10               0.394    0.006   68.305    0.000
## 
## Covariances:
##                    Estimate  Std.Err  z-value  P(&gt;|z|)
##   Warmth ~~                                           
##     Intellect         0.045    0.002   19.331    0.000
##     EmotSta           0.119    0.003   40.813    0.000
##     Assert            0.139    0.004   36.779    0.000
##     Gregar            0.311    0.005   65.131    0.000
##     Duti              0.117    0.003   40.744    0.000
##     Friend            0.376    0.005   77.040    0.000
##     Sens              0.034    0.005    7.444    0.000
##     Dist             -0.225    0.004  -59.546    0.000
##     Imag             -0.034    0.003  -12.601    0.000
##     Reser            -0.369    0.005  -72.007    0.000
##     Anx              -0.035    0.003  -10.163    0.000
##     Complex           0.084    0.002   34.019    0.000
##     Intr             -0.297    0.005  -63.609    0.000
##     Order             0.031    0.002   20.261    0.000
##     Emot             -0.267    0.005  -53.438    0.000
##   Intellect ~~                                        
##     EmotSta           0.090    0.002   42.220    0.000
##     Assert            0.197    0.003   60.419    0.000
##     Gregar           -0.023    0.003   -8.550    0.000
##     Duti             -0.026    0.002  -14.976    0.000
##     Friend            0.063    0.003   24.553    0.000
##     Sens              0.232    0.004   58.667    0.000
##     Dist              0.006    0.002    3.482    0.000
##     Imag              0.056    0.002   28.282    0.000
##     Reser            -0.029    0.003  -10.569    0.000
##     Anx              -0.114    0.003  -41.711    0.000
##     Complex           0.163    0.003   55.379    0.000
##     Intr              0.074    0.003   27.102    0.000
##     Order             0.031    0.001   26.585    0.000
##     Emot             -0.086    0.003  -26.908    0.000
##   EmotSta ~~                                          
##     Assert            0.211    0.004   56.972    0.000
##     Gregar            0.132    0.003   39.308    0.000
##     Duti              0.072    0.002   33.265    0.000
##     Friend            0.247    0.004   61.511    0.000
##     Sens             -0.018    0.004   -5.172    0.000
##     Dist             -0.156    0.003  -51.590    0.000
##     Imag             -0.104    0.003  -41.240    0.000
##     Reser            -0.155    0.004  -43.925    0.000
##     Anx              -0.376    0.005  -68.570    0.000
##     Complex           0.036    0.002   20.334    0.000
##     Intr             -0.146    0.003  -43.165    0.000
##     Order             0.048    0.001   32.170    0.000
##     Emot             -0.359    0.005  -66.888    0.000
##   Assert ~~                                           
##     Gregar            0.235    0.005   51.078    0.000
##     Duti             -0.020    0.003   -7.516    0.000
##     Friend            0.370    0.005   75.878    0.000
##     Sens              0.047    0.005    9.370    0.000
##     Dist             -0.024    0.003   -8.180    0.000
##     Imag             -0.059    0.003  -19.623    0.000
##     Reser            -0.219    0.005  -47.302    0.000
##     Anx              -0.277    0.005  -60.925    0.000
##     Complex           0.106    0.003   38.450    0.000
##     Intr             -0.132    0.004  -31.046    0.000
##     Order             0.078    0.002   36.130    0.000
##     Emot             -0.040    0.005   -8.186    0.000
##   Gregar ~~                                           
##     Duti             -0.020    0.003   -6.772    0.000
##     Friend            0.538    0.006   88.407    0.000
##     Sens             -0.184    0.006  -33.177    0.000
##     Dist             -0.140    0.004  -39.876    0.000
##     Imag             -0.016    0.003   -4.913    0.000
##     Reser            -0.345    0.005  -63.469    0.000
##     Anx              -0.141    0.004  -32.927    0.000
##     Complex           0.016    0.003    6.375    0.000
##     Intr             -0.485    0.006  -79.410    0.000
##     Order            -0.015    0.002   -9.087    0.000
##     Emot             -0.093    0.005  -17.515    0.000
##   Duti ~~                                             
##     Friend            0.056    0.003   19.773    0.000
##     Sens             -0.023    0.004   -6.588    0.000
##     Dist             -0.126    0.003  -47.210    0.000
##     Imag             -0.158    0.003  -53.202    0.000
##     Reser            -0.076    0.003  -24.417    0.000
##     Anx              -0.007    0.003   -2.646    0.008
##     Complex          -0.068    0.002  -34.325    0.000
##     Intr             -0.082    0.003  -27.119    0.000
##     Order             0.075    0.002   39.158    0.000
##     Emot             -0.146    0.004  -38.826    0.000
##   Friend ~~                                           
##     Sens             -0.073    0.005  -14.513    0.000
##     Dist             -0.211    0.004  -56.194    0.000
##     Imag             -0.114    0.003  -35.699    0.000
##     Reser            -0.482    0.006  -83.318    0.000
##     Anx              -0.271    0.005  -59.695    0.000
##     Complex           0.057    0.002   22.944    0.000
##     Intr             -0.452    0.006  -80.620    0.000
##     Order             0.042    0.002   23.978    0.000
##     Emot             -0.247    0.005  -47.273    0.000
##   Sens ~~                                             
##     Dist              0.005    0.004    1.229    0.219
##     Imag              0.173    0.004   41.725    0.000
##     Reser             0.033    0.006    6.045    0.000
##     Anx               0.006    0.005    1.219    0.223
##     Complex           0.229    0.004   53.692    0.000
##     Intr              0.252    0.006   44.922    0.000
##     Order             0.003    0.002    1.718    0.086
##     Emot             -0.072    0.006  -11.450    0.000
##   Dist ~~                                             
##     Imag              0.094    0.003   37.328    0.000
##     Reser             0.268    0.004   60.801    0.000
##     Anx               0.143    0.003   43.392    0.000
##     Complex          -0.010    0.002   -5.710    0.000
##     Intr              0.229    0.004   56.477    0.000
##     Order            -0.018    0.001  -14.858    0.000
##     Emot              0.318    0.005   63.357    0.000
##   Imag ~~                                             
##     Reser             0.087    0.003   25.777    0.000
##     Anx               0.118    0.003   37.386    0.000
##     Complex           0.135    0.003   48.962    0.000
##     Intr              0.170    0.004   46.729    0.000
##     Order            -0.076    0.002  -38.556    0.000
##     Emot              0.118    0.004   30.514    0.000
##   Reser ~~                                            
##     Anx               0.114    0.004   26.597    0.000
##     Complex          -0.056    0.003  -20.535    0.000
##     Intr              0.401    0.006   70.747    0.000
##     Order            -0.026    0.002  -14.528    0.000
##     Emot              0.171    0.006   30.948    0.000
##   Anx ~~                                              
##     Complex          -0.056    0.002  -23.138    0.000
##     Intr              0.138    0.004   32.817    0.000
##     Order            -0.038    0.002  -22.601    0.000
##     Emot              0.459    0.006   73.932    0.000
##   Complex ~~                                          
##     Intr              0.039    0.003   15.348    0.000
##     Order            -0.009    0.001   -9.319    0.000
##     Emot             -0.103    0.003  -31.667    0.000
##   Intr ~~                                             
##     Order            -0.006    0.002   -3.931    0.000
##     Emot              0.218    0.005   40.239    0.000
##   Order ~~                                            
##     Emot             -0.044    0.002  -20.728    0.000
## 
## Variances:
##                    Estimate  Std.Err  z-value  P(&gt;|z|)
##    .A1                0.590    0.005  116.592    0.000
##    .A2                0.463    0.004  115.829    0.000
##    .A3                0.693    0.006  123.897    0.000
##    .A4                0.573    0.005  121.544    0.000
##    .A5                0.452    0.004  117.342    0.000
##    .A6                0.473    0.004  120.215    0.000
##    .A7                0.524    0.004  122.985    0.000
##    .A8                1.025    0.008  129.023    0.000
##    .A9                0.608    0.005  120.991    0.000
##    .A10               0.948    0.007  130.051    0.000
##    .B1                0.558    0.005  122.992    0.000
##    .B2                0.731    0.006  123.616    0.000
##    .B3                0.491    0.004  125.438    0.000
##    .B4                0.292    0.002  118.132    0.000
##    .B5                0.477    0.004  121.535    0.000
##    .B6                0.800    0.006  128.707    0.000
##    .B7                0.920    0.007  129.524    0.000
##    .B8                0.725    0.006  129.034    0.000
##    .B9                1.230    0.010  128.209    0.000
##    .B10               0.895    0.007  124.119    0.000
##    .B11               1.360    0.010  129.878    0.000
##    .B12               0.654    0.005  122.019    0.000
##    .B13               1.072    0.008  126.409    0.000
##    .C1                1.000    0.008  128.625    0.000
##    .C2                0.654    0.005  122.467    0.000
##    .C3                0.639    0.005  127.664    0.000
##    .C4                0.845    0.007  127.844    0.000
##    .C5                1.013    0.008  127.803    0.000
##    .C6                0.947    0.008  124.395    0.000
##    .C7                0.652    0.006  117.267    0.000
##    .C8                0.728    0.006  119.182    0.000
##    .C9                0.722    0.006  121.731    0.000
##    .C10               0.644    0.005  121.360    0.000
##    .D1                0.410    0.004  105.119    0.000
##    .D2                0.755    0.006  123.351    0.000
##    .D3                0.837    0.007  127.820    0.000
##    .D4                0.859    0.007  128.066    0.000
##    .D5                0.454    0.004  115.444    0.000
##    .D6                0.586    0.005  127.682    0.000
##    .D7                0.544    0.005  113.808    0.000
##    .D8                0.641    0.005  128.290    0.000
##    .D9                0.640    0.005  121.729    0.000
##    .D10               0.958    0.008  125.477    0.000
##    .E1                0.585    0.005  112.127    0.000
##    .E2                0.573    0.006  102.590    0.000
##    .E3                0.817    0.006  128.902    0.000
##    .E4                0.694    0.006  112.680    0.000
##    .E5                0.567    0.004  129.391    0.000
##    .E6                1.103    0.009  126.725    0.000
##    .E7                1.110    0.008  131.905    0.000
##    .E8                0.815    0.007  117.714    0.000
##    .E9                0.952    0.007  132.121    0.000
##    .E10               1.211    0.009  130.122    0.000
##    .F1                0.840    0.007  126.688    0.000
##    .F2                0.417    0.004  113.030    0.000
##    .F3                2.153    0.016  131.109    0.000
##    .F4                0.446    0.004  106.579    0.000
##    .F5                1.433    0.011  129.389    0.000
##    .F6                0.476    0.004  109.547    0.000
##    .F7                0.671    0.006  118.994    0.000
##    .F8                1.429    0.011  130.771    0.000
##    .F9                0.450    0.004  108.066    0.000
##    .F10               0.869    0.007  128.323    0.000
##    .G1                0.426    0.004  117.899    0.000
##    .G2                0.728    0.006  122.143    0.000
##    .G3                0.962    0.008  127.879    0.000
##    .G4                0.559    0.005  118.510    0.000
##    .G5                0.497    0.004  118.740    0.000
##    .G6                0.636    0.005  119.461    0.000
##    .G7                0.773    0.006  124.456    0.000
##    .G8                0.895    0.007  129.064    0.000
##    .G9                0.741    0.006  124.052    0.000
##    .G10               0.697    0.006  124.695    0.000
##    .H1                0.194    0.004   47.101    0.000
##    .H2                0.752    0.006  128.930    0.000
##    .H3                0.344    0.005   66.883    0.000
##    .H4                1.314    0.010  132.473    0.000
##    .H5                1.753    0.013  132.336    0.000
##    .H6                1.173    0.009  131.990    0.000
##    .H7                1.560    0.012  132.263    0.000
##    .H8                1.315    0.010  130.839    0.000
##    .H9                0.834    0.006  129.930    0.000
##    .H10               1.222    0.009  132.241    0.000
##    .I1                0.962    0.008  126.938    0.000
##    .I2                0.760    0.006  124.967    0.000
##    .I3                0.783    0.006  127.345    0.000
##    .I4                0.428    0.004  104.018    0.000
##    .I5                0.905    0.007  128.913    0.000
##    .I6                0.782    0.006  125.363    0.000
##    .I7                0.517    0.004  118.647    0.000
##    .I8                0.437    0.004  107.988    0.000
##    .I9                0.456    0.004  117.546    0.000
##    .I10               0.727    0.006  126.246    0.000
##    .J1                0.817    0.007  122.881    0.000
##    .J2                0.582    0.005  108.442    0.000
##    .J3                0.787    0.007  116.769    0.000
##    .J4                0.570    0.005  110.701    0.000
##    .J5                0.849    0.007  128.340    0.000
##    .J6                0.906    0.007  128.764    0.000
##    .J7                0.932    0.007  129.006    0.000
##    .J8                0.944    0.007  129.632    0.000
##    .J9                0.923    0.008  121.356    0.000
##    .J10               0.939    0.008  123.139    0.000
##    .K1                0.552    0.005  114.506    0.000
##    .K2                0.980    0.008  125.535    0.000
##    .K3                1.074    0.008  127.126    0.000
##    .K4                0.905    0.007  125.957    0.000
##    .K5                0.747    0.006  124.095    0.000
##    .K6                0.470    0.004  105.537    0.000
##    .K7                0.432    0.004  105.217    0.000
##    .K8                1.146    0.009  130.236    0.000
##    .K9                0.752    0.006  120.881    0.000
##    .K10               0.737    0.006  124.970    0.000
##    .L1                0.827    0.007  122.550    0.000
##    .L2                0.728    0.006  122.121    0.000
##    .L3                0.748    0.006  119.483    0.000
##    .L4                0.612    0.005  121.010    0.000
##    .L5                0.830    0.007  125.339    0.000
##    .L6                1.209    0.009  129.213    0.000
##    .L7                0.759    0.006  123.570    0.000
##    .L8                1.071    0.008  127.183    0.000
##    .L9                0.806    0.006  125.072    0.000
##    .L10               0.754    0.006  123.978    0.000
##    .M1                0.946    0.007  127.367    0.000
##    .M2                0.655    0.005  126.498    0.000
##    .M3                0.344    0.003  123.375    0.000
##    .M4                0.653    0.005  123.979    0.000
##    .M5                1.116    0.009  130.827    0.000
##    .M6                0.669    0.006  115.570    0.000
##    .M7                0.924    0.007  125.032    0.000
##    .M8                0.696    0.006  117.557    0.000
##    .M9                0.604    0.005  120.094    0.000
##    .M10               0.830    0.007  123.851    0.000
##    .N1                0.639    0.006  113.871    0.000
##    .N2                0.692    0.006  122.230    0.000
##    .N3                0.451    0.004  118.559    0.000
##    .N4                0.504    0.005  111.790    0.000
##    .N5                1.046    0.008  128.549    0.000
##    .N6                0.693    0.006  122.614    0.000
##    .N7                0.440    0.004  124.078    0.000
##    .N8                0.626    0.005  122.509    0.000
##    .N9                0.892    0.007  125.668    0.000
##    .N10               1.127    0.009  128.456    0.000
##    .O1                0.922    0.007  129.814    0.000
##    .O2                0.804    0.007  112.203    0.000
##    .O3                0.561    0.005  119.511    0.000
##    .O4                0.898    0.007  126.096    0.000
##    .O5                0.683    0.005  125.654    0.000
##    .O6                1.065    0.009  125.120    0.000
##    .O7                1.004    0.008  123.295    0.000
##    .O8                0.808    0.008  104.138    0.000
##    .O9                1.028    0.009  119.036    0.000
##    .O10               0.859    0.007  122.110    0.000
##    .P1                0.401    0.004   90.771    0.000
##    .P2                0.582    0.005  107.074    0.000
##    .P3                0.983    0.008  127.851    0.000
##    .P4                0.899    0.007  127.744    0.000
##    .P5                0.746    0.006  128.331    0.000
##    .P6                0.980    0.008  128.617    0.000
##    .P7                1.118    0.009  130.233    0.000
##    .P8                0.657    0.006  114.394    0.000
##    .P9                0.912    0.007  129.128    0.000
##    .P10               0.958    0.007  129.879    0.000
##     Warmth            0.527    0.008   69.795    0.000
##     Intellect         0.233    0.005   51.196    0.000
##     EmotSta           0.314    0.007   46.901    0.000
##     Assert            0.622    0.008   82.607    0.000
##     Gregar            0.731    0.009   78.463    0.000
##     Duti              0.317    0.006   50.255    0.000
##     Friend            0.675    0.008   86.162    0.000
##     Sens              1.089    0.010  105.517    0.000
##     Dist              0.355    0.007   49.784    0.000
##     Imag              0.337    0.007   50.792    0.000
##     Reser             0.805    0.010   83.324    0.000
##     Anx               0.587    0.009   65.016    0.000
##     Complex           0.214    0.005   39.193    0.000
##     Intr              0.702    0.009   75.082    0.000
##     Order             0.093    0.004   26.438    0.000
##     Emot              0.994    0.011   93.936    0.000</pre>
<p>The fit statistics mostly indicate poor fit. Our comparative fit
indices, CFI = 0.678, TLI = 0.671, should be much higher, preferably in
the 0.9 range. And GFI (0.664), a measure of absolute fit, is similarly
low. But RMSEA, 0.042, is good, and SRMR (0.074) is acceptable. There a
few potential issues that could explain poor fit, including the fact our
observed variables aren’t normally distributed, but before we try a
different estimation method or way of dealing with missing data, let’s
look at what the model is telling us. All items load onto their factor
significantly and positively. Factors are correlated with each other,
except sensitivity and distrust, sensitivity and anxiety, and
sensitivity and orderliness. Let’s extract parameter estimates, as
well as standardized estimates, so we can dig in a bit more. Remember
that for the unstandardized solution, the factors (the latent variables
in our model) don’t have a metric, so the first item (observed
variables) is always loaded at 1 to set the range. If we want to see how
strongly that item loads on a factor, you’ll want the standardized
values.</p>
<pre>parameters &lt;- parameterEstimates(CFA16)
standardizedsol &lt;- standardizedSolution(CFA16)

unstandardized &lt;- parameters[c(1:163), 4]
standardized &lt;- standardizedsol[c(1:163), 4]

ByItem &lt;- cbind(ByItem, unstandardized, standardized)

summary(ByItem$standardized)
##    Min. 1st Qu.  Median    Mean 3rd Qu.    Max. 
## 0.06515 0.44843 0.56886 0.55692 0.68524 0.92115</pre>
<p>We have at least one factor loading that is quite low - about 0.07
standardized loading. Turns out, that’s item H4, the action movie item
from the Sensitivity scale that we also flagged for low P, low
discrimination, and poor scale function. Every indicator we’ve examined
has show this item doesn’t really relate to the concept of
“Sensitivity.” In fact, our four lowest factor ratings all belong to the
Sensitivity scale. This scale also had our worst alpha. My
recommendation would be, at the very least, to drop the 4th item from
Sensitivity and rerun alpha.</p>
<pre>Scores &lt;- Items %&gt;%
  filter(Item != &quot;H4&quot;) %&gt;%
  ungroup() %&gt;%
  group_by(ID, Code) %&gt;%
  summarise(Total = sum(Rating, na.rm = TRUE),
            NItems = sum(!is.na(Rating))) %&gt;%
  ungroup() %&gt;%
  left_join(Scales, by = &quot;Code&quot;) %&gt;%
  mutate(Items = ifelse(Name == &quot;Sensitivity&quot;, 9, Items),
         Score = Total/NItems,
         CorTotal = Score*Items) 
## `summarise()` has regrouped the output.
## &#x2139; Summaries were computed grouped by ID and Code.
## &#x2139; Output is grouped by ID.
## &#x2139; Use `summarise(.groups = &quot;drop_last&quot;)` to silence this message.
## &#x2139; Use `summarise(.by = c(ID, Code))` for per-operation grouping
##   (`?dplyr::dplyr_by`) instead.
ByScale &lt;- Scores %&gt;%
  group_by(Code) %&gt;%
  summarise(Variance = var(CorTotal, na.rm = TRUE))

ByScale2 &lt;- ByItem %&gt;%
  ungroup() %&gt;%
  mutate(Code = substr(Column, 1, 1)) %&gt;%
  group_by(Code) %&gt;%
  summarise(EItemVar = sum(Variance))

Scales &lt;- Scales %&gt;%
  left_join(ByScale, by = &quot;Code&quot;) %&gt;%
  left_join(ByScale2, by = &quot;Code&quot;)

Scales &lt;- Scales %&gt;%
  mutate(Items.y = ifelse(Name == &quot;Sensitivity&quot;, 9, Items),
         Alpha.y = (Items.y/(Items.y-1)) * (1 - (EItemVar.y/Variance.y)))</pre>
<p>Removing H4 actually makes alpha go down. Remember, though, that
alpha rewards longer measures (more items increase reliability in CTT),
so any gain from removing a poor item could be lost because now the
measure is shorter. We could drop Sensitivity fully from the measure,
but then that would break the factor structure Cattell theorized that
included this concept of Sensitivity. If full removal is unacceptable,
then the Sensitivity scale probably needs an overhaul with edited/new
items.</p>
<p>Note that, while I said our CFA could handle some missing data, the
estimation method (maximum likelihood, the default) uses only complete
cases. An estimation method that allows missing data might get better
results. Further, our data is not normally distributed, another
requirement of this estimation method. So we want a different estimator
that can handle some missing data and that works with nonnormal data.
This
<a href="https://pmc.ncbi.nlm.nih.gov/articles/PMC10326553/" rel="nofollow" target="_blank">paper</a>
recommends a weighted least squares method with rating scale items
entered as ordinal. This approach definitely makes sense, but fair
warning, this approach will use a lot of memory (to store the many
matrices) and will take a while to run, especially if you don’t have a
lot of RAM and/or are running programs like RStudio that use a lot of
RAM. My current system has 48 gigs of RAM, but on my previous 16 gig
system, I would sometimes need to close RStudio and run my code directly
in R.</p>
<p>This is the code I ran: CFA2 <- cfa(model = Factor16, data =
PF16R, ordered = TRUE, estimator = “WLSMV”)</p>
<p>Why am I telling you instead of showing you? Unfortunately, this
analysis took over 1.5 hours and found similar results as the ML
estimation model: fit statistics were in the 0.5-0.6 range, lack of
correlation between Sensitivity and multiple other scales, and H4 had
the lowest loading. So the issue isn’t that the data aren’t normally
distributed. The issue is that the prescribed model does not fit the
data well.</p>
<p>So, out of pure curiosity, I’m going to do something I typically do
not recommend. I’m going to run an exploratory factor analysis, asking
it to derive up to 16 factors. Normally I do not condone this kind of
fishing. If you expect certain items to load on certain factors, you
should use CFA. And if your CFA doesn’t work out, you should have some
backup options - a different estimator, a different arrangement of
factors, or even just accepting that your theoretical model isn’t it.
But I don’t want to use this approach to see how the items should fall,
to try to develop a new measure or personality theory. I want to use it
for diagnosis - where do things fall apart? Do we have a small number of
problem factors, or is the issue more widespread than that?</p>
<p>EFA in lavaan allows you to specify a number of factors, or even a
range of factors, to extract. I definitely want to see what it does with
the 16 factor solution. We could compare that to another personality
theory, Big Five, which states that personality is made up of five
independent but correlated factors: Openness to Experience,
Conscientiousness, Extraversion, Agreeableness, and Emotional Stability.
I could see how some of the 16 factors could map onto the Big Five, but
the one exception I see is Imagination. It doesn’t have a clear place
among the Big Five, and seems to be a unique contribution by Cattell. So
let’s see what happens if I ask the EFA to extract 5, 6, and 16
factors.</p>
<pre>ItemList &lt;- grep(&quot;^[A-Za-z][0-9]+$&quot;, colnames(PF16R), value = TRUE)

EFA &lt;- efa(data = PF16R, nfactors = c(5, 6, 16), rotation = &quot;varimax&quot;, ov_names = ItemList)</pre>
<p>I’ll start by looking at the 16 factor solution.</p>
<pre>summary(EFA$nf16, fit.measures = TRUE)
## lavaan 0.7-2 ended normally after 1 iteration
## 
##   Estimator                                         ML
##   Optimization method                           NLMINB
##   Number of model parameters                      2771
##   Row rank of the constraints matrix               283
## 
##   Rotation method                   VARIMAX ORTHOGONAL
##   Rotation algorithm (rstarts)                GPA (30)
##   Standardized metric                             TRUE
##   Row weights                                   Kaiser
## 
##                                                   Used       Total
##   Number of observations                         35127       46427
## 
## Model Test User Model:
##                                                         
##   Test statistic                              261484.745
##   Degrees of freedom                               10715
##   P-value (Chi-square)                             0.000
## 
## Model Test Baseline Model:
## 
##   Test statistic                           2538331.585
##   Degrees of freedom                             13203
##   P-value                                        0.000
## 
## User Model versus Baseline Model:
## 
##   Comparative Fit Index (CFI)                    0.901
##   Tucker-Lewis Index (TLI)                       0.878
## 
## Loglikelihood and Information Criteria:
## 
##   Loglikelihood user model (H0)           -7427538.797
##   Loglikelihood unrestricted model (H1)   -7296796.425
##                                                       
##   Akaike (AIC)                            14860379.594
##   Bayesian (BIC)                          14882824.883
##   Sample-size adjusted Bayesian (SABIC)   14874400.014
## 
## Root Mean Square Error of Approximation:
## 
##   RMSEA                                          0.026
##   90 Percent confidence interval - lower         0.026
##   90 Percent confidence interval - upper         0.026
##   P-value H_0: RMSEA &lt;= 0.050                    1.000
##   P-value H_0: RMSEA &gt;= 0.080                    0.000
## 
## Standardized Root Mean Square Residual:
## 
##   SRMR                                           0.015
## 
## Goodness of Fit Index:
## 
##   Goodness of Fit Index (GFI)                    0.899
##   90 Percent confidence interval - lower         0.899
##   90 Percent confidence interval - upper         0.900
## 
## Standardized loadings: (* = significant at 1% level)
## 
##         f1      f2      f3      f4      f5      f6      f7      f8      f9 
## A1   0.591*      .*       *       *       *      .*               *       *
## A2   0.502*       *      .*       *       *  0.357*       *      .*      .*
## A3   0.612*               *       *      .*       *               *      .*
## A4   0.489*               *       *       *      .*               *      .*
## A5   0.532*       *      .*       *      .*  0.363*               *      .*
## A6   0.510*       *      .*       *      .*  0.319*               *      .*
## A7   0.517*       *      .*      .*              .*       *       *      .*
## A8       .*       *               *       *      .*               *      .*
## A9   0.490*       *       *       *       *      .*       *       *      .*
## A10  0.359*       *       *       *       *       *               *       *
## B1        *      .*       *       *       *               *               *
## B2       .*      .*      .*       *       *               *               *
## B3        *      .*               *       *       *       *       *       *
## B4        *      .*       *       *      .*       *       *                
## B5        *      .*       *              .*       *       *       *       *
## B6       .*      .*      .*      .*       *       *               *      .*
## B7        *       *       *      .*      .*      .*       *       *       *
## B8        *      .*       *      .*      .*       *               *       *
## B9        *      .*      .*      .*      .*       *       *               *
## B10       *      .*       *       *  0.439*       *       *      .*       *
## B11       *      .*      .*       *      .*      .*       *       *       *
## B12       *       *      .*              .*              .*      .*       *
## B13       *       *       *              .*       *      .*      .*       *
## C1        *                       *  0.445*       *       *               *
## C2       .*      .*       *       *  0.615*      .*       *      .*      .*
## C3       .*      .*       *          0.465*       *               *       *
## C4        *       *      .*       *  0.514*       *       *      .*      .*
## C5        *       *       *       *  0.492*                       *      .*
## C6        *       *              .*  0.591*       *       *      .*      .*
## C7        *                      .*  0.680*      .*       *       *      .*
## C8       .*       *      .*       *  0.661*      .*       *       *      .*
## C9        *       *       *      .*  0.652*      .*       *      .*       *
## C10       *      .*       *          0.664*      .*       *       *       *
## D1        *  0.668*       *       *      .*      .*       *       *        
## D2        *  0.574*       *                      .*       *       *       *
## D3        *  0.324*      .*      .*      .*      .*       *       *       *
## D4       .*  0.336*      .*       *      .*      .*               *       *
## D5        *  0.616*               *      .*      .*       *       *       *
## D6        *  0.385*      .*       *      .*       *              .*       *
## D7        *  0.518*       *       *  0.322*      .*       *       *       *
## D8        *      .*       *      .*      .*       *       *       *       *
## D9           0.469*      .*       *      .*      .*               *       *
## D10       *      .*       *       *  0.471*      .*       *       *       *
## E1       .*      .*       *       *      .*  0.667*       *      .*       *
## E2        *       *      .*       *      .*  0.617*       *      .*       *
## E3       .*          0.474*       *          0.315*       *      .*       *
## E4        *       *      .*       *       *  0.550*              .*      .*
## E5       .*       *  0.398*               *  0.322*       *       *        
## E6        *       *      .*      .*       *  0.395*       *  0.372*       *
## E7       .*       *  0.311*       *       *      .*       *      .*        
## E8        *       *       *       *      .*  0.516*       *      .*      .*
## E9        *              .*              .*      .*               *       *
## E10       *       *      .*       *              .*       *      .*       *
## F1               .*          0.521*       *               *       *       *
## F2       .*               *  0.731*       *       *       *       *      .*
## F3       .*       *       *      .*       *       *              .*       *
## F4       .*       *       *  0.747*       *       *       *       *      .*
## F5       .*      .*       *  0.339*      .*      .*               *      .*
## F6       .*       *       *  0.738*       *       *       *       *      .*
## F7        *      .*      .*  0.646*       *       *              .*      .*
## F8        *       * -0.347*      .*      .*       *       *              .*
## F9       .*       *          0.742*       *       *       *       *      .*
## F10       *      .*      .*  0.409*       *       *              .*      .*
## G1       .*      .*       *       *  0.306*  0.591*       *              .*
## G2       .*       *       *       *      .*  0.694*               *       *
## G3        *      .*               *      .*  0.538*       *      .*       *
## G4       .*       *       *       *      .*  0.659*               *      .*
## G5       .*      .*       *              .*  0.653*       *       *       *
## G6       .*      .*       *       *  0.341*  0.619*       *      .*       *
## G7       .*       *       *       *  0.357*  0.521*       *       *      .*
## G8       .*      .*               *      .*  0.407*              .*        
## G9        *      .*       *       *      .*  0.617*              .*       *
## G10       *      .*       *       *      .*  0.583*       *       *       *
## H1        *               *       *               *  0.783*               *
## H2       .*       *       *       *       *       *  0.304*      .*       *
## H3        *       *       *                      .*  0.771*                
## H4                *      .*       *      .*       *       *      .*        
## H5   0.320*       *      .*       *      .*       *      .*       *       *
## H6   0.385*       *      .*       *       *       *      .*      .*       *
## H7       .*       *      .*       *       *      .*       *      .*       *
## H8       .*       *      .*       *       *       *      .*      .*        
## H9        *      .*       *       *       *       *      .*       *       *
## H10      .*       *       *       *                              .*       *
## I1       .*       *               *      .*       *       *          0.392*
## I2        *       *       *      .*      .*       *       *      .*  0.494*
## I3        *       *       *       *      .*      .*       *      .*  0.390*
## I4       .*       *       *      .*      .*      .*               *  0.687*
## I5        *       *       *       *      .*       *       *      .*  0.357*
## I6       .*       *              .*      .*       *              .*  0.477*
## I7       .*       *       *      .*       *      .*               *  0.677*
## I8       .*       *       *      .*      .*      .*               *  0.704*
## I9       .*               *      .*      .*       *               *  0.633*
## I10      .*       *       *      .*       *       *       *       *  0.505*
## J1        *       *      .*      .*      .*       *          0.366*      .*
## J2        *      .*              .*      .*      .*       *  0.305*       *
## J3        *       *       *      .*      .*       *       *  0.465*       *
## J4        *      .*       *      .*      .*       *          0.407*       *
## J5               .*       * -0.303*       *                      .*      .*
## J6       .*      .*       * -0.346*      .*                      .*      .*
## J7        *      .*      .* -0.301*       *      .*          0.398*       *
## J8        *       *         -0.559*       *       *       *       *       *
## J9                *       *       *      .*       *       *      .*       *
## J10       *       *       *      .*      .*      .*       *       *       *
## K1       .*                       *       *      .*       *       *      .*
## K2       .*       *       *      .*      .* -0.378*       *      .*      .*
## K3       .*      .*       *       *       * -0.602*              .*       *
## K4        *       *      .*       * -0.337*      .*               *      .*
## K5        *      .*               *      .*      .*       *      .*       *
## K6       .*       *       *       *       *      .*               *      .*
## K7       .*       *       *       *       *      .*       *       *      .*
## K8        *       *       *       *       *      .*       *       *       *
## K9       .*       *       *       *       *      .*       *       *      .*
## K10      .*       *               *       *      .*       *       *      .*
## L1        *      .*       *       * -0.586*      .*       *       *       *
## L2        *       *       *         -0.622*      .*       *       *      .*
## L3       .*       *       *         -0.648*       *       *       *        
## L4       .*       *       *       * -0.616*       *       *       *      .*
## L5        *       *       *       * -0.557*       *       *       *       *
## L6       .*      .*              .* -0.410*       *                      .*
## L7        *       *       *         -0.586*       *       *       *       *
## L8        *       *       *       * -0.484*       *       *      .*       *
## L9        *               *         -0.551*       *       *       *       *
## L10       *      .*       *         -0.604*       *              .*       *
## M1       .*       *      .*       *       *       *      .*      .*       *
## M2       .*      .*       *      .*      .*      .*       *  0.320*       *
## M3       .*       *       *       *      .*       *       *      .*       *
## M4        *      .*              .*       *      .*       *       *       *
## M5       .*       *       *      .*      .*      .*       *      .*       *
## M6                *       *      .*       *                      .*        
## M7       .*               *       *       *       *       *               *
## M8        *                       *       *       *       *       *        
## M9        *       *       *      .*       *       *       *      .*       *
## M10       *       *       *      .*       *       *       *       *        
## N1       .*               *       *      .* -0.301*       *       *      .*
## N2       .*      .*       *       *      .*      .*       *      .*      .*
## N3        *       *                       *      .*       *       *       *
## N4        *       *       *              .* -0.387*       *               *
## N5        *               *       *       *      .*               *       *
## N6        *       *       *       *              .*       *       *       *
## N7                        *       *       *      .*               *      .*
## N8       .*              .*      .*      .* -0.423*              .*      .*
## N9       .*       *       *      .*      .*      .*       *      .*      .*
## N10      .*       *       *       *      .*      .*               *      .*
## O1        *      .*              .*      .*       *       *       *       *
## O2       .*      .*       *      .*      .*       *       *       *       *
## O3        *      .*       *  0.332*       *                       *       *
## O4        *      .*       *      .*       *       *       *      .*       *
## O5        *      .*       *      .*      .*       *               *       *
## O6                *       *      .*       *       *       *      .*       *
## O7        *       *       *      .*      .*               *      .*       *
## O8        *               *       *      .*       *       *       *       *
## O9        *       *               *      .*       *       *       *       *
## O10       *      .*       *      .*  0.300*       *       *               *
## P1       .*      .*      .*      .* -0.519*       *       *       *      .*
## P2       .*      .*      .*      .* -0.454*               *       *      .*
## P3       .*      .*       *       *      .*               *       *      .*
## P4       .*      .*       *       *      .*       *               *      .*
## P5       .*       *               * -0.493*       *               *       *
## P6        *       *       *              .*       *       *       *      .*
## P7       .*       *       *       *      .*       *       *       *       *
## P8       .*      .*       *       * -0.415*       *       *       *      .*
## P9       .*       *       *      .*      .*       *       *      .*  0.355*
## P10 -0.400*                      .*       *      .*              .*      .*
##        f10     f11     f12     f13     f14     f15     f16       unique.var
## A1        *      .*       *       *               *       *           0.504
## A2        *      .*       *       *      .*       *       *           0.489
## A3               .*       *       *       *       *       *           0.550
## A4               .*       *      .*      .*       *                   0.613
## A5                *       *               *               *           0.488
## A6        *      .*      .*       *       *       *       *           0.537
## A7                *       *       *      .*       *       *           0.621
## A8        *      .*              .*      .*       *       *           0.799
## A9        *      .*       *      .*      .*               *           0.548
## A10       *       *       *      .*       *       *      .*           0.775
## B1        *       *       *  0.486*      .*              .*           0.665
## B2                        *  0.393*      .*              .*           0.667
## B3        *               *  0.456*      .*      .*      .*           0.651
## B4                *       *  0.476*      .*      .*      .*           0.636
## B5                *       *  0.382*       *       *       *           0.708
## B6                *          0.350*       *       *      .*           0.677
## B7        *       *      .*      .*      .*      .*       *           0.703
## B8                *      .*      .*       *      .*      .*           0.799
## B9        *       *       *  0.341*               *       *           0.724
## B10               *       *  0.353*       *      .*       *           0.570
## B11       *      .*      .*      .*               *      .*           0.695
## B12       *               *  0.515*       *       *                   0.635
## B13       *       *          0.443*       *       *       *           0.722
## C1       .*       *       *       *       *       *      .*           0.735
## C2        *      .*       *       *       *       *      .*           0.443
## C3        *       *       *      .*       *       *       *           0.661
## C4                       .*       *       *       *       *           0.596
## C5        *       * -0.511*       *               *       *           0.452
## C6                *      .*      .*      .*       *                   0.505
## C7                *       *       *      .*       *      .*           0.427
## C8        *      .*      .*               *      .*      .*           0.360
## C9        *       *      .*       *       *       *       *           0.488
## C10                              .*       *       *       *           0.472
## D1        *       *       *       *       *      .*       *           0.384
## D2        *       *       *       *       *       *      .*           0.565
## D3        *      .*       *       *               *                   0.676
## D4        *      .*       *      .*       *       *       *           0.720
## D5        *       *       *       *              .*       *           0.492
## D6        *       *       *      .*       *       *       *           0.712
## D7                *      .*      .*       *       *      .*           0.458
## D8        *       *       *  0.348*       *               *           0.684
## D9                *      .*      .*       *       *       *           0.608
## D10               *      .*      .*       *       *       *           0.590
## E1        *      .*       *       *      .*       *       *           0.415
## E2        *       *              .* -0.313*       *       *           0.410
## E3        *       *       *      .*       *      .*      .*           0.565
## E4        *       *              .* -0.339*       *       *           0.456
## E5        *       *       *      .*               *      .*           0.598
## E6                *       *       *       *      .*                   0.528
## E7   0.305*       *       *      .*       *      .*       *           0.658
## E8        *       *               * -0.353*               *           0.527
## E9        *               *      .*       *                           0.830
## E10               *      .*       *      .*       *       *           0.783
## F1        *       *       *      .*       *      .*       *           0.639
## F2        *       *       *       *       *      .*       *           0.390
## F3        *               *      .*               *       *           0.820
## F4        *       *       *      .*       *       *                   0.338
## F5        *       *              .*       *       *       *           0.737
## F6                        *       *       *       *      .*           0.385
## F7                        *       *       *      .*       *           0.471
## F8        *       *      .*       *       *      .*       *           0.717
## F9                *       *       *       *       *      .*           0.382
## F10       *       *       *       *       *       *      .*           0.650
## G1        *      .*       *       *      .*       *       *           0.368
## G2        *      .*       *       *      .*       *       *           0.415
## G3        *      .*       *       *      .*       *      .*           0.562
## G4        *      .*       *       *       *       *       *           0.362
## G5        *      .*       *       *       *       *                   0.390
## G6        *      .*                       *       *       *           0.382
## G7        *      .*       *              .*       *                   0.509
## G8        *      .*      .*  0.349*      .*       *                   0.548
## G9               .*       *       *      .*       *      .*           0.457
## G10       *      .*      .*       *      .*       *       *           0.460
## H1        *       *       *  0.420*      .*       *       *           0.161
## H2        *       *       *  0.400*       *       *       *           0.688
## H3        *       *          0.402*      .*               *           0.191
## H4        *       *       *       *       *       *       *           0.872
## H5        *      .*      .*       *       *       *                   0.738
## H6        *      .*       *       *       *       *       *           0.719
## H7                *      .*       *       *       *       *           0.809
## H8                *       *  0.346*       *              .*           0.691
## H9       .*       *      .*  0.408*       *      .*       *           0.702
## H10       *      .*      .*      .*       *       *       *           0.828
## I1        *      .*      .*       *       *       *      .*           0.645
## I2        *       *       *       *       *              .*           0.578
## I3        *      .*       *       *      .*               *           0.680
## I4               .*       *       *      .*               *           0.359
## I5       .*       *       *       *      .*       *      .*           0.758
## I6        *       *       *      .*      .*               *           0.609
## I7               .*       *       *       *       *       *           0.448
## I8        *      .*       *       *      .*       *       *           0.353
## I9        *      .*       *       *       *       *                   0.466
## I10       *       *       *       *       *       *       *           0.659
## J1        *       *       *      .*      .*      .*                   0.650
## J2       .*       *       *  0.333*      .*      .*       *           0.536
## J3       .*       *              .*      .*      .*       *           0.590
## J4   0.305*       *       *      .*      .*      .*      .*           0.538
## J5        *               *      .*      .*       *       *           0.709
## J6                *       *       *       *       *       *           0.702
## J7        *       *               *       *      .*       *           0.629
## J8        *       *       *       *       *      .*      .*           0.581
## J9   0.830*       *              .*       *       *                   0.189
## J10  0.760*       *              .*       *       *                   0.288
## K1        *  0.668*       *       *      .*       *       *           0.392
## K2           0.377*       *       *      .*       *       *           0.546
## K3        *      .*       *       *      .*       *       *           0.455
## K4           0.494*       *       *      .*       *       *           0.532
## K5        *  0.511*       *      .*      .*       *       *           0.508
## K6        *  0.745*       *       *       *       *                   0.287
## K7        *  0.785*       *               *       *                   0.250
## K8        *  0.395*       *       *       *       *       *           0.799
## K9           0.649*       *       *       *       *                   0.443
## K10          0.517*       *      .*       *       *      .*           0.589
## L1        *       *       *       *               *      .*           0.553
## L2        *                       *       *              .*           0.529
## L3        *       *      .*      .*       *              .*           0.474
## L4        *       *       *       *       *       *      .*           0.555
## L5                *               *       *       *      .*           0.643
## L6        *       *      .*       *       *       *      .*           0.692
## L7                *               *       *              .*           0.620
## L8        *       *      .*       *       *       *       *           0.688
## L9        *       *  0.306*                       *       *           0.577
## L10       *       *       *       *       *       *       *           0.555
## M1        *       *       *  0.343*      .*       *      .*           0.654
## M2        *       *       *      .*       *       *                   0.661
## M3        *       *       *  0.418*       *               *           0.679
## M4        *      .*       *  0.429*       *       *       *           0.626
## M5        *       *       *       *       *      .*       *           0.764
## M6        *       *       *  0.611*       *       *       *           0.590
## M7        *       *       *  0.505*       *               *           0.703
## M8        *               *  0.625*       *       *       *           0.585
## M9        *               *  0.534*       *       *      .*           0.625
## M10       *       *          0.544*       *       *      .*           0.640
## N1        *      .*               *  0.545*       *                   0.423
## N2               .*               *  0.494*       *       *           0.605
## N3        *       *       *      .*  0.651*               *           0.480
## N4        *      .*       *       *  0.613*       *       *           0.415
## N5                *       *      .*  0.423*               *           0.755
## N6                *               *  0.608*       *       *           0.550
## N7        *      .*       *      .*  0.505*       *       *           0.620
## N8        *       *       *       *  0.352*              .*           0.509
## N9        *       *       *      .*      .*       *                   0.595
## N10       *      .*       *      .*  0.388*       *      .*           0.712
## O1        *               *               *  0.313*      .*           0.699
## O2        *       *       *      .*       *  0.584*      .*           0.511
## O3                *       *       *       *  0.489*      .*           0.597
## O4        *       *      .*      .*       *  0.414*      .*           0.646
## O5        *               *      .*       *  0.361*      .*           0.676
## O6        *       *      .*               *  0.458*       *           0.724
## O7        *              .*                  0.497*       *           0.667
## O8        *       *               *       *  0.696*      .*           0.433
## O9        *       *       *       *          0.573*      .*           0.611
## O10      .*       *       *       *       *  0.441*      .*           0.595
## P1                *  0.507*      .*      .*              .*           0.308
## P2        *       *  0.485*      .*       *       *       *           0.384
## P3                *      .*       *       *       *  0.372*           0.670
## P4        *       *      .*               *       *  0.348*           0.649
## P5                        *      .*       *       *      .*           0.674
## P6        *       *      .*      .*       *              .*           0.756
## P7        *       *       *       *       *       *  0.402*           0.727
## P8        *       *  0.575*       *       *       *      .*           0.405
## P9                *      .*                               *           0.698
## P10       *       *      .*       *       *       *       *           0.650
##       communalities
## A1            0.496
## A2            0.511
## A3            0.450
## A4            0.387
## A5            0.512
## A6            0.463
## A7            0.379
## A8            0.201
## A9            0.452
## A10           0.225
## B1            0.335
## B2            0.333
## B3            0.349
## B4            0.364
## B5            0.292
## B6            0.323
## B7            0.297
## B8            0.201
## B9            0.276
## B10           0.430
## B11           0.305
## B12           0.365
## B13           0.278
## C1            0.265
## C2            0.557
## C3            0.339
## C4            0.404
## C5            0.548
## C6            0.495
## C7            0.573
## C8            0.640
## C9            0.512
## C10           0.528
## D1            0.616
## D2            0.435
## D3            0.324
## D4            0.280
## D5            0.508
## D6            0.288
## D7            0.542
## D8            0.316
## D9            0.392
## D10           0.410
## E1            0.585
## E2            0.590
## E3            0.435
## E4            0.544
## E5            0.402
## E6            0.472
## E7            0.342
## E8            0.473
## E9            0.170
## E10           0.217
## F1            0.361
## F2            0.610
## F3            0.180
## F4            0.662
## F5            0.263
## F6            0.615
## F7            0.529
## F8            0.283
## F9            0.618
## F10           0.350
## G1            0.632
## G2            0.585
## G3            0.438
## G4            0.638
## G5            0.610
## G6            0.618
## G7            0.491
## G8            0.452
## G9            0.543
## G10           0.540
## H1            0.839
## H2            0.312
## H3            0.809
## H4            0.128
## H5            0.262
## H6            0.281
## H7            0.191
## H8            0.309
## H9            0.298
## H10           0.172
## I1            0.355
## I2            0.422
## I3            0.320
## I4            0.641
## I5            0.242
## I6            0.391
## I7            0.552
## I8            0.647
## I9            0.534
## I10           0.341
## J1            0.350
## J2            0.464
## J3            0.410
## J4            0.462
## J5            0.291
## J6            0.298
## J7            0.371
## J8            0.419
## J9            0.811
## J10           0.712
## K1            0.608
## K2            0.454
## K3            0.545
## K4            0.468
## K5            0.492
## K6            0.713
## K7            0.750
## K8            0.201
## K9            0.557
## K10           0.411
## L1            0.447
## L2            0.471
## L3            0.526
## L4            0.445
## L5            0.357
## L6            0.308
## L7            0.380
## L8            0.312
## L9            0.423
## L10           0.445
## M1            0.346
## M2            0.339
## M3            0.321
## M4            0.374
## M5            0.236
## M6            0.410
## M7            0.297
## M8            0.415
## M9            0.375
## M10           0.360
## N1            0.577
## N2            0.395
## N3            0.520
## N4            0.585
## N5            0.245
## N6            0.450
## N7            0.380
## N8            0.491
## N9            0.405
## N10           0.288
## O1            0.301
## O2            0.489
## O3            0.403
## O4            0.354
## O5            0.324
## O6            0.276
## O7            0.333
## O8            0.567
## O9            0.389
## O10           0.405
## P1            0.692
## P2            0.616
## P3            0.330
## P4            0.351
## P5            0.326
## P6            0.244
## P7            0.273
## P8            0.595
## P9            0.302
## P10           0.350
## 
##                                f5    f6   f13    f4    f1    f9   f11    f2
## Sum of sq (ortho) loadings 11.086 8.592 6.852 5.226 5.170 4.574 4.296 4.016
## Proportion of total         0.160 0.124 0.099 0.076 0.075 0.066 0.062 0.058
## Proportion var              0.068 0.053 0.042 0.032 0.032 0.028 0.026 0.025
## Cumulative var              0.068 0.121 0.163 0.195 0.227 0.255 0.281 0.306
##                              f14   f15    f8   f12   f16    f3   f10    f7
## Sum of sq (ortho) loadings 3.992 3.378 2.728 2.111 1.894 1.796 1.769 1.636
## Proportion of total        0.058 0.049 0.039 0.031 0.027 0.026 0.026 0.024
## Proportion var             0.024 0.021 0.017 0.013 0.012 0.011 0.011 0.010
## Cumulative var             0.330 0.351 0.368 0.381 0.392 0.403 0.414 0.424
##                             total
## Sum of sq (ortho) loadings 69.117
## Proportion of total         1.000
## Proportion var              0.424
## Cumulative var              0.424</pre>
<p>Our model fit is quite good, but that’s not too surprising since the data determines the model, rather than the other way around. I extracted the loadings into a data frame, then keep only the highest
loading for each item. The gives me a dataset matching the standardized loading output from above. This was a bit easier to work with than scrolling through the output.</p>
<pre>StLoadings16 &lt;- as_tibble(EFA$loadings$nf16)

StLoadings16 &lt;- StLoadings16 %&gt;%
  mutate(Item = ItemList) %&gt;%
  group_by(Item) %&gt;%
  pivot_longer(cols = f1:f16,
               names_to = &quot;factor&quot;,
               values_to = &quot;loading&quot;) %&gt;%
  filter(loading == max(loading))

StLoadings16 &lt;- StLoadings16 %&gt;%
  pivot_wider(id_cols = Item,
              names_from = factor,
              values_from = loading,
              values_fill = NA)</pre>
<p>The results are, of course, quite a mess and somewhat hard to read.
But I went through it and here’s the scales that had factors all to
themselves: F, K, N, and O (or Dutifulness, Reserve, Introversion, and
Orderliness). Some scales split across a couple factors, or shared
factors with other scales. Our worst offenders were H, J, and L
(Sensitivity, Imagination, and Anxiety). Each of these 3 scales split
into 4 factors (with a total of 8 factors among them, since there was a
bit of overlap); some of those factors were made up of a few items. H4,
our worst item of the bunch, didn't load with any of the other H items. So we seem to have
decent support for 4 of Cattell’s factors, little to no support for 3,
and mediocre support for the rest.</p>
<p>I created a
<a href="https://docs.google.com/spreadsheets/d/1Yx1YAVRzCqgcg0YipqyTgF8pTkWJIWvM/edit?usp=sharing&#038;ouid=109248788629520655353&#038;rtpof=true&#038;sd=true" rel="nofollow" target="_blank">chart
color-coding where items fell</a>. It’s still messy and a bit
overwhelming. But it gives you some idea of what scales seem to hold
together and which ones fall apart.</p>
<p>Since this post is already overlong, I won’t be going through the 5
and 6 factor models, but look for them in a future post! Next time,
let’s subject our 16 Factor Measure to Rasch measurement!</p>
<div style="border: 1px solid; background: none repeat scroll 0 0 #EDEDED; margin: 1px; font-size: 13px;">
<div style="text-align: center;">To <strong>leave a comment</strong> for the author, please follow the link and comment on their blog: <strong><a href="http://www.deeplytrivial.com/2026/11/classical-test-theory-analysis-of-16.html"> Deeply Trivial</a></strong>.</div>
<hr />
<a href="https://www.r-bloggers.com/" rel="nofollow">R-bloggers.com</a> offers <strong><a href="https://feedburner.google.com/fb/a/mailverify?uri=RBloggers" rel="nofollow">daily e-mail updates</a></strong> about <a title="The R Project for Statistical Computing" href="https://www.r-project.org/" rel="nofollow">R</a> news and tutorials about <a title="R tutorials" href="https://www.r-bloggers.com/how-to-learn-r-2/" rel="nofollow">learning R</a> and many other topics. <a title="Data science jobs" href="https://www.r-users.com/" rel="nofollow">Click here if you're looking to post or find an R/data-science job</a>.

<hr>Want to share your content on R-bloggers?<a href="https://www.r-bloggers.com/add-your-blog/" rel="nofollow"> click here</a> if you have a blog, or <a href="http://r-posts.com/" rel="nofollow"> here</a> if you don't.
</div><strong>Continue reading</strong>: <a href="https://www.r-bloggers.com/2026/11/classical-test-theory-analysis-of-the-16-factor-personality-measure/">Classical Test Theory Analysis of the 16 Factor Personality Measure</a>]]></content:encoded>
					
		
		<enclosure url="" length="0" type="" />

		<post-id xmlns="com-wordpress:feed-additions:1">405037</post-id>	</item>
		<item>
		<title>blorr 0.3.2</title>
		<link>https://www.r-bloggers.com/2026/11/blorr-0-3-2/</link>
		
		<dc:creator><![CDATA[Aravind Hebbali]]></dc:creator>
		<pubDate>Sat, 21 Nov 2026 00:00:00 +0000</pubDate>
				<category><![CDATA[R bloggers]]></category>
		<guid isPermaLink="false">https://blog.rsquaredacademy.com/posts/blorr-0-3-2/</guid>

					<description><![CDATA[<div style = "width:60%; display: inline-block; float:left; ">
<p>blorr 0.3.2 is on CRAN. blorr provides tools for binary logistic regression in R: model fit statistics, variable selection, bivariate analysis, weight of evidence, and the validation charts used in credit scoring (gains table, ROC curve, KS chart and Lorenz curve), all built around glm() objects.<br />
The last blorr post covered 0.2.0 ...</p></div>
<div style = "width: 40%; display: inline-block; float:right;"></div>
<div style="clear: both;"></div>
<strong>Continue reading</strong>: <a href="https://www.r-bloggers.com/2026/11/blorr-0-3-2/">blorr 0.3.2</a>]]></description>
										<content:encoded><![CDATA[<!-- 
<div style="min-height: 30px;">
[social4i size="small" align="align-left"]
</div>
-->

<div style="border: 1px solid; background: none repeat scroll 0 0 #EDEDED; margin: 1px; font-size: 12px;">
[This article was first published on  <strong><a href="https://blog.rsquaredacademy.com/posts/blorr-0-3-2/"> Rsquared Academy Blog</a></strong>, and kindly contributed to <a href="https://www.r-bloggers.com/" rel="nofollow">R-bloggers</a>].  (You can report issue about the content on this page <a href="https://www.r-bloggers.com/contact-us/">here</a>)
<hr>Want to share your content on R-bloggers?<a href="https://www.r-bloggers.com/add-your-blog/" rel="nofollow"> click here</a> if you have a blog, or <a href="http://r-posts.com/" rel="nofollow"> here</a> if you don't.
</div>
 




<p><img src="https://i0.wp.com/blog.rsquaredacademy.com/img/blorr-0-3-2.png?w=578&#038;ssl=1" class="img-fluid" style="width:100.0%" alt="blorr hex logo next to the tagline Binary logistic regression in R, the line 0.3.2, corrected results, the package name blorr and blorr.rsquaredacademy.com" data-recalc-dims="1"></p>
<style>
.ba-note{font-size:.88rem;color:#57606a;border-left:3px solid #d0d7de;padding-left:.75rem;margin:.5rem 0 1.25rem}
</style>
<p><code>blorr</code> 0.3.2 is on CRAN. <code>blorr</code> provides tools for binary logistic regression in R: model fit statistics, variable selection, bivariate analysis, weight of evidence, and the validation charts used in credit scoring (gains table, ROC curve, KS chart and Lorenz curve), all built around <code>glm()</code> objects.</p>
<p>The last blorr post covered 0.2.0 in 2019. Since then there have been four CRAN releases (0.2.1, 0.2.2, 0.3.0 and 0.3.1), and this one changes numbers that may already be in reports:</p>
<ul>
<li>Pseudo-R² values and the Gini index now use the rows the model was actually fitted on, and the Gini index follows the credit-scoring definition <img src="https://latex.codecogs.com/png.latex?2%20%5Ctimes%20%5Cmathrm%7BAUC%7D%20-%201">.</li>
<li>The likelihood ratio test uses the difference in residual degrees of freedom, so factor predictors get the right <img src="https://latex.codecogs.com/png.latex?p">-value.</li>
<li>Gains tables, confusion matrices and segmentation rates were rebuilt around the fitted response.</li>
</ul>
<p>If you report the Gini index, Cox–Snell or Nagelkerke R², or a likelihood ratio test from blorr, read the next three sections before you reuse those numbers. Everyone else can start at What is new since 2019.</p>
<p>You can install it from CRAN with:</p>
<div class="cell">
<details open="" class="code-fold">
<summary>Code</summary>
<pre>install.packages(&quot;blorr&quot;)</pre>
</details>
</div>
<p>You can see a full list of changes in the <a href="https://blorr.rsquaredacademy.com/news/" rel="nofollow" target="_blank">release notes</a>.</p>
<p>These fixes change results. In each case the new value agrees with the definition or with base R, so the new value is the one to report.</p>
<div class="ba-note">
<p>How we checked: Every number in this post was re-run against blorr 0.3.2 from CRAN; the release passed independent audits before submission.</p>
</div>
<section id="do-the-pseudo-r²-values-use-the-rows-the-model-fitted" class="level2">
<h2 class="anchored" data-anchor-id="do-the-pseudo-r²-values-use-the-rows-the-model-fitted">Do the pseudo-R² values use the rows the model fitted?</h2>
<p>Cox–Snell and Nagelkerke R² are functions of the fitted and intercept-only log-likelihoods and of the number of observations. If the data contain missing values, that number is the rows the model used, not the rows in the data frame.</p>
<p><code>bank_marketing</code> records bank term-deposit marketing outcomes. It has no missing values, so we blank out 300 balances to mimic incomplete records:</p>
<div class="cell">
<details open="" class="code-fold">
<summary>Code</summary>
<pre>bank_incomplete &lt;- bank_marketing
set.seed(123)
bank_incomplete$balance[sample(nrow(bank_incomplete), 300)] &lt;- NA
m_bank &lt;- glm(y ~ balance + housing + loan, data = bank_incomplete, family = binomial)
c(rows_in_data = nrow(bank_incomplete), rows_fitted = nobs(m_bank))</pre>
</details>
<div class="cell-output cell-output-stdout">
<pre>rows_in_data  rows_fitted 
        4521         4221 </pre>
</div>
</div>
<p>With <img src="https://latex.codecogs.com/png.latex?n%20=%204221"> and the intercept-only model fitted on the same 4221 rows, the two R² values are:</p>
<div class="cell">
<details open="" class="code-fold">
<summary>Code</summary>
<pre>n &lt;- nobs(m_bank)
ll &lt;- as.numeric(logLik(m_bank))
ll0 &lt;- as.numeric(logLik(glm(y ~ 1, data = model.frame(m_bank), family = binomial)))
cox_snell &lt;- 1 - exp((2 / n) * (ll0 - ll))
nagelkerke &lt;- cox_snell / (1 - exp((2 / n) * ll0))
c(cox_snell = cox_snell, nagelkerke = nagelkerke)</pre>
</details>
<div class="cell-output cell-output-stdout">
<pre> cox_snell nagelkerke 
0.02278596 0.04455730 </pre>
</div>
</div>
<p><code>blr_rsq_cox_snell()</code> and <code>blr_rsq_nagelkerke()</code> return the same two values, and <code>blr_model_fit_stats()</code> prints them in the fit statistics table:</p>
<div class="cell">
<details open="" class="code-fold">
<summary>Code</summary>
<pre>blr_model_fit_stats(m_bank)</pre>
</details>
<div class="cell-output cell-output-stdout">
<pre>                               Model Fit Statistics                                 
-----------------------------------------------------------------------------------
Log-Lik Intercept Only:     -1511.502    Log-Lik Full Model:              -1462.856 
Deviance(4217):              2925.711    LR(3):                              97.292 
                                         Prob &gt; LR:                           0.000 
MCFadden's R2                   0.032    McFadden's Adj R2:                   0.030 
ML (Cox-Snell) R2:              0.023    Cragg-Uhler(Nagelkerke) R2:          0.045 
McKelvey & Zavoina's R2:        0.067    Efron's R2:                          0.025 
Count R2:                       0.884    Adj Count R2:                        0.000 
BIC:                         2959.102    AIC:                              2933.711 
-----------------------------------------------------------------------------------</pre>
</div>
</div>
<p>In 0.3.2 the intercept-only model keeps the fitted model’s response, offset and family/link, and <code>n</code> is <code>nobs(model)</code>. Earlier versions used the number of rows in the data frame, so missing values pulled both R² towards zero.</p>
<p><strong>What to do:</strong> re-run pseudo-R² for any model fitted with missing data; the new values are the ones that match the definitions.</p>
</section>
<section id="does-the-gini-index-agree-with-the-auc" class="level2">
<h2 class="anchored" data-anchor-id="does-the-gini-index-agree-with-the-auc">Does the Gini index agree with the AUC?</h2>
<p>The Gini index is usually reported beside the AUC in credit scoring, under the convention <img src="https://latex.codecogs.com/png.latex?G%20=%202%20%5Ctimes%20%5Cmathrm%7BAUC%7D%20-%201">. For the bank marketing model below, the ROC curve is:</p>
<div class="cell">
<details open="" class="code-fold">
<summary>Code</summary>
<pre>m &lt;- glm(y ~ duration + loan + housing + campaign, data = bank_marketing, family = binomial)
g &lt;- blr_gains_table(m)</pre>
</details>
</div>
<div class="cell">
<details open="" class="code-fold">
<summary>Code</summary>
<pre>blr_roc_curve(g)</pre>
</details>
<div class="cell-output-display">
<div id="fig-roc" class="quarto-float quarto-figure quarto-figure-center anchored" alt="ROC curve for the bank marketing model, with sensitivity on the y-axis against 1 minus specificity on the x-axis. The curve rises from 0% to 100% and stays well above the diagonal reference line.">
<figure class="quarto-float quarto-float-fig figure">
<div aria-describedby="fig-roc-caption-0ceaefa1-69ba-4598-a22c-09a6ac19f8ca">
<img src="https://i1.wp.com/blog.rsquaredacademy.com/posts/blorr-0-3-2/index_files/figure-html/fig-roc-1.png?w=450&#038;ssl=1" class="img-fluid figure-img" alt="ROC curve for the bank marketing model, with sensitivity on the y-axis against 1 minus specificity on the x-axis. The curve rises from 0% to 100% and stays well above the diagonal reference line."  data-recalc-dims="1">
</div>
<figcaption class="quarto-float-caption-bottom quarto-float-caption quarto-float-fig" id="fig-roc-caption-0ceaefa1-69ba-4598-a22c-09a6ac19f8ca">
Figure 1: ROC curve for the bank marketing model.
</figcaption>
</figure>
</div>
</div>
</div>
<p>The area under that curve, computed from the ranks of the fitted probabilities, and the Gini index are:</p>
<div class="cell">
<details open="" class="code-fold">
<summary>Code</summary>
<pre>p &lt;- fitted(m)
event &lt;- bank_marketing$y == &quot;1&quot;
r &lt;- rank(p)
n1 &lt;- sum(event)
n0 &lt;- sum(!event)
auc &lt;- (sum(r[event]) - n1 * (n1 + 1) / 2) / (n1 * n0)
c(auc = auc, gini_from_auc = 2 * auc - 1, gini = blr_gini_index(m))</pre>
</details>
<div class="cell-output cell-output-stdout">
<pre>          auc gini_from_auc          gini 
    0.8466918     0.6933835     0.6933835 </pre>
</div>
</div>
<p>The last two numbers are equal. In 0.3.2 <code>blr_gini_index()</code> computes the AUC from the Mann–Whitney rank statistic and returns <img src="https://latex.codecogs.com/png.latex?2%20%5Ctimes%20%5Cmathrm%7BAUC%7D%20-%201">, using only the rows the model was fitted on. Earlier versions returned the concentration index of the predicted probabilities, a different number for the same model, so a Gini reported before 0.3.2 cannot be compared with the AUC. The rank formula also avoids overflow on large models.</p>
<p>The gains table behind the curve now puts every observation in exactly one of ten deciles and counts events using the event level of the response:</p>
<div class="cell">
<details open="" class="code-fold">
<summary>Code</summary>
<pre>c(observations = sum(g$gains_table$total), events = sum(g$gains_table$`1`))</pre>
</details>
<div class="cell-output cell-output-stdout">
<pre>observations       events 
        4521          517 </pre>
</div>
</div>
<p><strong>What to do:</strong> recompute any Gini index and report it as <img src="https://latex.codecogs.com/png.latex?2%20%5Ctimes%20%5Cmathrm%7BAUC%7D%20-%201"> from now on.</p>
</section>
<section id="does-the-likelihood-ratio-test-use-the-right-degrees-of-freedom" class="level2">
<h2 class="anchored" data-anchor-id="does-the-likelihood-ratio-test-use-the-right-degrees-of-freedom">Does the likelihood ratio test use the right degrees of freedom?</h2>
<p>A likelihood ratio test compares a full model with a reduced one. Its degrees of freedom are the difference in the number of estimated parameters, which is also the difference in residual degrees of freedom.</p>
<p><code>job</code> has 12 levels, so adding it to a model with <code>duration</code> and <code>loan</code> adds 11 parameters:</p>
<div class="cell">
<details open="" class="code-fold">
<summary>Code</summary>
<pre>m_red &lt;- glm(y ~ duration + loan, data = bank_marketing, family = binomial)
m_full &lt;- glm(y ~ duration + loan + job, data = bank_marketing, family = binomial)
c(resid_df_reduced = m_red$df.residual, resid_df_full = m_full$df.residual)</pre>
</details>
<div class="cell-output cell-output-stdout">
<pre>resid_df_reduced    resid_df_full 
            4518             4507 </pre>
</div>
</div>
<p>The test uses those two residual degrees of freedom:</p>
<div class="cell">
<details open="" class="code-fold">
<summary>Code</summary>
<pre>print(blr_test_lr(m_full, m_red))</pre>
</details>
<div class="cell-output cell-output-stdout">
<pre>    Likelihood Ratio Test      
------------------------------
Chi-Square    DF    Pr &gt; ChiSq 
------------------------------
 86.2666      11      0.0000   
------------------------------</pre>
</div>
</div>
<p>The same comparison in base R gives the same deviance, degrees of freedom and <img src="https://latex.codecogs.com/png.latex?p">-value:</p>
<div class="cell">
<details open="" class="code-fold">
<summary>Code</summary>
<pre>anova(m_red, m_full, test = &quot;Chisq&quot;)</pre>
</details>
<div class="cell-output cell-output-stdout">
<pre>Analysis of Deviance Table

Model 1: y ~ duration + loan
Model 2: y ~ duration + loan + job
  Resid. Df Resid. Dev Df Deviance  Pr(&gt;Chi)    
1      4518     2644.9                          
2      4507     2558.7 11   86.267 8.951e-14 ***
---
Signif. codes:  0 '***' 0.001 '**' 0.01 '*' 0.05 '.' 0.1 ' ' 1</pre>
</div>
</div>
<p>In 0.3.2 the degrees of freedom come from <code>df.residual</code> of the two models, and the <img src="https://latex.codecogs.com/png.latex?p">-value from the chi-square distribution with those degrees of freedom. Earlier versions could report the wrong degrees of freedom, and therefore the wrong <img src="https://latex.codecogs.com/png.latex?p">-value, for nested models with factor predictors. The test also checks that the reduced model is nested in the full model by comparing the fitted design spaces instead of assuming it.</p>
<p><strong>What to do:</strong> re-run likelihood ratio tests that involve factor predictors; a <img src="https://latex.codecogs.com/png.latex?p">-value from an earlier version may be based on the wrong degrees of freedom.</p>
</section>
<section id="what-is-new-since-2019" class="level2">
<h2 class="anchored" data-anchor-id="what-is-new-since-2019">What is new since 2019?</h2>
<section id="does-blorr-stop-when-the-model-is-not-a-binary-logit" class="level3">
<h3 class="anchored" data-anchor-id="does-blorr-stop-when-the-model-is-not-a-binary-logit">Does blorr stop when the model is not a binary logit?</h3>
<p>blorr’s tests and plots assume a binary response with a logit link. Version 0.3.2 checks the model before it calculates anything, instead of returning a number from a fit it cannot interpret:</p>
<div class="cell">
<details open="" class="code-fold">
<summary>Code</summary>
<pre>m_q &lt;- glm(y ~ duration, data = bank_marketing, family = quasibinomial)
blr_regress(m_q)</pre>
</details>
<div class="cell-output cell-output-error">
<pre>Error:
! blorr supports binary logistic regression only (binomial family, logit link). This model uses the 'quasibinomial' family and the 'logit' link.</pre>
</div>
</div>
<p>The same guard rejects prior weights other than 1, grouped binomial responses and fits stored without their model frame or response, and the selection functions reject these models before they refit anything.</p>
</section>
<section id="can-i-draw-the-validation-charts-my-way" class="level3">
<h3 class="anchored" data-anchor-id="can-i-draw-the-validation-charts-my-way">Can I draw the validation charts my way?</h3>
<p>The data behind the Lorenz curve and the decile capture-rate chart is exported as a plain data frame. <code>blr_prep_lorenz_data()</code> returns the cumulative event and non-event shares; <code>blr_prep_dcrate_data()</code> returns the decile counts and the decile mean:</p>
<div class="cell">
<details open="" class="code-fold">
<summary>Code</summary>
<pre>head(blr_prep_lorenz_data(m), 4)</pre>
</details>
<div class="cell-output cell-output-stdout">
<pre>  cum_0s_per cum_1s_per
1 0.00000000  0.0000000
2 0.05844156  0.4216634
3 0.14285714  0.6421663
4 0.23276723  0.8201161</pre>
</div>
<details open="" class="code-fold">
<summary>Code</summary>
<pre>head(blr_prep_dcrate_data(g), 4)</pre>
</details>
<div class="cell-output cell-output-stdout">
<pre>  decile total   1 decile_mean
1      1   452 218  0.48230088
2      2   452 114  0.25221239
3      3   452  92  0.20353982
4      4   452  27  0.05973451</pre>
</div>
</div>
<p>Both can go straight into <code>ggplot2</code>, <code>plotly</code> or any other plotting library, with the grouping and percentages already computed. The same applies to <code>blr_prep_roc_data()</code>, <code>blr_prep_kschart_data()</code> and <code>blr_prep_kschart_stat()</code>.</p>
</section>
</section>
<section id="other-improvements" class="level2">
<h2 class="anchored" data-anchor-id="other-improvements">Other improvements</h2>
<ul>
<li>The Hosmer–Lemeshow test takes its degrees of freedom from the observed number of groups; the intercept-only model behind the fit statistics keeps the fitted response, offset and family/link; and package startup no longer checks the network (<a href="https://github.com/rsquaredacademy/blorr/issues/138" rel="nofollow" target="_blank">#138</a>, <a href="https://github.com/rsquaredacademy/blorr/issues/129" rel="nofollow" target="_blank">#129</a>, <a href="https://github.com/rsquaredacademy/blorr/issues/139" rel="nofollow" target="_blank">#139</a>).</li>
<li><code>blr_pairs()</code> uses wide counters, so pair counts above the 32-bit integer limit no longer overflow, and its Somers’ D and Goodman–Kruskal gamma use the correct denominators.</li>
<li>Variance decomposition proportions in <code>blr_eigen_cindex()</code> sum to one, and condition indices stay finite for nearly collinear full-rank designs.</li>
<li>Missing responses are no longer counted as non-events in segment, gains, confusion matrix and validation summaries, and the event rate in <code>blr_segment()</code> and <code>blr_segment_dist()</code> is the share of events within each level.</li>
<li><code>blr_woe_iv()</code> accepts character and numeric predictors, drops unused factor levels, applies a 0.5 continuity correction to levels with no events or no non-events, and drops rows with missing values.</li>
<li>The stepwise AIC functions now return an intercept-only model when no predictor qualifies.</li>
</ul>
</section>
<section id="whats-next" class="level2">
<h2 class="anchored" data-anchor-id="whats-next">What’s next</h2>
<p>These issues are known in 0.3.2. Most were found by an independent audit after the CRAN release. Each has a GitHub issue with a reproducible example, and each fix goes into blorr 0.3.3:</p>
<ul>
<li>A response with three levels is fitted silently, and the response summary drops a level (<a href="https://github.com/rsquaredacademy/blorr/issues/130" rel="nofollow" target="_blank">#130</a>). Check <code>nlevels()</code> of the response before fitting. Fixed on the development branch.</li>
<li>The delta deviance in <code>blr_residual_diagnostics()</code> uses the squared standardized Pearson residual (<a href="https://github.com/rsquaredacademy/blorr/pull/146" rel="nofollow" target="_blank">#146</a>). Fixed on the development branch.</li>
<li>The cells of <code>blr_segment_twoway()</code> are each cell’s share of all observations, not the event rate within the cell. For a within-cell rate, use <code>tapply(y, list(a, b), mean)</code> (<a href="https://github.com/rsquaredacademy/blorr/issues/152" rel="nofollow" target="_blank">#152</a>).</li>
<li><code>blr_segment()</code> and <code>blr_segment_dist()</code> round proportions to two decimals before using them, so their percentages and plots can be off by up to half a percentage point (<a href="https://github.com/rsquaredacademy/blorr/issues/153" rel="nofollow" target="_blank">#153</a>). For exact shares, use <code>prop.table(table(x))</code> and <code>tapply(y, x, mean)</code>.</li>
<li>The total information value printed by <code>blr_woe_iv()</code> adds up the rounded per-level values. For an accurate total, use a larger <code>digits</code>, for example <code>digits = 4</code> (<a href="https://github.com/rsquaredacademy/blorr/issues/155" rel="nofollow" target="_blank">#155</a>).</li>
<li>A factor response with only one observed level is treated as all non-events by the segment and weight-of-evidence functions. Check that both classes are present first (<a href="https://github.com/rsquaredacademy/blorr/issues/154" rel="nofollow" target="_blank">#154</a>).</li>
</ul>
<p>Fixes for #152–#155 are on the development branch. blorr 0.3.3, with all of these fixes, is planned after 2027-01-13.</p>
</section>
<section id="acknowledgements" class="level2">
<h2 class="anchored" data-anchor-id="acknowledgements">Acknowledgements</h2>
<p>Thank you to everyone who contributed to <code>blorr</code> since the 2019 post by opening issues, reporting bugs and sending pull requests: <a href="https://github.com/aravindhebbali" rel="nofollow" target="_blank">@aravindhebbali</a>, <a href="https://github.com/DrMedfaresBrini" rel="nofollow" target="_blank">@DrMedfaresBrini</a>, <a href="https://github.com/Irazall" rel="nofollow" target="_blank">@Irazall</a>, <a href="https://github.com/LuiNov" rel="nofollow" target="_blank">@LuiNov</a>, <a href="https://github.com/paleolimbot" rel="nofollow" target="_blank">@paleolimbot</a>, and <a href="https://github.com/romainfrancois" rel="nofollow" target="_blank">@romainfrancois</a>.</p>


</section>

 
<div style="border: 1px solid; background: none repeat scroll 0 0 #EDEDED; margin: 1px; font-size: 13px;">
<div style="text-align: center;">To <strong>leave a comment</strong> for the author, please follow the link and comment on their blog: <strong><a href="https://blog.rsquaredacademy.com/posts/blorr-0-3-2/"> Rsquared Academy Blog</a></strong>.</div>
<hr />
<a href="https://www.r-bloggers.com/" rel="nofollow">R-bloggers.com</a> offers <strong><a href="https://feedburner.google.com/fb/a/mailverify?uri=RBloggers" rel="nofollow">daily e-mail updates</a></strong> about <a title="The R Project for Statistical Computing" href="https://www.r-project.org/" rel="nofollow">R</a> news and tutorials about <a title="R tutorials" href="https://www.r-bloggers.com/how-to-learn-r-2/" rel="nofollow">learning R</a> and many other topics. <a title="Data science jobs" href="https://www.r-users.com/" rel="nofollow">Click here if you're looking to post or find an R/data-science job</a>.

<hr>Want to share your content on R-bloggers?<a href="https://www.r-bloggers.com/add-your-blog/" rel="nofollow"> click here</a> if you have a blog, or <a href="http://r-posts.com/" rel="nofollow"> here</a> if you don't.
</div><strong>Continue reading</strong>: <a href="https://www.r-bloggers.com/2026/11/blorr-0-3-2/">blorr 0.3.2</a>]]></content:encoded>
					
		
		<enclosure url="https://blog.rsquaredacademy.com/img/blorr-0-3-2.png" length="0" type="image/png" />

		<post-id xmlns="com-wordpress:feed-additions:1">405035</post-id>	</item>
		<item>
		<title>Why Risk Ratio Is Preferred, What is Modified Poisson, and Why Do We Even Care About Standard Error?</title>
		<link>https://www.r-bloggers.com/2026/11/why-risk-ratio-is-preferred-what-is-modified-poisson-and-why-do-we-even-care-about-standard-error/</link>
		
		<dc:creator><![CDATA[r on Everyday Is A School Day]]></dc:creator>
		<pubDate>Fri, 20 Nov 2026 00:00:00 +0000</pubDate>
				<category><![CDATA[R bloggers]]></category>
		<guid isPermaLink="false">https://www.kenkoonwong.com/blog/modified-poisson/</guid>

					<description><![CDATA[<div style = "width:60%; display: inline-block; float:left; ">
Learnt about modified Poisson for the first time. Simulated RR vs OR, log-binomial and robust SE, then sprinkled in repeated measures. Turns out a 95% CI can be too narrow (confidently wrong) or too wide (overly cautious)! Still learning, but pretty c...</div>
<div style = "width: 40%; display: inline-block; float:right;"></div>
<div style="clear: both;"></div>
<strong>Continue reading</strong>: <a href="https://www.r-bloggers.com/2026/11/why-risk-ratio-is-preferred-what-is-modified-poisson-and-why-do-we-even-care-about-standard-error/">Why Risk Ratio Is Preferred, What is Modified Poisson, and Why Do We Even Care About Standard Error?</a>]]></description>
										<content:encoded><![CDATA[<!-- 
<div style="min-height: 30px;">
[social4i size="small" align="align-left"]
</div>
-->

<div style="border: 1px solid; background: none repeat scroll 0 0 #EDEDED; margin: 1px; font-size: 12px;">
[This article was first published on  <strong><a href="https://www.kenkoonwong.com/blog/modified-poisson/"> r on Everyday Is A School Day</a></strong>, and kindly contributed to <a href="https://www.r-bloggers.com/" rel="nofollow">R-bloggers</a>].  (You can report issue about the content on this page <a href="https://www.r-bloggers.com/contact-us/">here</a>)
<hr>Want to share your content on R-bloggers?<a href="https://www.r-bloggers.com/add-your-blog/" rel="nofollow"> click here</a> if you have a blog, or <a href="http://r-posts.com/" rel="nofollow"> here</a> if you don't.
</div>
<blockquote>
<p>Learnt about modified Poisson for the first time. Simulated RR vs OR, log-binomial and robust SE, then sprinkled in repeated measures. Turns out a 95% CI can be too narrow (confidently wrong) or too wide (overly cautious)! Still learning, but pretty convinced now <img src="https://s.w.org/images/core/emoji/13.0.0/72x72/1f64c.png" alt="🙌" class="wp-smiley" style="height: 1em; max-height: 1em;" /></p>
</blockquote>




<h2 id="motivations">Motivations
  <a href="https://www.kenkoonwong.com/blog/modified-poisson/#motivations" rel="nofollow" target="_blank"><svg class="anchor-symbol" aria-hidden="true" height="26" width="26" viewBox="0 0 22 22" xmlns="http://www.w3.org/2000/svg">
      <path d="M0 0h24v24H0z" fill="currentColor"></path>
      <path d="M3.9 12c0-1.71 1.39-3.1 3.1-3.1h4V7H7c-2.76.0-5 2.24-5 5s2.24 5 5 5h4v-1.9H7c-1.71.0-3.1-1.39-3.1-3.1zM8 13h8v-2H8v2zm9-6h-4v1.9h4c1.71.0 3.1 1.39 3.1 3.1s-1.39 3.1-3.1 3.1h-4V17h4c2.76.0 5-2.24 5-5s-2.24-5-5-5z"></path>
    </svg></a>
</h2>
<p>I was working on a project recently and learnt a few things as we were going along and want to look into it a bit more with simulation to see for myself. These might sound like some random topics, but they’re all kind of tied together, at least in my mind they are. I’ve not heard of modified poisson before and what a great way to get from incompetent incompetence to at least competent incompetence. <img src="https://s.w.org/images/core/emoji/13.0.0/72x72/1f923.png" alt="🤣" class="wp-smiley" style="height: 1em; max-height: 1em;" /> Knowing what we don’t know is definitely better than not knowing what we don’t know (MNAR problem). Well let’s explore together and see for ourselves, will this be our next go-to model along with robust sandwich standard error? Oh, let’s also sprinkle a little bit of repeatd measure (some clustering) to beef up that SE to see an even better effect with this robust sandwich standard error. Let’s go! <img src="https://s.w.org/images/core/emoji/13.0.0/72x72/1f64c.png" alt="🙌" class="wp-smiley" style="height: 1em; max-height: 1em;" /></p>




<h2 id="thought-process">Thought Process
  <a href="https://www.kenkoonwong.com/blog/modified-poisson/#thought-process" rel="nofollow" target="_blank"><svg class="anchor-symbol" aria-hidden="true" height="26" width="26" viewBox="0 0 22 22" xmlns="http://www.w3.org/2000/svg">
      <path d="M0 0h24v24H0z" fill="currentColor"></path>
      <path d="M3.9 12c0-1.71 1.39-3.1 3.1-3.1h4V7H7c-2.76.0-5 2.24-5 5s2.24 5 5 5h4v-1.9H7c-1.71.0-3.1-1.39-3.1-3.1zM8 13h8v-2H8v2zm9-6h-4v1.9h4c1.71.0 3.1 1.39 3.1 3.1s-1.39 3.1-3.1 3.1h-4V17h4c2.76.0 5-2.24 5-5s-2.24-5-5-5z"></path>
    </svg></a>
</h2>
<p>But, how are we going to do this? Let’s go through the bare basics of the interpretation, let’s say we have binary outcome. A heuristic is to use logistic regression model with logit as link function. It’s a great model, but exponentiating on the coefficient of exposure turns it into odds ratio instead of risk ratio (RR). So, <code>let's talk a bit about why risk ratio may be a bit easier to understand</code> than odds ratio. After this we’ll look and see how can we <code>simulate using baseline rate and RR</code>. And use this simulated data to <code>check on our regular poisson regression, log binomial regression, logistic regression with logit link, then poisson regression w robust SE (aka modified poisson)</code>. We’ll look at their wideness of 95%CI. Then, to sprinkle a little bit of sweetness on top, we’ll add on repeated measure, look at SE of all these models. Top it up with, g-computation using logistic regression &#038; bootstrap based on subject and see how that matches up with modified poisson.</p>




<h2 id="objectives">Objectives:
  <a href="https://www.kenkoonwong.com/blog/modified-poisson/#objectives" rel="nofollow" target="_blank"><svg class="anchor-symbol" aria-hidden="true" height="26" width="26" viewBox="0 0 22 22" xmlns="http://www.w3.org/2000/svg">
      <path d="M0 0h24v24H0z" fill="currentColor"></path>
      <path d="M3.9 12c0-1.71 1.39-3.1 3.1-3.1h4V7H7c-2.76.0-5 2.24-5 5s2.24 5 5 5h4v-1.9H7c-1.71.0-3.1-1.39-3.1-3.1zM8 13h8v-2H8v2zm9-6h-4v1.9h4c1.71.0 3.1 1.39 3.1 3.1s-1.39 3.1-3.1 3.1h-4V17h4c2.76.0 5-2.24 5-5s-2.24-5-5-5z"></path>
    </svg></a>
</h2>
<ul>
<li>
<a href="https://www.kenkoonwong.com/blog/modified-poisson/#rr" rel="nofollow" target="_blank">Why Risk Ratio?</a></li>
<li>
<a href="https://www.kenkoonwong.com/blog/modified-poisson/#sim" rel="nofollow" target="_blank">Simulate Baseline Rate and RR</a></li>
<li>
<a href="https://www.kenkoonwong.com/blog/modified-poisson/#comparison" rel="nofollow" target="_blank">Comparison</a>
<ul>
<li>
<a href="https://www.kenkoonwong.com/blog/modified-poisson/#poisson" rel="nofollow" target="_blank">Poisson Regression</a></li>
<li>
<a href="https://www.kenkoonwong.com/blog/modified-poisson/#logbin" rel="nofollow" target="_blank">Log Binomial Regression</a></li>
<li>
<a href="https://www.kenkoonwong.com/blog/modified-poisson/#logit" rel="nofollow" target="_blank">Logistic Regression with Logit Link</a></li>
<li>
<a href="https://www.kenkoonwong.com/blog/modified-poisson/#modpoisson" rel="nofollow" target="_blank">Poisson Regression with Robust Standard Error (Modified Poisson)</a></li>
<li>
<a href="https://www.kenkoonwong.com/blog/modified-poisson/#highevent" rel="nofollow" target="_blank">High Event Rates</a></li>
<li>
<a href="https://www.kenkoonwong.com/blog/modified-poisson/#high-rr" rel="nofollow" target="_blank">High RR</a></li>
<li>
<a href="https://www.kenkoonwong.com/blog/modified-poisson/#very-high-rr" rel="nofollow" target="_blank">Very High RR</a></li>
</ul>
</li>
<li>
<a href="https://www.kenkoonwong.com/blog/modified-poisson/#repeated" rel="nofollow" target="_blank">Repeat Measures</a>
<ul>
<li>
<a href="https://www.kenkoonwong.com/blog/modified-poisson/#gcomp" rel="nofollow" target="_blank">RR Without Modified Poisson with LR G-computation with subject level bootstrap</a></li>
</ul>
</li>
<li>
<a href="https://www.kenkoonwong.com/blog/modified-poisson/#replicate-of-sim" rel="nofollow" target="_blank">Replicates of Our 4 Scenarios</a></li>
<li>
<a href="https://www.kenkoonwong.com/blog/modified-poisson/#opportunities" rel="nofollow" target="_blank">Opportunities For Improvement</a></li>
<li>
<a href="https://www.kenkoonwong.com/blog/modified-poisson/#lessons" rel="nofollow" target="_blank">Lessons Learnt</a></li>
</ul>




<h2 id="rr">Why Risk Ratio?
  <a href="https://www.kenkoonwong.com/blog/modified-poisson/#rr" rel="nofollow" target="_blank"><svg class="anchor-symbol" aria-hidden="true" height="26" width="26" viewBox="0 0 22 22" xmlns="http://www.w3.org/2000/svg">
      <path d="M0 0h24v24H0z" fill="currentColor"></path>
      <path d="M3.9 12c0-1.71 1.39-3.1 3.1-3.1h4V7H7c-2.76.0-5 2.24-5 5s2.24 5 5 5h4v-1.9H7c-1.71.0-3.1-1.39-3.1-3.1zM8 13h8v-2H8v2zm9-6h-4v1.9h4c1.71.0 3.1 1.39 3.1 3.1s-1.39 3.1-3.1 3.1h-4V17h4c2.76.0 5-2.24 5-5s-2.24-5-5-5z"></path>
    </svg></a>
</h2>
<p>Risk Ratio is easier to understand because it’s basically risk of event in exposed group divided by risk of event in unexposed group (p1/p0). So, if we have an RR of 0.6, we’re saying the exposed group has 40% less risk of event than the unexposed group. If we have an RR of 1.5, we’re saying the exposed group has 50% more risk of event than the unexposed group. That’s much more intuitive than the odds ratio, which only approximates RR when the outcome is rare (roughly <10%). When the outcome is common, OR exaggerates the effect, pulling further from 1 than the RR.</p>
<p>To get an RR, we can’t just exponentiate the exposure coefficient from a logistic regression, because that gives us an OR. Instead, we can use:</p>
<ul>
<li><code>Log-binomial regression</code> (binomial family, log link): this models RR directly, but it often fails to converge, especially with continuous covariates or high baseline risk.</li>
<li><code>Modified Poisson regression</code> (Poisson family, log link, robust SEs): exponentiating the exposure coefficient gives us RR, how convenient! But there’s a catch. With a binary outcome, plain Poisson overestimates the variance, so the CIs are too wide. Use robust (sandwich) standard errors to fix this, e.g. sandwich::vcovHC() in R. Predicted “risks” can also exceed 1, so don’t use the model for predictions.</li>
</ul>
<p>Another reason to use RR to communicate effect size is that OR is non-collapsible. What do that mean? <img src="https://s.w.org/images/core/emoji/13.0.0/72x72/1f937-200d-2642-fe0f.png" alt="🤷‍♂️" class="wp-smiley" style="height: 1em; max-height: 1em;" /> I’ve tried to understand this several times in the past, I thought I got it but it was an illusion of understanding. <img src="https://s.w.org/images/core/emoji/13.0.0/72x72/1f923.png" alt="🤣" class="wp-smiley" style="height: 1em; max-height: 1em;" /> We’ll have to learn and go deeper on what that means next time with simulations and examples. Let’s focus on our current task.</p>




<h2 id="sim">Simulate Baseline Rate and RR
  <a href="https://www.kenkoonwong.com/blog/modified-poisson/#sim" rel="nofollow" target="_blank"><svg class="anchor-symbol" aria-hidden="true" height="26" width="26" viewBox="0 0 22 22" xmlns="http://www.w3.org/2000/svg">
      <path d="M0 0h24v24H0z" fill="currentColor"></path>
      <path d="M3.9 12c0-1.71 1.39-3.1 3.1-3.1h4V7H7c-2.76.0-5 2.24-5 5s2.24 5 5 5h4v-1.9H7c-1.71.0-3.1-1.39-3.1-3.1zM8 13h8v-2H8v2zm9-6h-4v1.9h4c1.71.0 3.1 1.39 3.1 3.1s-1.39 3.1-3.1 3.1h-4V17h4c2.76.0 5-2.24 5-5s-2.24-5-5-5z"></path>
    </svg></a>
</h2>
<pre>library(tidyverse)
library(broom)
library(sandwich)
library(lmtest)

set.seed(1)
n &lt;- 1300
baseline &lt;- log(0.06) # 6% base rate
rr &lt;- log(0.6) # RR of 0.6, meaning treatment reduces risk for 40% compared to non-treatment (noticed how we switched the term exposure with treatment here)

x &lt;- rbinom(n,1,0.5)
p &lt;- exp(baseline + rr*x)
y &lt;- rbinom(n, 1, p)
</pre><p>We’ve not simulated with the above setting before. So, let’s try to explain so that our future self can return and recall what’s going on here.</p>
<p>So in Poisson regression, we have log link function. So, we can model the log of the expected count as a linear combination of the predictors. In this case, we have a binary predictor x (0 or 1) and we want to simulate a binary outcome y (0 or 1) based on a baseline risk and a risk ratio. Poisson formula is log(λ) = β0 + β1*x, where λ is the expected count (or rate), β0 is the intercept (baseline log risk), and β1 is the coefficient for x (log risk ratio). To get probability of the Poisson distribution, we can exponentiate the linear predictor to get λ = exp(β0 + β1*x). Then we can use this λ as the probability of success in a Bernoulli trial to simulate our binary outcome y. Later on, we can add confounder to it on the equation as well.</p>
<pre>table(y)

## y
##    0    1 
## 1228   72
</pre><p>Pretty small event isn’t it? Let’s start with this</p>




<h2 id="comparison">Comparison
  <a href="https://www.kenkoonwong.com/blog/modified-poisson/#comparison" rel="nofollow" target="_blank"><svg class="anchor-symbol" aria-hidden="true" height="26" width="26" viewBox="0 0 22 22" xmlns="http://www.w3.org/2000/svg">
      <path d="M0 0h24v24H0z" fill="currentColor"></path>
      <path d="M3.9 12c0-1.71 1.39-3.1 3.1-3.1h4V7H7c-2.76.0-5 2.24-5 5s2.24 5 5 5h4v-1.9H7c-1.71.0-3.1-1.39-3.1-3.1zM8 13h8v-2H8v2zm9-6h-4v1.9h4c1.71.0 3.1 1.39 3.1 3.1s-1.39 3.1-3.1 3.1h-4V17h4c2.76.0 5-2.24 5-5s-2.24-5-5-5z"></path>
    </svg></a>
</h2>




<h3 id="poisson">Poisson Regression
  <a href="https://www.kenkoonwong.com/blog/modified-poisson/#poisson" rel="nofollow" target="_blank"><svg class="anchor-symbol" aria-hidden="true" height="26" width="26" viewBox="0 0 22 22" xmlns="http://www.w3.org/2000/svg">
      <path d="M0 0h24v24H0z" fill="currentColor"></path>
      <path d="M3.9 12c0-1.71 1.39-3.1 3.1-3.1h4V7H7c-2.76.0-5 2.24-5 5s2.24 5 5 5h4v-1.9H7c-1.71.0-3.1-1.39-3.1-3.1zM8 13h8v-2H8v2zm9-6h-4v1.9h4c1.71.0 3.1 1.39 3.1 3.1s-1.39 3.1-3.1 3.1h-4V17h4c2.76.0 5-2.24 5-5s-2.24-5-5-5z"></path>
    </svg></a>
</h3>
<pre>model_poisson &lt;- glm(y ~ x, family = poisson)
(model_poisson_df &lt;- tidy(model_poisson, exponentiate = T, conf.int = T))

## # A tibble: 2 × 7
##   term        estimate std.error statistic  p.value conf.low conf.high
##   &lt;chr&gt;          &lt;dbl&gt;     &lt;dbl&gt;     &lt;dbl&gt;    &lt;dbl&gt;    &lt;dbl&gt;     &lt;dbl&gt;
## 1 (Intercept)   0.0675     0.147    -18.3  1.24e-74   0.0499    0.0890
## 2 x             0.622      0.245     -1.94 5.28e- 2   0.379     0.997
</pre><p>Remember, Poisson assumes that the mean is equal to the variance. But with binary outcome, the variance is p*(1-p), which is less than the mean (p). So, Poisson overestimates the variance, leading to wider confidence intervals. Also notice that the exponentiated coef of x is very close to our truth <code>0.6</code>? <img src="https://s.w.org/images/core/emoji/13.0.0/72x72/1f64c.png" alt="🙌" class="wp-smiley" style="height: 1em; max-height: 1em;" /> Wow! I would never have thought we can use Poisson model for binary data! Let’s keep an eye on the 95%CI width, it’s 0.6180093</p>




<h3 id="logbin">Log Binomial Regression
  <a href="https://www.kenkoonwong.com/blog/modified-poisson/#logbin" rel="nofollow" target="_blank"><svg class="anchor-symbol" aria-hidden="true" height="26" width="26" viewBox="0 0 22 22" xmlns="http://www.w3.org/2000/svg">
      <path d="M0 0h24v24H0z" fill="currentColor"></path>
      <path d="M3.9 12c0-1.71 1.39-3.1 3.1-3.1h4V7H7c-2.76.0-5 2.24-5 5s2.24 5 5 5h4v-1.9H7c-1.71.0-3.1-1.39-3.1-3.1zM8 13h8v-2H8v2zm9-6h-4v1.9h4c1.71.0 3.1 1.39 3.1 3.1s-1.39 3.1-3.1 3.1h-4V17h4c2.76.0 5-2.24 5-5s-2.24-5-5-5z"></path>
    </svg></a>
</h3>
<pre>model_bin &lt;- tryCatch(
  glm(y ~ x, family = binomial(&quot;log&quot;)), #notice the link function here is log, not logit?
  error = function(e) NULL
)

(model_bin_df &lt;- tidy(model_bin, exponentiate = T, conf.int = T))

## # A tibble: 2 × 7
##   term        estimate std.error statistic  p.value conf.low conf.high
##   &lt;chr&gt;          &lt;dbl&gt;     &lt;dbl&gt;     &lt;dbl&gt;    &lt;dbl&gt;    &lt;dbl&gt;     &lt;dbl&gt;
## 1 (Intercept)   0.0675     0.142    -18.9  6.63e-80   0.0503    0.0880
## 2 x             0.622      0.239     -1.99 4.68e- 2   0.384     0.985
</pre><p>wow, same estimate! But smalled 95% CI, which is because of smaller SE! The width of 95%CI is 0.6007632. Now let’s take a look at logistic regression.</p>
<blockquote>
<p>Now one might wonder, if log binomial regression is the OG, why don’t we use this? We can, but it has a convergence issue, especially when we have continuous covariates or high baseline risk. That is also why we sometimes have to use <code>tryCatch</code> for the error.</p>
</blockquote>




<h3 id="logit">Logistic Regression with Logit Link
  <a href="https://www.kenkoonwong.com/blog/modified-poisson/#logit" rel="nofollow" target="_blank"><svg class="anchor-symbol" aria-hidden="true" height="26" width="26" viewBox="0 0 22 22" xmlns="http://www.w3.org/2000/svg">
      <path d="M0 0h24v24H0z" fill="currentColor"></path>
      <path d="M3.9 12c0-1.71 1.39-3.1 3.1-3.1h4V7H7c-2.76.0-5 2.24-5 5s2.24 5 5 5h4v-1.9H7c-1.71.0-3.1-1.39-3.1-3.1zM8 13h8v-2H8v2zm9-6h-4v1.9h4c1.71.0 3.1 1.39 3.1 3.1s-1.39 3.1-3.1 3.1h-4V17h4c2.76.0 5-2.24 5-5s-2.24-5-5-5z"></path>
    </svg></a>
</h3>
<pre>model_logit &lt;- glm(y ~ x, family = binomial(&quot;logit&quot;))
(model_logit_df &lt;- tidy(model_logit, exponentiate = T, conf.int = T))

## # A tibble: 2 × 7
##   term        estimate std.error statistic  p.value conf.low conf.high
##   &lt;chr&gt;          &lt;dbl&gt;     &lt;dbl&gt;     &lt;dbl&gt;    &lt;dbl&gt;    &lt;dbl&gt;     &lt;dbl&gt;
## 1 (Intercept)   0.0724     0.153    -17.2  3.06e-66   0.0530    0.0965
## 2 x             0.605      0.252     -1.99 4.62e- 2   0.365     0.984
</pre><p>OK, remember we mentioned early? the exponentiated coefficient does not give an RR, it’s OR, though very close to our truth, because the event is rare. But the width of 95%CI is 0.6189336. So, we can see that the logistic regression has a wider CI than the log-binomial regression, which is expected because the log-binomial model is more efficient for estimating RR when the outcome is binary.</p>




<h3 id="modpoisson">Poisson Regression with Robust Standard Error (Modified Poisson)
  <a href="https://www.kenkoonwong.com/blog/modified-poisson/#modpoisson" rel="nofollow" target="_blank"><svg class="anchor-symbol" aria-hidden="true" height="26" width="26" viewBox="0 0 22 22" xmlns="http://www.w3.org/2000/svg">
      <path d="M0 0h24v24H0z" fill="currentColor"></path>
      <path d="M3.9 12c0-1.71 1.39-3.1 3.1-3.1h4V7H7c-2.76.0-5 2.24-5 5s2.24 5 5 5h4v-1.9H7c-1.71.0-3.1-1.39-3.1-3.1zM8 13h8v-2H8v2zm9-6h-4v1.9h4c1.71.0 3.1 1.39 3.1 3.1s-1.39 3.1-3.1 3.1h-4V17h4c2.76.0 5-2.24 5-5s-2.24-5-5-5z"></path>
    </svg></a>
</h3>
<pre>(model_modpoisson &lt;- coeftest(model_poisson, vcov = vcovHC(model_poisson, type = &quot;HC0&quot;)) |&gt;
  tidy(conf.int = TRUE) |&gt; #apparently exp not supported in coeftest from broom
  mutate(across(c(estimate, conf.low, conf.high), exp)))

## # A tibble: 2 × 7
##   term        estimate std.error statistic  p.value conf.low conf.high
##   &lt;chr&gt;          &lt;dbl&gt;     &lt;dbl&gt;     &lt;dbl&gt;    &lt;dbl&gt;    &lt;dbl&gt;     &lt;dbl&gt;
## 1 (Intercept)   0.0675     0.142    -18.9  6.67e-80   0.0511    0.0893
## 2 x             0.622      0.239     -1.99 4.68e- 2   0.389     0.993
</pre><p>Alright, accurate estimate (well, we didn’t change it from Poisson result), and smaller CI width than Poisson regression, but still wider than log-binomial regression. The width of 95%CI is 0.6040859 by very small amount! And doesn’t seem like there is convergence issue with modified poisson, which is good. <img src="https://s.w.org/images/core/emoji/13.0.0/72x72/1f44d.png" alt="👍" class="wp-smiley" style="height: 1em; max-height: 1em;" /> We can read more about this here 
<a href="https://academic.oup.com/aje/article-abstract/159/7/702/71883?login=false" rel="nofollow" target="_blank">Zou G - A Modified Poisson Regression Approach to Prospective Studies with Binary Data</a></p>
<p>Let’s compare all of them with dataviz
<img src="https://i1.wp.com/www.kenkoonwong.com/blog/modified-poisson/index_files/figure-html/unnamed-chunk-8-1.png?w=450&#038;ssl=1" alt="" data-recalc-dims="1" /></p>




<h3 id="highevent">High Event Rates
  <a href="https://www.kenkoonwong.com/blog/modified-poisson/#highevent" rel="nofollow" target="_blank"><svg class="anchor-symbol" aria-hidden="true" height="26" width="26" viewBox="0 0 22 22" xmlns="http://www.w3.org/2000/svg">
      <path d="M0 0h24v24H0z" fill="currentColor"></path>
      <path d="M3.9 12c0-1.71 1.39-3.1 3.1-3.1h4V7H7c-2.76.0-5 2.24-5 5s2.24 5 5 5h4v-1.9H7c-1.71.0-3.1-1.39-3.1-3.1zM8 13h8v-2H8v2zm9-6h-4v1.9h4c1.71.0 3.1 1.39 3.1 3.1s-1.39 3.1-3.1 3.1h-4V17h4c2.76.0 5-2.24 5-5s-2.24-5-5-5z"></path>
    </svg></a>
</h3>
<p>Let’s set baseline rate to 80%</p>
<pre>## y
##   0   1 
## 441 859

## # A tibble: 4 × 5
##   model            estimate conf.low conf.high width
##   &lt;fct&gt;               &lt;dbl&gt;    &lt;dbl&gt;     &lt;dbl&gt; &lt;dbl&gt;
## 1 Poisson             0.631    0.548     0.724 0.176
## 2 Log Binomial        0.631    0.577     0.686 0.109
## 3 Logistic            0.253    0.197     0.323 0.125
## 4 Modified Poisson    0.631    0.578     0.688 0.109
</pre><img src="https://i0.wp.com/www.kenkoonwong.com/blog/modified-poisson/index_files/figure-html/unnamed-chunk-9-1.png?w=450&#038;ssl=1" alt="" data-recalc-dims="1" />
<p>Wow, how about that! OR no longer is interchangeable as RR, 95% CI is wider for Poisson but for log binomial and modified Poisson, the 95% CIs are narrower and close to each other. Let’s increass the RR and see if log binomial breaks</p>




<h3 id="high-rr">High RR
  <a href="https://www.kenkoonwong.com/blog/modified-poisson/#high-rr" rel="nofollow" target="_blank"><svg class="anchor-symbol" aria-hidden="true" height="26" width="26" viewBox="0 0 22 22" xmlns="http://www.w3.org/2000/svg">
      <path d="M0 0h24v24H0z" fill="currentColor"></path>
      <path d="M3.9 12c0-1.71 1.39-3.1 3.1-3.1h4V7H7c-2.76.0-5 2.24-5 5s2.24 5 5 5h4v-1.9H7c-1.71.0-3.1-1.39-3.1-3.1zM8 13h8v-2H8v2zm9-6h-4v1.9h4c1.71.0 3.1 1.39 3.1 3.1s-1.39 3.1-3.1 3.1h-4V17h4c2.76.0 5-2.24 5-5s-2.24-5-5-5z"></path>
    </svg></a>
</h3>
<p>Let’s set RR as 2 and base rate as 30%</p>
<pre>## y
##   0   1 
## 749 551

## # A tibble: 4 × 5
##   model            estimate conf.low conf.high width
##   &lt;fct&gt;               &lt;dbl&gt;    &lt;dbl&gt;     &lt;dbl&gt; &lt;dbl&gt;
## 1 Poisson              2.02     1.70      2.42 0.713
## 2 Log Binomial         2.02     1.77      2.33 0.558
## 3 Logistic             3.42     2.72      4.31 1.59 
## 4 Modified Poisson     2.02     1.77      2.32 0.556
</pre><img src="https://i2.wp.com/www.kenkoonwong.com/blog/modified-poisson/index_files/figure-html/unnamed-chunk-10-1.png?w=450&#038;ssl=1" alt="" data-recalc-dims="1" />
<p>Wow! log binomial and modified poisson still win! Look at logistic regression, the exponentiated coefficient is no longer close to RR. So far this still doesn’t break log bin, let’s push further.</p>




<h3 id="very-high-rr">Very High RR
  <a href="https://www.kenkoonwong.com/blog/modified-poisson/#very-high-rr" rel="nofollow" target="_blank"><svg class="anchor-symbol" aria-hidden="true" height="26" width="26" viewBox="0 0 22 22" xmlns="http://www.w3.org/2000/svg">
      <path d="M0 0h24v24H0z" fill="currentColor"></path>
      <path d="M3.9 12c0-1.71 1.39-3.1 3.1-3.1h4V7H7c-2.76.0-5 2.24-5 5s2.24 5 5 5h4v-1.9H7c-1.71.0-3.1-1.39-3.1-3.1zM8 13h8v-2H8v2zm9-6h-4v1.9h4c1.71.0 3.1 1.39 3.1 3.1s-1.39 3.1-3.1 3.1h-4V17h4c2.76.0 5-2.24 5-5s-2.24-5-5-5z"></path>
    </svg></a>
</h3>
<p>Let’s set RR to 15? base rate of 6%</p>
<pre>## y
##   0   1 
## 697 603

## # A tibble: 4 × 5
##   model            estimate conf.low conf.high  width
##   &lt;fct&gt;               &lt;dbl&gt;    &lt;dbl&gt;     &lt;dbl&gt;  &lt;dbl&gt;
## 1 Poisson              13.3     9.98      18.2   8.26
## 2 Log Binomial         NA      NA         NA    NA   
## 3 Logistic            124.     84.2      187.  103.  
## 4 Modified Poisson     13.3    10.1       17.6   7.57

## Warning: Removed 1 row containing missing values or values outside the scale range
## (`geom_pointrange()`).
</pre><img src="https://i0.wp.com/www.kenkoonwong.com/blog/modified-poisson/index_files/figure-html/unnamed-chunk-11-1.png?w=450&#038;ssl=1" alt="" data-recalc-dims="1" />
<p>umm, ok that’s a bit hard to see. We notice that log binomial did not converge and logistic regression is estimating odds ratio, not RR lol. Let’s remove logisic regression and compare poisson to modified poisson.</p>
<img src="https://i1.wp.com/www.kenkoonwong.com/blog/modified-poisson/index_files/figure-html/unnamed-chunk-12-1.png?w=450&#038;ssl=1" alt="" data-recalc-dims="1" />
<p>Alright! We’ve seen in the past that log binomial and modified poisson estimates and SE are pretty close, and since our log binomial model could not converge, modified Poisson is our winner! <img src="https://s.w.org/images/core/emoji/13.0.0/72x72/1f947.png" alt="🥇" class="wp-smiley" style="height: 1em; max-height: 1em;" /></p>




<h2 id="repeated">Repeat Measures
  <a href="https://www.kenkoonwong.com/blog/modified-poisson/#repeated" rel="nofollow" target="_blank"><svg class="anchor-symbol" aria-hidden="true" height="26" width="26" viewBox="0 0 22 22" xmlns="http://www.w3.org/2000/svg">
      <path d="M0 0h24v24H0z" fill="currentColor"></path>
      <path d="M3.9 12c0-1.71 1.39-3.1 3.1-3.1h4V7H7c-2.76.0-5 2.24-5 5s2.24 5 5 5h4v-1.9H7c-1.71.0-3.1-1.39-3.1-3.1zM8 13h8v-2H8v2zm9-6h-4v1.9h4c1.71.0 3.1 1.39 3.1 3.1s-1.39 3.1-3.1 3.1h-4V17h4c2.76.0 5-2.24 5-5s-2.24-5-5-5z"></path>
    </svg></a>
</h2>
<p>Alright, now that we’re convinced (though we really need to do lots of replicates of the above to “convince” ourselves that it’s not just one dataset that did this - let’s spawn an agent to push these to computer cluster and replicate for us while we go on… 
<a href="https://www.kenkoonwong.com/blog/modified-poisson/#replicate-of-sim" rel="nofollow" target="_blank">if you’re curious click here</a>), let’s insert some interesting thing here. What if, we have repeated measure? Let’s simulate 65 subjects with 20 visits each, treatment fixed per subject and a subject-level random effect, then checked how often each method’s 95% CI actually contained the true RR (~0.63).</p>
<pre>library(geepack)

set.seed(1)
n_id &lt;- 65     # subjects
n_visit &lt;- 20  # visits per subject (65 x 20 = 1300 rows)
baseline &lt;- log(0.15) # 15% base rate
rr &lt;- log(0.6) # RR of 0.6

id &lt;- rep(1:n_id, each = n_visit)
x &lt;- rep(rbinom(n_id, 1, 0.5), each = n_visit) # treatment fixed per subject
u &lt;- rep(rnorm(n_id, 0, 1), each = n_visit)    # subject random effect, strong clustering
p &lt;- pmin(exp(baseline + rr*x + u), 1)
y &lt;- rbinom(n_id * n_visit, 1, p)

df &lt;- tibble(id, x, y)

table(df$y)

## 
##    0    1 
## 1078  222

# true marginal RR (pmin caps a few risks at 1, so it&#39;s slightly off 0.6)
u_big &lt;- rnorm(1e6, 0, 1)
true_rr &lt;- mean(pmin(exp(baseline + rr + u_big), 1)) / mean(pmin(exp(baseline + u_big), 1))
true_rr

## [1] 0.6271079

# models
model_poisson_rm &lt;- glm(y ~ x, family = poisson, data = df)
model_gee_rm &lt;- geeglm(y ~ x, family = poisson(&quot;log&quot;), data = df, id = id, corstr = &quot;independence&quot;)

exp_ct &lt;- function(ct) {
  ct |&gt;
    tidy(conf.int = TRUE) |&gt;
    mutate(across(c(estimate, conf.low, conf.high), exp))
}

results_rm &lt;- bind_rows(
  tidy(model_poisson_rm, exponentiate = T, conf.int = T) |&gt; mutate(model = &quot;Poisson&quot;),
  coeftest(model_poisson_rm, vcov = vcovHC(model_poisson_rm, type = &quot;HC0&quot;)) |&gt; exp_ct() |&gt; mutate(model = &quot;Modified Poisson&quot;),
  coeftest(model_poisson_rm, vcov = vcovCL(model_poisson_rm, cluster = ~id, type = &quot;HC0&quot;, cadjust = FALSE)) |&gt; exp_ct() |&gt; mutate(model = &quot;Modified Poisson (cluster)&quot;),
  tidy(model_gee_rm, exponentiate = T, conf.int = T) |&gt; mutate(model = &quot;GEE&quot;)
) |&gt;
  filter(term == &quot;x&quot;) |&gt;
  select(model, estimate, std.error, conf.low, conf.high) |&gt;
  mutate(width = conf.high - conf.low,
         model = factor(model, levels = c(&quot;Poisson&quot;, &quot;Modified Poisson&quot;, &quot;Modified Poisson (cluster)&quot;, &quot;GEE&quot;)))

results_rm

## # A tibble: 4 × 6
##   model                      estimate std.error conf.low conf.high width
##   &lt;fct&gt;                         &lt;dbl&gt;     &lt;dbl&gt;    &lt;dbl&gt;     &lt;dbl&gt; &lt;dbl&gt;
## 1 Poisson                        1.13     0.134    0.867      1.47 0.603
## 2 Modified Poisson               1.13     0.122    0.888      1.43 0.547
## 3 Modified Poisson (cluster)     1.13     0.243    0.701      1.82 1.12 
## 4 GEE                            1.13     0.243    0.701      1.82 1.12

results_rm |&gt;
  ggplot(aes(x = model, y = estimate, ymin = conf.low, ymax = conf.high)) +
  geom_pointrange() +
  geom_hline(yintercept = true_rr, linetype = &quot;dashed&quot;, color = &quot;red&quot;) +
  ylim(0, 2.5)
</pre><img src="https://i1.wp.com/www.kenkoonwong.com/blog/modified-poisson/index_files/figure-html/unnamed-chunk-13-1.png?w=450&#038;ssl=1" alt="" data-recalc-dims="1" />
<p>Wow! Remember we said poisson SE is bigger than modified poisson, but now both poisson and modified poisson have narrower 95%CI than the clustering methods. Which is right? I mean, we did simulate repeated measures with strong clustering, so the clustering methods should be more appropriate, right? But the 95%CI didn’t even cover the truth… let’s call the agent again.</p>
<p><img src="https://i0.wp.com/www.kenkoonwong.com/blog/modified-poisson/replicates_repeated_measures.png?w=578&#038;ssl=1" alt="" data-recalc-dims="1"></p>
<p>Holy Mac! Yea poisson and modified poisson without clusterings have narrow CI but look at their coverage! Poor! And the clustering methods have wider CI but their coverage is much better, close to 95%. So, we can see that the clustering methods are more appropriate for repeated measures data, even though they have wider confidence intervals. Alright, right now I’m pretty convinced about modified poisson and use clustering if appropriate. Next, let’s see if we can estimate RR with g-computation and bootstrap by subject to see if we can get a similar result as modified poisson with robust SE + clustering.</p>




<h3 id="gcomp">RR Without Modified Poisson with LR G-computation
  <a href="https://www.kenkoonwong.com/blog/modified-poisson/#gcomp" rel="nofollow" target="_blank"><svg class="anchor-symbol" aria-hidden="true" height="26" width="26" viewBox="0 0 22 22" xmlns="http://www.w3.org/2000/svg">
      <path d="M0 0h24v24H0z" fill="currentColor"></path>
      <path d="M3.9 12c0-1.71 1.39-3.1 3.1-3.1h4V7H7c-2.76.0-5 2.24-5 5s2.24 5 5 5h4v-1.9H7c-1.71.0-3.1-1.39-3.1-3.1zM8 13h8v-2H8v2zm9-6h-4v1.9h4c1.71.0 3.1 1.39 3.1 3.1s-1.39 3.1-3.1 3.1h-4V17h4c2.76.0 5-2.24 5-5s-2.24-5-5-5z"></path>
    </svg></a>
</h3>
<pre># g-computation: fit logistic, predict everyone as treated vs untreated, take ratio of mean risks
gcomp_rr &lt;- function(data) {
  m &lt;- glm(y ~ x, family = binomial(&quot;logit&quot;), data = data)
  p1 &lt;- mean(predict(m, newdata = mutate(data, x = 1), type = &quot;response&quot;))
  p0 &lt;- mean(predict(m, newdata = mutate(data, x = 0), type = &quot;response&quot;))
  p1 / p0
}

rr_gcomp &lt;- gcomp_rr(df)

# bootstrap by subject: resample subjects (not rows), keep all their visits together
df_split &lt;- split(df, df$id)

set.seed(1)
boot_rr &lt;- map_dbl(1:1000, ~ {
  samp &lt;- sample(names(df_split), replace = TRUE)
  boot_df &lt;- bind_rows(df_split[samp], .id = &quot;boot_id&quot;) # new id so duplicated subjects count separately
  gcomp_rr(boot_df)
})

results_gcomp &lt;- tibble(
  model = &quot;G-comp (cluster bootstrap)&quot;,
  estimate = rr_gcomp,
  conf.low = quantile(boot_rr, 0.025),
  conf.high = quantile(boot_rr, 0.975)
) |&gt;
  mutate(width = conf.high - conf.low)

results_gcomp

## # A tibble: 1 × 5
##   model                      estimate conf.low conf.high width
##   &lt;chr&gt;                         &lt;dbl&gt;    &lt;dbl&gt;     &lt;dbl&gt; &lt;dbl&gt;
## 1 G-comp (cluster bootstrap)     1.13    0.690      1.80  1.11

bind_rows(results_rm, results_gcomp) |&gt;
  mutate(model = factor(model, levels = c(&quot;Poisson&quot;, &quot;Modified Poisson&quot;, &quot;Modified Poisson (cluster)&quot;, &quot;GEE&quot;, &quot;G-comp (cluster bootstrap)&quot;))) |&gt;
  ggplot(aes(x = model, y = estimate, ymin = conf.low, ymax = conf.high)) +
  geom_pointrange() +
  geom_hline(yintercept = true_rr, linetype = &quot;dashed&quot;, color = &quot;red&quot;) +
  ylim(0, 2.5)
</pre><img src="https://i1.wp.com/www.kenkoonwong.com/blog/modified-poisson/index_files/figure-html/unnamed-chunk-14-1.png?w=450&#038;ssl=1" alt="" data-recalc-dims="1" />
<p>Look at that! G-computation with logistic regression gives us the exact same RR as modified Poisson. That makes sense, because with only x in the model, both are just computing the risk in the treated divided by the risk in the untreated. And bootstrapping by subject (not by row!) gives a 95% CI almost identical to the cluster robust SE and GEE. Should we call the agent again?</p>
<p><img src="https://i1.wp.com/www.kenkoonwong.com/blog/modified-poisson/replicates_repeated_measures_gcomp.png?w=578&#038;ssl=1" alt="" data-recalc-dims="1">
Et viola! Same same! woo hoo! <img src="https://s.w.org/images/core/emoji/13.0.0/72x72/1f64c.png" alt="🙌" class="wp-smiley" style="height: 1em; max-height: 1em;" /></p>




<h2 id="replicate-of-sim">Replicates of Our 4 Scenarios
  <a href="https://www.kenkoonwong.com/blog/modified-poisson/#replicate-of-sim" rel="nofollow" target="_blank"><svg class="anchor-symbol" aria-hidden="true" height="26" width="26" viewBox="0 0 22 22" xmlns="http://www.w3.org/2000/svg">
      <path d="M0 0h24v24H0z" fill="currentColor"></path>
      <path d="M3.9 12c0-1.71 1.39-3.1 3.1-3.1h4V7H7c-2.76.0-5 2.24-5 5s2.24 5 5 5h4v-1.9H7c-1.71.0-3.1-1.39-3.1-3.1zM8 13h8v-2H8v2zm9-6h-4v1.9h4c1.71.0 3.1 1.39 3.1 3.1s-1.39 3.1-3.1 3.1h-4V17h4c2.76.0 5-2.24 5-5s-2.24-5-5-5z"></path>
    </svg></a>
</h2>
<p><img src="https://i1.wp.com/www.kenkoonwong.com/blog/modified-poisson/replicates_normal.png?w=578&#038;ssl=1" alt="" data-recalc-dims="1">
<img src="https://i0.wp.com/www.kenkoonwong.com/blog/modified-poisson/replicates_high_event_rate.png?w=578&#038;ssl=1" alt="" data-recalc-dims="1">
<img src="https://i1.wp.com/www.kenkoonwong.com/blog/modified-poisson/replicates_high_rr.png?w=578&#038;ssl=1" alt="" data-recalc-dims="1">
<img src="https://i2.wp.com/www.kenkoonwong.com/blog/modified-poisson/replicates_very_high_rr.png?w=578&#038;ssl=1" alt="" data-recalc-dims="1">
Now we’ve seen it! All 4 scenarios with replicates showed pretty convincing evidence that modified poisson is a good choice for estimating risk ratios, especially when log-binomial regression fails to converge. Not only we care about convergence and narrow CI, we care about appropriate CI with appropriate coverage as we saw from the repeated measures simulation.</p>




<h2 id="opportunities">Opportunities For Improvement
  <a href="https://www.kenkoonwong.com/blog/modified-poisson/#opportunities" rel="nofollow" target="_blank"><svg class="anchor-symbol" aria-hidden="true" height="26" width="26" viewBox="0 0 22 22" xmlns="http://www.w3.org/2000/svg">
      <path d="M0 0h24v24H0z" fill="currentColor"></path>
      <path d="M3.9 12c0-1.71 1.39-3.1 3.1-3.1h4V7H7c-2.76.0-5 2.24-5 5s2.24 5 5 5h4v-1.9H7c-1.71.0-3.1-1.39-3.1-3.1zM8 13h8v-2H8v2zm9-6h-4v1.9h4c1.71.0 3.1 1.39 3.1 3.1s-1.39 3.1-3.1 3.1h-4V17h4c2.76.0 5-2.24 5-5s-2.24-5-5-5z"></path>
    </svg></a>
</h2>
<ul>
<li>No confounders yet! We only had one binary treatment. I heard this is where log-binomial really struggles to converge.</li>
<li>Explore non-collapsibility of OR</li>
<li>Other GEE correlations. We only used independence, to match modified Poisson. What about exchangeable?</li>
<li>Rescuing log-binomial. We let it fail. Starting values might fix it. Is it the model, or just the algorithm?</li>
<li>Risk difference. We only looked at RR. Absolute risk difference often matters more to patients and clinicians.</li>
<li>Need to try to solving robust/sandwich SE from scratch to know how it actually works</li>
</ul>




<h2 id="lessons">Lessons learnt
  <a href="https://www.kenkoonwong.com/blog/modified-poisson/#lessons" rel="nofollow" target="_blank"><svg class="anchor-symbol" aria-hidden="true" height="26" width="26" viewBox="0 0 22 22" xmlns="http://www.w3.org/2000/svg">
      <path d="M0 0h24v24H0z" fill="currentColor"></path>
      <path d="M3.9 12c0-1.71 1.39-3.1 3.1-3.1h4V7H7c-2.76.0-5 2.24-5 5s2.24 5 5 5h4v-1.9H7c-1.71.0-3.1-1.39-3.1-3.1zM8 13h8v-2H8v2zm9-6h-4v1.9h4c1.71.0 3.1 1.39 3.1 3.1s-1.39 3.1-3.1 3.1h-4V17h4c2.76.0 5-2.24 5-5s-2.24-5-5-5z"></path>
    </svg></a>
</h2>
<ul>
<li>learnt what modified poisson with robust SE is</li>
<li>learnt about clustering with <code>vcovCl</code> or <code>geepack</code> package</li>
<li>learnt that modified poisson with robuse SE w/wo clustering (depending on data) really matters because SE could be wrong either too narrow or too wide!</li>
<li>thank goodness to Claude code where I can paste my rmarkdown of my simulation and models so that it can send replicates to cluster and create the plot for me! Saved me a lot of time trying to code from the ground up! Will definitely be using this more!</li>
</ul>
<p>If you like this article:</p>
<ul>
<li>please feel free to send me a 
<a href="https://www.kenkoonwong.com/blog/" rel="nofollow" target="_blank">comment or visit my other blogs</a></li>
<li>please feel free to follow me on 
<a href="https://bsky.app/profile/kenkoonwong.bsky.social" rel="nofollow" target="_blank">BlueSky</a>, 
<a href="https://twitter.com/kenkoonwong/" rel="nofollow" target="_blank">twitter</a>, 
<a href="https://github.com/kenkoonwong/" rel="nofollow" target="_blank">GitHub</a> or 
<a href="https://rstats.me/@kenkoonwong" rel="nofollow" target="_blank">Mastodon</a></li>
<li>if you would like collaborate please feel free to 
<a href="https://www.kenkoonwong.com/contact/" rel="nofollow" target="_blank">contact me</a></li>
</ul>

<div style="border: 1px solid; background: none repeat scroll 0 0 #EDEDED; margin: 1px; font-size: 13px;">
<div style="text-align: center;">To <strong>leave a comment</strong> for the author, please follow the link and comment on their blog: <strong><a href="https://www.kenkoonwong.com/blog/modified-poisson/"> r on Everyday Is A School Day</a></strong>.</div>
<hr />
<a href="https://www.r-bloggers.com/" rel="nofollow">R-bloggers.com</a> offers <strong><a href="https://feedburner.google.com/fb/a/mailverify?uri=RBloggers" rel="nofollow">daily e-mail updates</a></strong> about <a title="The R Project for Statistical Computing" href="https://www.r-project.org/" rel="nofollow">R</a> news and tutorials about <a title="R tutorials" href="https://www.r-bloggers.com/how-to-learn-r-2/" rel="nofollow">learning R</a> and many other topics. <a title="Data science jobs" href="https://www.r-users.com/" rel="nofollow">Click here if you're looking to post or find an R/data-science job</a>.

<hr>Want to share your content on R-bloggers?<a href="https://www.r-bloggers.com/add-your-blog/" rel="nofollow"> click here</a> if you have a blog, or <a href="http://r-posts.com/" rel="nofollow"> here</a> if you don't.
</div><strong>Continue reading</strong>: <a href="https://www.r-bloggers.com/2026/11/why-risk-ratio-is-preferred-what-is-modified-poisson-and-why-do-we-even-care-about-standard-error/">Why Risk Ratio Is Preferred, What is Modified Poisson, and Why Do We Even Care About Standard Error?</a>]]></content:encoded>
					
		
		<enclosure url="" length="0" type="" />

		<post-id xmlns="com-wordpress:feed-additions:1">405010</post-id>	</item>
		<item>
		<title>Hacking Two Hours of Contributions to R</title>
		<link>https://www.r-bloggers.com/2026/11/hacking-two-hours-of-contributions-to-r/</link>
		
		<dc:creator><![CDATA[rOpenSci]]></dc:creator>
		<pubDate>Fri, 20 Nov 2026 00:00:00 +0000</pubDate>
				<category><![CDATA[R bloggers]]></category>
		<guid isPermaLink="false">https://ropensci.org/blog/2026/11/20/hackear-latinr2026/</guid>

					<description><![CDATA[<p>Read it in: Español. LatinR is a conference on the use of R in Research and Development that brings together the Latin American community using our favorite programming language. In 2026 it took place from November 11 to 13 in Medellín, Colombia, toge...</p>
<strong>Continue reading</strong>: <a href="https://www.r-bloggers.com/2026/11/hacking-two-hours-of-contributions-to-r/">Hacking Two Hours of Contributions to R</a>]]></description>
										<content:encoded><![CDATA[<!-- 
<div style="min-height: 30px;">
[social4i size="small" align="align-left"]
</div>
-->

<div style="border: 1px solid; background: none repeat scroll 0 0 #EDEDED; margin: 1px; font-size: 12px;">
[This article was first published on  <strong><a href="https://ropensci.org/blog/2026/11/20/hackear-latinr2026/"> rOpenSci - open tools for open science</a></strong>, and kindly contributed to <a href="https://www.r-bloggers.com/" rel="nofollow">R-bloggers</a>].  (You can report issue about the content on this page <a href="https://www.r-bloggers.com/contact-us/">here</a>)
<hr>Want to share your content on R-bloggers?<a href="https://www.r-bloggers.com/add-your-blog/" rel="nofollow"> click here</a> if you have a blog, or <a href="http://r-posts.com/" rel="nofollow"> here</a> if you don't.
</div>

<p><a href='https://ropensci.org/es/blog/2026/11/20/hackear-latinr2026/' rel="nofollow" target="_blank">Read it in: Español</a>.</p> <p><a href="https://latinr.org/" rel="nofollow" target="_blank">LatinR</a> is a conference on the use of R in Research and Development that brings together the Latin American community using our favorite programming language. In 2026 it took place from November 11 to 13 in Medellín, Colombia, together with the Universidad de Antioquia.</p>
<p>On Friday, November 13, <strong><a href="https://latinr.org/cronograma/hackear/" rel="nofollow" target="_blank">HackeaR</a></strong> took place: a two-hour meetup to work in small groups where experienced people supported those taking their first steps contributing to open projects. In this post we summarize what we worked on and how.</p>
<h2>
What is HackeaR
</h2><p>This event combines the experience of rOpenSci’s <a href="https://ftc-guide.ropensci.org/" rel="nofollow" target="_blank">mini hackathons and mini translathons</a> with the R Dev Days/Sprints of the <a href="https://contributor.r-project.org/events/r-dev-days/" rel="nofollow" target="_blank">R Contributor</a> group.
The idea is that anyone, whether a beginner or an experienced person, can make a real contribution to the R ecosystem.</p>
<p>The focus was on contributions that help both base R and the R packages that make up our ecosystem. Several of these packages and projects are rOpenSci programs. Possible contributions included analyzing and working on issues and pull requests listed on the <a href="https://github.com/orgs/r-devel/projects/14/views/1" rel="nofollow" target="_blank">hackathon board</a>, and improving documentation, and reviewing translations of rOpenSci materials.</p>
<p>Twenty-seven people attended the event; some stayed for the full two hours, while others came and went between the other conference sessions.</p>
<div class="row">
<div class="col-md-6">
<figure><img src="https://i1.wp.com/ropensci.org/blog/2026/11/20/hackear-latinr2026/working_groups.jpeg?w=578&#038;ssl=1"
alt="Participants selecting issues and pull requests to work on during the event, sitting in the room and working on their laptops" data-recalc-dims="1"><figcaption>
<p>Participants selecting issues and pull requests to work on during the event</p>
</figcaption>
</figure>
</div>
<div class="col-md-6">
<figure><img src="https://i2.wp.com/ropensci.org/blog/2026/11/20/hackear-latinr2026/working_groups_2.jpeg?w=578&#038;ssl=1"
alt="More participants selecting issues and pull requests to work on during the event, sitting in the room and working on their laptops" data-recalc-dims="1"><figcaption>
<p>Hackathon participants working on their computers during the event</p>
</figcaption>
</figure>
</div>
</div>
<h2>
The work proposals
</h2><p>To help people decide where to start, we prepared a GitHub project in advance with 25 tasks from different repositories, grouped into three categories: best practices, documentation, and translation.</p>
<h3>
Best practices (9)
</h3><ul>
<li>
<p><strong>Accessibility:</strong> Diana Garcia added alt text to the images in <a href="https://github.com/luisDVA/unheadr/issues/6" rel="nofollow" target="_blank">unheadr</a> <a href="https://github.com/luisDVA/unheadr/pull/13" rel="nofollow" target="_blank">through a pull request</a> that was accepted and closed this issue! <img src="https://s.w.org/images/core/emoji/13.0.0/72x72/1f389.png" alt="🎉" class="wp-smiley" style="height: 1em; max-height: 1em;" />
Riva Quiroga and Jesica Formoso worked on a color contrast problem below the WCAG AA minimum in the <a href="https://github.com/r-devel/rdevguide/issues/274" rel="nofollow" target="_blank">r-devel guide</a>.</p>
</li>
<li>
<p><strong>Base R on different platforms:</strong> Jeroen Ooms added to the dashboard and worked on two pull requests in progress in r-svn, one to <a href="https://github.com/r-devel/r-svn/pull/476" rel="nofollow" target="_blank">fix Alpine on ARM64 and add continuous integration</a> and another to <a href="https://github.com/r-devel/r-svn/pull/478" rel="nofollow" target="_blank">fix the C stack limit on Linux and FreeBSD</a>.</p>
</li>
<li>
<p><strong>stplanr:</strong> the <a href="https://github.com/ropensci/stplanr/issues/567" rel="nofollow" target="_blank">failing actions issue</a> was closed <img src="https://s.w.org/images/core/emoji/13.0.0/72x72/1f389.png" alt="🎉" class="wp-smiley" style="height: 1em; max-height: 1em;" /> and four remain pending, ranging from renaming <code>rnet_merge</code> to an <code>sf</code> method for <code>line_midpoint</code> and a vignette on route networks.</p>
</li>
</ul>
<h3>
Documentation (6)
</h3><ul>
<li>
<p>The “Lost braces” issue, proposed by Kurt Hornik (R Core), consisted of <a href="https://github.com/r-devel/r-dev-day/issues/110" rel="nofollow" target="_blank">sending pull requests to CRAN packages</a> that show the <em>NOTE</em> about <em>“Lost braces”</em> in the Rd files check. During HackeaR, Yanina Bellini Saibene opened a <a href="https://github.com/CDEager/standardize/pull/4" rel="nofollow" target="_blank">pull request for the standardize package</a> that fixes this NOTE, and Ella Kaye, Heather Turner, and Francisco Cardozo worked on other packages for the same issue. Luis Verde explained how to resolve the NOTE, because he had already worked on this topic at previous events in addition to work on this issue. The most frequent cases are a missing backslash before a macro (such as <code>code{...}</code>), braces used for set notation that need to be escaped, and <code>\itemize</code> used where <code>\describe</code> should be. Progress is tracked in the <a href="https://github.com/r-devel/track-lost-braces" rel="nofollow" target="_blank">track-lost-braces</a> repository.</p>
</li>
<li>
<p>Still available are a review of the <a href="https://github.com/ropensci/weathercan" rel="nofollow" target="_blank">weathercan</a> vignettes, improvements to the documentation for publishing packages on <a href="https://r-universe.dev/" rel="nofollow" target="_blank">R-Universe</a>, and three minor fixes in <a href="https://github.com/luisDVA/unheadr" rel="nofollow" target="_blank">unheadr</a> (a typo in the roxygen documentation, a vignette with a deprecated argument, and an example in the README).</p>
</li>
</ul>
<h3>
Translation (10)
</h3><ul>
<li>
<p><strong>rOpenSci materials:</strong> there are open pull requests with translations of the Git course into <a href="https://github.com/ropensci-training/curriculum/pull/116" rel="nofollow" target="_blank">Spanish</a> and Portuguese. <a href="https://github.com/ropensci-training/curriculum/pull/136" rel="nofollow" target="_blank">Francisco Cardozo and Catalina Cañizares took on the Spanish one during the hackathon</a>, and it is in progress; <a href="https://github.com/ropensci-training/curriculum/pulls?q=sort%3Aupdated-desc+is%3Apr+state%3Aopen+label%3Atradu%C3%A7%C3%A3o" rel="nofollow" target="_blank">the Portuguese ones are awaiting review</a>.</p>
</li>
<li>
<p><strong>R messages:</strong> the issue about translating R messages remains open for anyone who wants to join. In Spanish, everything has already been completed, but there is still work to do in Portuguese.</p>
</li>
<li>
<p><strong><a href="https://github.com/eliocamp/rdlocal" rel="nofollow" target="_blank">rdlocal</a>:</strong> Elio Campitelli’s package for making translation easier had a user testing session with Paola Corrales, Evelia Coss Navarrete, Mauricio Gómez Ardila, and Oscar De Leon. They worked on two vignettes, one for people who translate and another for people who use the package. Issues remain open about overwriting modules and about including authorship in the DESCRIPTION file of the translation modules.</p>
</li>
<li>
<p>Other participants, such as Gustavo Bruges and Audrey, reviewed the list of rOpenSci <a href="https://ropensci.org/help-wanted/" rel="nofollow" target="_blank">“Help Wanted” issues</a> and offered their help translating vignettes.</p>
</li>
</ul>
<div class="row">
<div class="col-md-6">
<figure><img src="https://i2.wp.com/ropensci.org/blog/2026/11/20/hackear-latinr2026/learning_togethers.jpeg?w=578&#038;ssl=1"
alt="A mentor and a participant reviewing an assignment together during the event" data-recalc-dims="1"><figcaption>
<p>Learning and working together during the event</p>
</figcaption>
</figure>
</div>
<div class="col-md-6">
<figure><img src="https://i1.wp.com/ropensci.org/blog/2026/11/20/hackear-latinr2026/hybrid.jpeg?w=578&#038;ssl=1"
alt="Three people are sitting in the room, and one of them is holding a laptop, with two people participating online" data-recalc-dims="1"><figcaption>
<p>The hybrid nature of the event, which allows us to work with people from all over the world.</p>
</figcaption>
</figure>
</div>
</div>
<h2>
What we take away
</h2><p>In just two hours, the board showed how varied contributing can be: from alt text or a typo in a README to working together with a package’s authors to improve it.</p>
<p>It also showed that translation and documentation are very valuable entry points, that the support of experienced mentors (such as Luis’s explanation of “Lost braces”) makes it possible for newcomers to contribute right away, and that working in Spanish and Portuguese is a central part of what we do at LatinR.</p>
<p>There are still open issues and pull requests, and that is good news: if you’re left wanting more, you can keep contributing whenever you like. Check out the <a href="https://github.com/orgs/r-devel/projects/14/views/1" rel="nofollow" target="_blank">hackathon board</a> and the <a href="https://ropensci.org/help-wanted/" rel="nofollow" target="_blank">rOpenSci Help Wanted list</a>. You can also join the <a href="https://r-project.zulipchat.com/" rel="nofollow" target="_blank">R Contributors Zulip</a> and the <a href="https://join.slack.com/t/latin-r/shared_invite/zt-2tespojdh-OpXaVcnzOY_SETtv9hqRSQ" rel="nofollow" target="_blank">LatinR Slack</a>, and subscribe to the <a href="https://ropensci.org/news/" rel="nofollow" target="_blank">rOpenSci newsletter</a> to find out about upcoming events like this one.</p>
<p>At the end of the event, we raffled a Platzi scholarship<sup id="fnref:1"><a href="https://ropensci.org/blog/2026/11/20/hackear-latinr2026/#fn:1" class="footnote-ref" role="doc-noteref" rel="nofollow" target="_blank">1</a></sup> among the participants, and Audrey was the one who received the prize. Congratulations! <img src="https://s.w.org/images/core/emoji/13.0.0/72x72/1f389.png" alt="🎉" class="wp-smiley" style="height: 1em; max-height: 1em;" /></p>
<p>Sharing a moment with new and familiar people, working on something we enjoy, learning, and helping the people who develop packages are among the most interesting activities you can do at these events.</p>
<p>Thank you to everyone who participated!</p>
<figure class="center"><img src="https://i1.wp.com/ropensci.org/blog/2026/11/20/hackear-latinr2026/hackear_participants.jpeg?w=578&#038;ssl=1"
alt="A group of 10 people is sitting on stage, smiling, and the Zoom screen shows four other participants connected online." data-recalc-dims="1"><figcaption>
<p>Some of the HackeaR participants at LatinR 2026, both in person and online</p>
</figcaption>
</figure>
<div class="footnotes" role="doc-endnotes">
<hr>
<ol>
<li id="fn:1">
<p>Platzi is an online educational platform <a href="https://ropensci.org/blog/2026/11/20/hackear-latinr2026/#fnref:1" class="footnote-backref" role="doc-backlink" rel="nofollow" target="_blank"><img src="https://s.w.org/images/core/emoji/13.0.0/72x72/21a9.png" alt="↩" class="wp-smiley" style="height: 1em; max-height: 1em;" />︎</a></p>
</li>
</ol>
</div>
<div style="border: 1px solid; background: none repeat scroll 0 0 #EDEDED; margin: 1px; font-size: 13px;">
<div style="text-align: center;">To <strong>leave a comment</strong> for the author, please follow the link and comment on their blog: <strong><a href="https://ropensci.org/blog/2026/11/20/hackear-latinr2026/"> rOpenSci - open tools for open science</a></strong>.</div>
<hr />
<a href="https://www.r-bloggers.com/" rel="nofollow">R-bloggers.com</a> offers <strong><a href="https://feedburner.google.com/fb/a/mailverify?uri=RBloggers" rel="nofollow">daily e-mail updates</a></strong> about <a title="The R Project for Statistical Computing" href="https://www.r-project.org/" rel="nofollow">R</a> news and tutorials about <a title="R tutorials" href="https://www.r-bloggers.com/how-to-learn-r-2/" rel="nofollow">learning R</a> and many other topics. <a title="Data science jobs" href="https://www.r-users.com/" rel="nofollow">Click here if you're looking to post or find an R/data-science job</a>.

<hr>Want to share your content on R-bloggers?<a href="https://www.r-bloggers.com/add-your-blog/" rel="nofollow"> click here</a> if you have a blog, or <a href="http://r-posts.com/" rel="nofollow"> here</a> if you don't.
</div><strong>Continue reading</strong>: <a href="https://www.r-bloggers.com/2026/11/hacking-two-hours-of-contributions-to-r/">Hacking Two Hours of Contributions to R</a>]]></content:encoded>
					
		
		<enclosure url="" length="0" type="" />

		<post-id xmlns="com-wordpress:feed-additions:1">404991</post-id>	</item>
		<item>
		<title>Making the incidental an invitation in building community</title>
		<link>https://www.r-bloggers.com/2026/11/making-the-incidental-an-invitation-in-building-community/</link>
		
		<dc:creator><![CDATA[rOpenSci]]></dc:creator>
		<pubDate>Thu, 19 Nov 2026 00:00:00 +0000</pubDate>
				<category><![CDATA[R bloggers]]></category>
		<guid isPermaLink="false">https://ropensci.org/blog/2026/11/19/comm-call-openscapes/</guid>

					<description><![CDATA[<p>On October 1, 2026 Openscapes hosted a Community Call on Open Communities in the Age of AI. The 1.5-hour event included four speakers, a panel discussion, and questions from participants. Among more than sixty participants, we recognized so many we co...</p>
<strong>Continue reading</strong>: <a href="https://www.r-bloggers.com/2026/11/making-the-incidental-an-invitation-in-building-community/">Making the incidental an invitation in building community</a>]]></description>
										<content:encoded><![CDATA[<!-- 
<div style="min-height: 30px;">
[social4i size="small" align="align-left"]
</div>
-->

<div style="border: 1px solid; background: none repeat scroll 0 0 #EDEDED; margin: 1px; font-size: 12px;">
[This article was first published on  <strong><a href="https://ropensci.org/blog/2026/11/19/comm-call-openscapes/"> rOpenSci - open tools for open science</a></strong>, and kindly contributed to <a href="https://www.r-bloggers.com/" rel="nofollow">R-bloggers</a>].  (You can report issue about the content on this page <a href="https://www.r-bloggers.com/contact-us/">here</a>)
<hr>Want to share your content on R-bloggers?<a href="https://www.r-bloggers.com/add-your-blog/" rel="nofollow"> click here</a> if you have a blog, or <a href="http://r-posts.com/" rel="nofollow"> here</a> if you don't.
</div>

<p>On October 1, 2026 Openscapes hosted a Community Call on Open Communities in the Age of AI. The 1.5-hour event included four speakers, a panel discussion, and questions from participants. Among more than sixty participants, we recognized so many we connect with regularly across our communities! This post synthesizes some themes that we hope will entice you to watch the recording and consider how you intentionally welcome people into the communities you value.</p>
<h2>
The call
</h2><p>It has been just over a month since Openscapes hosted the <a href="https://openscapes.org/events/2026-10-01-community-call-open-communities-ai/" rel="nofollow" target="_blank">Community Call: Open Communities in the age of AI</a>. Why the long delay in this post? Because it was something <em>really</em> good. So good, in fact, that I (Mara) was reticent to recap it—not wanting to diminish what was said. However, the video and notes are available on the call page, so here is a synthesis, not of what was said, but where we (the four panelists) converged. The topic, as Openscapes described it, had a very specific aim:</p>
<blockquote>
<p>“We want to talk about the impact of AI on the growth and maintenance of communities, and the people in those communities. There are discussions happening in many Open Source communities about how to manage and use AI effectively and responsibly &#8211; discussions about increased burden on maintainers, policies for AI-written PRs, etc. Those are important conversations, however, <strong>the conversations about impacts of AI on communities are rare</strong>.”<sup id="fnref:1"><a href="https://ropensci.org/blog/2026/11/19/comm-call-openscapes/#fn:1" class="footnote-ref" role="doc-noteref" rel="nofollow" target="_blank">1</a></sup></p>
</blockquote>
<h2>
How events like this happen
</h2><p>As it so happens, the event itself was a meta example of one solution to themes and challenges we identified. Which means it took work.</p>
<p>This community call did not organize itself. What began as a <a href="https://github.com/Openscapes/how_we_work/issues/475" rel="nofollow" target="_blank">GitHub issue</a> opened by Stefanie Butland in May, inspired by an idea from Andy Teucher, became a discussion, an opportunity to connect, and eventually an invitation to speakers and the community to participate in a conversation. The passive “<em>became</em>” in the previous sentence hides the work of others—Julie Lowndes, Ronny Hernández Mora, Ileana Fenwick—who facilitated and “co-produced” this event. In a time when more and more of us work alone (Mark Padgham’s numbers on that to come), the call itself captured much of what the speakers identified as important: intentionality, using tools to facilitate connection, reaching out to one another for the things AI tools can’t provide.</p>
<p>The impetus for the discussion was not just a product of a few folks noticing and wanting to hear one another’s perspectives on AI and open-source communities. It’s definitionally a part of what Openscapes actually <em>is</em>. As Stefanie described in the opening:</p>
<blockquote>
<p>“Openscapes is an <strong>open-source approach and a movement</strong>. It’s a mechanism that helps research teams <strong>find each other</strong> and feel empowered with modern data-intensive science workflows.”</p>
</blockquote>
<p>Andy continued:</p>
<blockquote>
<p>“…open communities have a culture of shared and continued learning, and they prioritize diversity, equity, and belonging. They help us <strong>connect with each other on a human level around the things that we’re passionate about</strong>.”</p>
</blockquote>
<p>It’s because of communities like these that the organizers and panelists can see and feel an absence, a change—not something necessarily born of the use of AI-tools, but amplified and accelerated by them in a way that’s palpable. <em>But</em>, we convened neither to mourn, nor to wax nostalgic about days of yore that were imperfect, but to put to practice the kind of collaboration we’ve used to build and maintain software for years—this time, on open-source communities themselves.</p>
<p>Hadley, Mark, Yanina and I have different lived experiences. That’s <em>why</em> we came together. As Mark posited in <a href="https://mpadge.eu/blog/coding-alone.html" rel="nofollow" target="_blank">Coding Alone</a>: “Maybe software coded by increasingly isolated individuals will be just as good as previous software coded by larger communities building on one another’s ideas.”<sup id="fnref:2"><a href="https://ropensci.org/blog/2026/11/19/comm-call-openscapes/#fn:2" class="footnote-ref" role="doc-noteref" rel="nofollow" target="_blank">2</a></sup> The same cannot be said of communities, especially not ones built around a “knowledge commons.”<sup id="fnref:3"><a href="https://ropensci.org/blog/2026/11/19/comm-call-openscapes/#fn:3" class="footnote-ref" role="doc-noteref" rel="nofollow" target="_blank">3</a></sup> Communities sustain shared resources through self-organized collective action—co-production, <em>by definition</em>, cannot occur alone.<sup id="fnref:4"><a href="https://ropensci.org/blog/2026/11/19/comm-call-openscapes/#fn:4" class="footnote-ref" role="doc-noteref" rel="nofollow" target="_blank">4</a></sup></p>
<p>The <a href="https://openscapes.org/events/2026-10-01-community-call-open-communities-ai/" rel="nofollow" target="_blank">video and notes</a> are archived for you to peruse in full, but here I capture some themes and takeaways that stood out.</p>
<h2>
The four-way convergence
</h2><p>From our different vantage points, and in our own words, we converged around one idea: <em><strong>what used to be incidental now has to be deliberate</strong></em>**.** Some of the friction that’s been removed by using AI tools had side effects that we didn’t know we were counting on—much of it related to community. And so, now, the challenge becomes one of creating conditions for encounters that used to just happen as byproducts of need.</p>
<h3>
It was never just about need &#8211; Mara Averick
</h3><ul>
<li>My “tripped-into-open-source” story leaves out the people who <em>invited</em> me in. I don’t think I could do it today, because so much of what happened <em>around</em> me isn’t happening anymore.</li>
<li>Asking in public got you unstuck, but it also taught the answerer, revealed new experts, built a shared vocabulary, and made people visible.<sup id="fnref:5"><a href="https://ropensci.org/blog/2026/11/19/comm-call-openscapes/#fn:5" class="footnote-ref" role="doc-noteref" rel="nofollow" target="_blank">5</a></sup></li>
<li>Nobody took the side-effects of asking in public away on purpose—the learning done by a person one rung ahead, the visibility of the asker to other community members, the abstraction born of common vocabulary—they were bundled with the need to ask.</li>
<li>A default isn’t a fate. <strong>Invitation used to be a byproduct of asking for help; now it has to be built.</strong></li>
</ul>
<h3>
The long view &#8211; Hadley Wickham
</h3><ul>
<li>Over his ~20 years in the R community, Hadley has moved with it from the r-help mailing list to Stack Overflow, <code>#rstats</code> Twitter and Bluesky. Each new place was a chance to ask what we value and carry that forward.</li>
<li>Some of what’s worth carrying was incidental. Places like Twitter (used to) let people bring their whole selves, so you’d meet someone over R (or crochet) and discover everything else interesting about them.</li>
<li>Losing a place you love is scary, but it’s also a chance to ask “what can we do better this round?”</li>
<li><a href="https://tidyverse.org/tags/tidyverse-dev-day/" rel="nofollow" target="_blank">Tidyverse developer days</a> for the contributor community make the incidental deliberate. AI use is welcome, but <strong>fixing issues has never been the point. “We’re doing this because we want to build that community.”</strong></li>
</ul>
<h3>
Now with numbers &#8211; Mark Padgham
</h3><p>Mark Padgham came bearing data, paired with deep philosophical consideration. His piece, <a href="https://mpadge.eu/blog/purposeful-joy.html" rel="nofollow" target="_blank">Purposeful Joy</a>, which aims to “to help computer programs replace the purposeful labour of a generation of uniquely idiosyncratic human beings”<sup id="fnref:6"><a href="https://ropensci.org/blog/2026/11/19/comm-call-openscapes/#fn:6" class="footnote-ref" role="doc-noteref" rel="nofollow" target="_blank">6</a></sup> helped shape this call. And many of the findings from his presentation are captured beautifully in prose in <a href="https://mpadge.eu/blog/coding-alone.html" rel="nofollow" target="_blank">Coding Alone</a>.</p>
<ul>
<li>Working alone was on the rise before AI tools entered the picture. Across npm, PyPI, CRAN, JOSS and rOpenSci, the share of repositories effectively maintained by one person has gone from 27% in January 2021 to 44% in October 2026.<sup id="fnref:7"><a href="https://ropensci.org/blog/2026/11/19/comm-call-openscapes/#fn:7" class="footnote-ref" role="doc-noteref" rel="nofollow" target="_blank">7</a></sup> AI tools have sped that up; they didn’t start it.</li>
<li>This isn’t inevitable. AI tools “reflect conscious design decisions on the part of humans”, which means they can be designed differently.</li>
<li><a href="https://github.com/mpadge/askfirst" rel="nofollow" target="_blank"><code>askfirst</code></a><sup id="fnref:8"><a href="https://ropensci.org/blog/2026/11/19/comm-call-openscapes/#fn:8" class="footnote-ref" role="doc-noteref" rel="nofollow" target="_blank">8</a></sup> is one example. When your coding agent hits something a package can’t do, instead of quietly building its own workaround, <code>askfirst</code> prompts the agent to connect you to the packages’ authors. In Mark’s words, it’s <strong>“nothing but an invitation.”</strong></li>
</ul>
<h3>
What communities give that AI cannot &#8211; Yanina Bellini Saibene
</h3><p>Yani told three stories, each an offering with a lesson for community managers and one for community members. They’re well worth watching in full.</p>
<ul>
<li>The value of communities is moving “from information to judgment and trust”—knowing who is there, and trusting them enough to build something together.</li>
<li>Asking for help used to be an incidental on-ramp to such communities, but it’s weakening. So <strong>we need to build on-ramps that <em>don’t</em> depend on someone being stuck.</strong></li>
<li>Rethink how we welcome people. Every interaction you have with a colleague is a chance to be open. Part of the welcome is saying “You CAN”.</li>
<li>“AI gives you answers. Communities give you people. AI answers can be wrong. Connecting with people never is.”</li>
</ul>
<h2>
Closer
</h2><p>The discussion that followed is well worth watching, and I encourage you to do so. There is, however, one quotation from Yanina that captured the essence of the call so beautifully that I simply must include it here:</p>
<blockquote>
<p>“<em><strong>The community is not only a place to get unstuck, it is a place that will help you grow.</strong></em> Beyond the immediate tasks that you need to do. So, it is the contact network. So, why are we all here, all the speakers today? Because we have our contact network in some places, <em><strong>we know each other, and we know our work, and we trust each other</strong></em>**.** So, you will not get that from the model, how you co-create something with someone. You are not going to get that with the model.” — Yanina Bellini Saibene</p>
</blockquote>
<figure class="center"><img src="https://i2.wp.com/ropensci.org/blog/2026/11/19/comm-call-openscapes/communities-give-you-people.png?w=60%25&#038;ssl=1"
alt="black text on two lines says, AI gives you answers. Communities give you people. AI answers can be wrong. Connecting with people never is."  data-recalc-dims="1"><figcaption>
<p>A quote from Yanina Bellini Saibene.</p>
</figcaption>
</figure>
<h2>
Resources
</h2><ul>
<li><a href="https://youtu.be/tc3oj8UEAPQ" rel="nofollow" target="_blank"><em>Recording</em></a></li>
<li><a href="https://docs.google.com/document/d/16xDtQnUcZl70_0NhiV5L7OQ5om3dpyXMz6mNiBp-5W4/" rel="nofollow" target="_blank"><em>Notes doc</em></a></li>
<li><em>Speakers</em>
<ul>
<li><a href="https://www.linkedin.com/in/maraaverick/" rel="nofollow" target="_blank"><em>Mara Averick</em></a><em>, Senior Developer Advocate at <a href="https://quansight.com/" rel="nofollow" target="_blank">Quansight</a> and Contributor-Experience Lead for <a href="https://stdlib.io/" rel="nofollow" target="_blank">stdlib</a> (<a href="https://blog.stdlib.io/tag/developer-relations/" rel="nofollow" target="_blank">blog</a>) (<a href="https://docs.google.com/presentation/d/1Dl5YJy6ROykFbLRm38Wu6IKi9Q3M9--6ZTMUZ7Z0ciU/edit?slide=id.p1#slide=id.p1" rel="nofollow" target="_blank">slides</a>)</em></li>
<li><a href="https://hadley.nz/" rel="nofollow" target="_blank"><em>Hadley Wickham</em></a><em>, Chief Scientist at <a href="https://posit.co/" rel="nofollow" target="_blank">Posit</a> (<a href="https://drive.google.com/file/d/1Jj8LEeB7RLncDs-nqn54tPEJY2dKNESM/view?usp=drive_link" rel="nofollow" target="_blank">slides</a>)</em></li>
<li><a href="https://mpadge.eu/blog/" rel="nofollow" target="_blank"><em>Mark Padgham</em></a><em>, former Software Review Lead at <a href="https://ropensci.org/" rel="nofollow" target="_blank">rOpenSci</a> (<a href="https://mpadge.github.io/presentations/2026/openscapes/" rel="nofollow" target="_blank">slides</a>)</em></li>
<li><a href="https://yabellini.netlify.app/" rel="nofollow" target="_blank"><em>Yanina Bellini Saibene</em></a><em>, Community Manager at <a href="https://ropensci.org/" rel="nofollow" target="_blank">rOpenSci</a>, <a href="https://www.sovereign.tech/programs/fellowship" rel="nofollow" target="_blank">Sovereign Tech Fellow 2026</a>. Member of <a href="https://rladies.org/" rel="nofollow" target="_blank">RLadies+</a> and <a href="https://carpentries.org/" rel="nofollow" target="_blank">The Carpentries</a> Board of Directors (<a href="https://yabellini.github.io/OpenScapes/" rel="nofollow" target="_blank">slides</a>)</em></li>
</ul>
</li>
</ul>
<div class="footnotes" role="doc-endnotes">
<hr>
<ol>
<li id="fn:1">
<p>Openscapes. 2026. “Community Call: Open Communities in the Age of AI.” October 1. <a href="https://www.openscapes.org/events/2026-10-01-community-call-open-communities-ai/" rel="nofollow" target="_blank">https://www.openscapes.org/events/2026-10-01-community-call-open-communities-ai/</a>. <a href="https://ropensci.org/blog/2026/11/19/comm-call-openscapes/#fnref:1" class="footnote-backref" role="doc-backlink" rel="nofollow" target="_blank"><img src="https://s.w.org/images/core/emoji/13.0.0/72x72/21a9.png" alt="↩" class="wp-smiley" style="height: 1em; max-height: 1em;" />︎</a></p>
</li>
<li id="fn:2">
<p>Padgham, Mark. 2026. “Coding Alone.” mpadge, October 12. <a href="https://mpadge.eu/blog/coding-alone.html" rel="nofollow" target="_blank">https://mpadge.eu/blog/coding-alone.html</a>. <a href="https://ropensci.org/blog/2026/11/19/comm-call-openscapes/#fnref:2" class="footnote-backref" role="doc-backlink" rel="nofollow" target="_blank"><img src="https://s.w.org/images/core/emoji/13.0.0/72x72/21a9.png" alt="↩" class="wp-smiley" style="height: 1em; max-height: 1em;" />︎</a></p>
</li>
<li id="fn:3">
<p>Hess, Charlotte, and Elinor Ostrom, eds. 2007. Understanding Knowledge as a Commons: From Theory to Practice. MIT Press. <a href="https://ropensci.org/blog/2026/11/19/comm-call-openscapes/#fnref:3" class="footnote-backref" role="doc-backlink" rel="nofollow" target="_blank"><img src="https://s.w.org/images/core/emoji/13.0.0/72x72/21a9.png" alt="↩" class="wp-smiley" style="height: 1em; max-height: 1em;" />︎</a></p>
</li>
<li id="fn:4">
<p>Ostrom, Elinor. 1990. Governing the Commons: The Evolution of Institutions for Collective Action. Cambridge University Press. <a href="https://ropensci.org/blog/2026/11/19/comm-call-openscapes/#fnref:4" class="footnote-backref" role="doc-backlink" rel="nofollow" target="_blank"><img src="https://s.w.org/images/core/emoji/13.0.0/72x72/21a9.png" alt="↩" class="wp-smiley" style="height: 1em; max-height: 1em;" />︎</a></p>
</li>
<li id="fn:5">
<p>Averick, Mara. 2026. “What We’re No Longer Seeing: AI and the Invisible Newcomer in Open Source.” Numerical Bits, June 7. <a href="https://blog.stdlib.io/ai-and-the-invisible-newcomer-in-open-source/" rel="nofollow" target="_blank">https://blog.stdlib.io/ai-and-the-invisible-newcomer-in-open-source/</a> <a href="https://ropensci.org/blog/2026/11/19/comm-call-openscapes/#fnref:5" class="footnote-backref" role="doc-backlink" rel="nofollow" target="_blank"><img src="https://s.w.org/images/core/emoji/13.0.0/72x72/21a9.png" alt="↩" class="wp-smiley" style="height: 1em; max-height: 1em;" />︎</a></p>
</li>
<li id="fn:6">
<p>Padgham, Mark. 2026. “Purposeful Joy.” mpadge, June 26. <a href="https://mpadge.eu/blog/purposeful-joy.html" rel="nofollow" target="_blank">https://mpadge.eu/blog/purposeful-joy.html</a>. <a href="https://ropensci.org/blog/2026/11/19/comm-call-openscapes/#fnref:6" class="footnote-backref" role="doc-backlink" rel="nofollow" target="_blank"><img src="https://s.w.org/images/core/emoji/13.0.0/72x72/21a9.png" alt="↩" class="wp-smiley" style="height: 1em; max-height: 1em;" />︎</a></p>
</li>
<li id="fn:7">
<p>Padgham, Mark. 2026. “Coding Alone.” mpadge, October 12. <a href="https://mpadge.eu/blog/coding-alone.html" rel="nofollow" target="_blank">https://mpadge.eu/blog/coding-alone.html</a>. <a href="https://ropensci.org/blog/2026/11/19/comm-call-openscapes/#fnref:7" class="footnote-backref" role="doc-backlink" rel="nofollow" target="_blank"><img src="https://s.w.org/images/core/emoji/13.0.0/72x72/21a9.png" alt="↩" class="wp-smiley" style="height: 1em; max-height: 1em;" />︎</a></p>
</li>
<li id="fn:8">
<p>Padgham, Mark. 2026. askfirst: Connect AI with Your Coding Communities. <a href="https://github.com/mpadge/askfirst" rel="nofollow" target="_blank">https://github.com/mpadge/askfirst</a>. <a href="https://ropensci.org/blog/2026/11/19/comm-call-openscapes/#fnref:8" class="footnote-backref" role="doc-backlink" rel="nofollow" target="_blank"><img src="https://s.w.org/images/core/emoji/13.0.0/72x72/21a9.png" alt="↩" class="wp-smiley" style="height: 1em; max-height: 1em;" />︎</a></p>
</li>
</ol>
</div>
<div style="border: 1px solid; background: none repeat scroll 0 0 #EDEDED; margin: 1px; font-size: 13px;">
<div style="text-align: center;">To <strong>leave a comment</strong> for the author, please follow the link and comment on their blog: <strong><a href="https://ropensci.org/blog/2026/11/19/comm-call-openscapes/"> rOpenSci - open tools for open science</a></strong>.</div>
<hr />
<a href="https://www.r-bloggers.com/" rel="nofollow">R-bloggers.com</a> offers <strong><a href="https://feedburner.google.com/fb/a/mailverify?uri=RBloggers" rel="nofollow">daily e-mail updates</a></strong> about <a title="The R Project for Statistical Computing" href="https://www.r-project.org/" rel="nofollow">R</a> news and tutorials about <a title="R tutorials" href="https://www.r-bloggers.com/how-to-learn-r-2/" rel="nofollow">learning R</a> and many other topics. <a title="Data science jobs" href="https://www.r-users.com/" rel="nofollow">Click here if you're looking to post or find an R/data-science job</a>.

<hr>Want to share your content on R-bloggers?<a href="https://www.r-bloggers.com/add-your-blog/" rel="nofollow"> click here</a> if you have a blog, or <a href="http://r-posts.com/" rel="nofollow"> here</a> if you don't.
</div><strong>Continue reading</strong>: <a href="https://www.r-bloggers.com/2026/11/making-the-incidental-an-invitation-in-building-community/">Making the incidental an invitation in building community</a>]]></content:encoded>
					
		
		<enclosure url="" length="0" type="" />

		<post-id xmlns="com-wordpress:feed-additions:1">405072</post-id>	</item>
	</channel>
</rss>
