<?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>Fri, 27 Nov 2026 00:00:00 +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>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>“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>
		<item>
		<title>From Brisbane to the rOpenSci Community: Ten Years of Open Research Software</title>
		<link>https://www.r-bloggers.com/2026/11/from-brisbane-to-the-ropensci-community-ten-years-of-open-research-software/</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/brisbane-to-community/</guid>

					<description><![CDATA[<p>With rOpenSci turning 15 this year, it’s hard to believe that I’ve been part of it for 10 of those years.<br />
My involvement started in Brisbane in 2016, at the first Australian rOpenSci Unconference.<br />
I’d known about rOpenSci and its wor...</p>
<strong>Continue reading</strong>: <a href="https://www.r-bloggers.com/2026/11/from-brisbane-to-the-ropensci-community-ten-years-of-open-research-software/">From Brisbane to the rOpenSci Community: Ten Years of Open Research Software</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/brisbane-to-community/"> 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>With rOpenSci turning 15 this year, it’s hard to believe that I’ve been part of it for 10 of those years.</p>
<p>My involvement started in Brisbane in 2016, at the first <a href="https://ropensci.org/blog/2016/06/16/au-unconf/" rel="nofollow" target="_blank">Australian rOpenSci Unconference</a>.
I’d known about rOpenSci and its work for some time before then.
When rOpenSci was founded in 2011, I’d just moved from the US to the Philippines for work.
During the five years I lived and worked there, I became familiar with its packages and the people behind them.
I was interested in what rOpenSci was doing, but wasn’t sure how I might get involved.
I did recognise the value of being part of the R community, though, and joined the Manila R User Group.</p>
<h2>
Brisbane 2016: just the beginning
</h2><p>I moved to Australia for work in January 2016 and, as luck would have it, was living close enough to Brisbane to attend the rOpenSci Unconf in April.
The event was organised by a group of researchers at <a href="https://www.qut.edu.au/" rel="nofollow" target="_blank">QUT</a>, including <a href="https://www.njtierney.com/bio.html" rel="nofollow" target="_blank">Nick Tierney</a>, <a href="https://www.milesmcbain.com/" rel="nofollow" target="_blank">Miles McBain</a> and <a href="https://bragqut.wordpress.com/members/jessie-roberts/" rel="nofollow" target="_blank">Jessie Roberts</a>.</p>
<p>As it happened, my first R package, {<a href="https://docs.ropensci.org/GSODR/" rel="nofollow" target="_blank">GSODR</a>}, had just been accepted onto <a href="https://cran.r-project.org/package=GSODR" rel="nofollow" target="_blank">CRAN</a>.
That was the fact I shared when introducing myself to the other attendees.
I was an experienced researcher and R user, but still very much a newcomer to developing and publishing R packages.</p>
<p>I was nervous about attending.
I was new to Australia and had never been to an event quite like it.
But the chance to bring Australian R users together to work on practical research problems was exciting, and I soon settled in.</p>
<p>The format was very hands-on.
We shared unfinished ideas, learned from one another and built things together.
I found this a great way to learn, and it helped me gain confidence.
I was one of the few attendees with experience working with geospatial data and a particular interest in weather data, which led me to connect with <a href="https://ivanhanigan.github.io/about/" rel="nofollow" target="_blank">A/Prof Ivan Hanigan</a>.</p>
<p>Ivan had some R code for downloading AWAP grids, <a href="https://github.com/swish-climate-impact-assessment/AWAP_GRIDS" rel="nofollow" target="_blank">AWAP_GRIDS</a>, and I was able to help improve it.
I also contributed <a href="https://github.com/ivanhanigan/auunconf16" rel="nofollow" target="_blank">a vignette describing how to work with Australian weather data</a>, which went on to influence several packages that followed.</p>
<p>It was the first time I felt I had something useful to contribute to a wider group of R users, including people I’d never met before.
I came away from Brisbane with a much better sense of what I could do and who I could do it with.</p>
<h2>
From an idea to a package: learning to develop openly
</h2><p>After the Unconf, I returned home and soon submitted GSODR to rOpenSci for <a href="https://github.com/ropensci/software-review/issues/79" rel="nofollow" target="_blank">software peer review</a>.</p>
<p>I’d already seen how welcoming the people involved were, and I understood the value of peer review from my day job.
Now I had the chance to go through that process with code.
I’d written a few R packages for internal use, but nothing intended for a wider audience.</p>
<p>The feedback from the editors and reviewers helped sharpen the package’s focus and improve its reproducibility and robustness.
I also began to understand that making a package available to other people involved rather more than getting data from an API (or, in those days, FTP) and wrangling it into a usable format.
Good documentation, testing and a willingness to keep maintaining the package as data sources and the R ecosystem changed were just as important.</p>
<p>I went on to develop several other weather and climate-related packages, providing access to a range of data sources.
{<a href="https://docs.ropensci.org/getCRUCLdata/" rel="nofollow" target="_blank">getCRUCLdata</a>} grew out of scripts I’d written for my PhD research, while {<a href="https://github.com/ropensci-archive/bomrang" rel="nofollow" target="_blank">bomrang</a>} (now superseded by {<a href="https://docs.ropensci.org/weatherOz/" rel="nofollow" target="_blank">weatherOz</a>}) grew out of ideas from the Brisbane Unconf and the 2016 GovHack Hackathon.
My team went on to <a href="https://toowoombatrio.github.io/John_Conner/" rel="nofollow" target="_blank">win the national Paddock to Plate Award</a>.</p>
<p>Perhaps the best known of my rOpenSci packages, {<a href="https://docs.ropensci.org/nasapower/" rel="nofollow" target="_blank">nasapower</a>}, had a longer history.
I’d started working on it around 2011, but it really took shape during the peer-review process, when the <a href="https://power.larc.nasa.gov/" rel="nofollow" target="_blank">NASA-POWER</a> team released a dedicated API.
I ended up rewriting the package from the ground up during the review.
That taught me a great deal about working with REST APIs and testing code that depends on remote services.
In particular, I learned to use {<a href="https://docs.ropensci.org/vcr/" rel="nofollow" target="_blank">vcr</a>} to record and replay HTTP interactions, so tests could run without an internet connection.</p>
<p>Since then, much of my package development has been about making data easier for other researchers to access.
One of the best parts of that work is hearing from a student who has finally been able to get the data they need after struggling to find it or work out how to access it.
It’s a good reminder of why I started doing this in the first place.</p>
<h2>
From contributor to reviewer: giving back
</h2><p>In 2019, I was invited to review packages for rOpenSci.
I was delighted to have the chance to give something back to a group that had helped me so much.
I reviewed {<a href="https://docs.ropensci.org/stats19/" rel="nofollow" target="_blank">stats19</a>} and {<a href="https://docs.ropensci.org/bib2df/" rel="nofollow" target="_blank">bib2df</a>}.</p>
<p>A few years later, I had a nice reminder of how these connections can come full circle.
I reviewed {<a href="https://docs.ropensci.org/rnassqs/" rel="nofollow" target="_blank">rnassqs</a>} for <a href="https://econpotter.com/" rel="nofollow" target="_blank">Nicholas Potter</a>, who went on to review my package {<a href="https://docs.ropensci.org/read.abares/" rel="nofollow" target="_blank">read.abares</a>}.</p>
<p>Reviewing other people’s packages also made me a better package developer.
Seeing how other authors approached problems, and thinking carefully about their code and documentation, gave me a different perspective on my own work.</p>
<p>In 2021, Noam Ross invited me to serve as a guest editor for {<a href="https://github.com/ropensci/software-review/issues/4360" rel="nofollow" target="_blank">allodb</a>}.
I was surprised, but grateful, and accepted.
I stumbled a little while learning to use the rOpenSci bot and manage the submission, but it was a valuable experience.
The authors learned, I learned, and the package came out of the process in better shape.</p>
<p>That experience led to another invitation from Noam: joining the rOpenSci editorial board.
I gladly accepted.
Since then, I’ve been able to contribute beyond my own packages, supporting authors and reviewers and helping keep the software peer-review process running.</p>
<p>I particularly value rOpenSci’s approach to working together and its <a href="https://ropensci.org/code-of-conduct/" rel="nofollow" target="_blank">Code of Conduct</a>, which sets clear expectations for everyone involved.
Being on the editorial board has also helped me keep up with changing standards in research software, while giving me the chance to help make the process welcoming rather than intimidating for new contributors.</p>
<h2>
Beyond packages: building a wider open science community
</h2><p>rOpenSci’s influence on my work hasn’t stopped at package development or editorial duties.</p>
<p>In 2018, <a href="https://emersondelponte.com/" rel="nofollow" target="_blank">Dr Emerson Del Ponte</a> and I founded the <a href="https://openplantpathology.netlify.app/" rel="nofollow" target="_blank">Open Plant Pathology community</a>.
We saw a need in the global plant pathology community much like the one rOpenSci had addressed for R users: a place where people could share ideas, data and code, and help one another, wherever they happened to be in the world.</p>
<p>A lot of what I’d learned from rOpenSci shaped how we approached Open Plant Pathology.
For several years, we published blog posts with ideas, examples and code that others in plant pathology could use.
We also developed an R package, {<a href="https://cran.r-project.org/package=hagis" rel="nofollow" target="_blank">hagis</a>}, based on work that <a href="https://www.canr.msu.edu/people/austin_1" rel="nofollow" target="_blank">Dr Austin McCoy</a> and <a href="https://agriculture.auburn.edu/directory/profile.php?id=zan0002" rel="nofollow" target="_blank">Dr Zachary Noel</a> wanted to share with the wider community.</p>
<p>In 2025, with changes in our jobs and difficulties engaging with the community, we decided to wind down Open Plant Pathology and focus our efforts elsewhere.
For me, that included taking on a statistics editor role at rOpenSci, alongside my existing editorial responsibilities.</p>
<p>Looking back, I think Open Plant Pathology worked in part because we had a good example to follow.
rOpenSci had shown us that the value of a community isn’t just in the software or other technical contributions people make.
It’s also in the relationships people build, and in having a place where they can share their work and help one another improve it.</p>
<h2>
Ten years on: what rOpenSci has meant
</h2><p>A lot has changed over the past ten years.
I’ve had three jobs and lived in two Australian states.
I’ve gone from being a newcomer whose first R package had just been accepted onto CRAN to having several packages reviewed, reviewing other people’s work, joining the editorial board and becoming part of the rotating editor-in-chief team.</p>
<p>I never had any formal training in software development.
My only real introduction before working with R was a single undergraduate semester writing macros for spreadsheets.
Most of what I’ve learned has come from the people around me, starting with my PhD research and continuing through groups like rOpenSci.</p>
<p>I think that’s worth saying because you don’t need to be an expert software developer to contribute to open-source or open research software.
You need to be curious, willing to learn and able to find people who will help you along the way.
rOpenSci has been an important part of that for me, and has helped make research software development feel like a recognised and valued part of doing science.</p>
<h2>
It’s more than just software
</h2><p>But when I think about what has kept me involved for ten years, it’s not just what I’ve learned or the software I’ve helped develop.
It’s also the people I’ve met along the way.
Attending the Unconf in 2016 was also the start of friendships and working relationships that have lasted ever since.</p>
<p>Ivan Hanigan and I are now both on staff at Curtin University, where we continue to collaborate and find reasons to work together.
Nick Tierney and I became friends, and when he moved to Perth, we spent plenty of time together taking photographs.
<a href="https://www.noamross.net/" rel="nofollow" target="_blank">Noam Ross</a> and I have met several times to discuss disease-modelling ideas across plant, animal and human health.
I wish we had more opportunities for those conversations.
<a href="https://masalmon.eu/" rel="nofollow" target="_blank">Maëlle Salmon</a> has also been a great help in sorting out some particularly finicky time-zone issues in {weatherOz}.
We spent a fair amount of time on a video call getting them sorted.
<a href="https://samrogers.website/" rel="nofollow" target="_blank">Sam Rogers</a> reviewed {weatherOz} for rOpenSci.
We now work together on a large national project, have both contributed to the rOpenSci package {<a href="https://docs.ropensci.org/nert" rel="nofollow" target="_blank">nert</a>}, and collaborate on other projects outside the R community.
I’d also be remiss not to mention the people who helped build {bomrang} and later {weatherOz}.
Several were also part of the rOpenSci community.
They generously gave their time and expertise to these packages, often without me having to ask.
Together, {bomrang} and {weatherOz} became some of the largest collaborative open-source projects I’ve worked on, and I’m indebted to everyone who contributed.
Among those who contributed were <a href="https://mpadge.eu/" rel="nofollow" target="_blank">Mark Padgham</a>, <a href="https://github.com/HughParsonage" rel="nofollow" target="_blank">Hugh Parsonage</a>, <a href="https://jamesgoldie.dev/" rel="nofollow" target="_blank">James Goldie</a>, <a href="https://jcarroll.com.au/" rel="nofollow" target="_blank">Jono Carroll</a> (who I first met in 2016 at the Unconf), <a href="https://www.deanmarchiori.com/" rel="nofollow" target="_blank">Dean Marchiori</a>, <a href="https://staffprofile.unisq.edu.au/Profile/Keith-Pembleton" rel="nofollow" target="_blank">Keith Pembleton</a>, <a href="https://paulmelloy.com.au/" rel="nofollow" target="_blank">Paul Melloy</a>, and of course, <a href="https://github.com/bozaah" rel="nofollow" target="_blank">Rodrigo Pires</a> who maintains {weatherOz}.</p>
<p>These relationships are a big part of why I’ve stayed involved.
Wherever I find myself, there’s a good chance there’s someone from rOpenSci I can get in touch with for a coffee and a chat.</p>
<h2>
Looking forward: an invitation to get involved
</h2><p>If there’s one thing I’d say after ten years, it’s don’t be afraid to get involved.</p>
<p>I’ve been using R since the early 2000s and have watched a fantastic community grow around it.
I’ve also seen what a difference it makes when people make an effort to be kind, supportive and welcoming.
rOpenSci is a good example of that.</p>
<p><a href="https://ropensci.org/help-wanted/" rel="nofollow" target="_blank">Getting involved doesn’t have to mean writing an R package</a>.
You could open an issue to report a bug, help improve some documentation or write an example vignette showing others how to use a package.
If you’ve found a useful way to do something with a package, someone else might benefit from seeing it too (just check with the package author first!).</p>
<p>Reviewing is another good way to contribute.
You’ll learn a lot about your own coding by looking at someone else’s work and thinking about how it could be improved.
rOpenSci’s review process is intended to be supportive, friendly and constructive, and that makes it worthwhile for authors and reviewers alike.
If you are interested in reviewing, <a href="https://airtable.com/app8dssb6a7PG6Vwj/shrnfDI2S9uuyxtDw" rel="nofollow" target="_blank">rOpenSci maintains a database of potential reviewers that is open for you to volunteer</a>.</p>
<p>From my perspective as an editor, rOpenSci needs to keep adapting as the tools and practices of research software development change, as it has done throughout its history.
New technologies bring opportunities, but also questions about how to maintain quality, support contributors and keep peer review useful, particularly as the demands on editors and reviewers grow.</p>
<p>Whatever changes, I think the community will remain central to rOpenSci’s work.
If we keep that focus, we’ll continue to serve the needs of the R community.</p>
<p>I hope rOpenSci can make the most of what’s changing without losing the things that made me want to be involved in the first place: thoughtful reviews, useful feedback and people who are willing to help one another do better work.
After ten years, that’s what stands out to me.
The software matters, of course, but so do the people I’ve met, the things I’ve learned and the friendships that have come out of it.</p>
<p>And I’m very glad I made it to Brisbane in 2016.</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/19/brisbane-to-community/"> 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/from-brisbane-to-the-ropensci-community-ten-years-of-open-research-software/">From Brisbane to the rOpenSci Community: Ten Years of Open Research Software</a>]]></content:encoded>
					
		
		<enclosure url="" length="0" type="" />

		<post-id xmlns="com-wordpress:feed-additions:1">404981</post-id>	</item>
		<item>
		<title>Why the overall rate can flip: weighted means and Simpson&#8217;s paradox in R</title>
		<link>https://www.r-bloggers.com/2026/11/why-the-overall-rate-can-flip-weighted-means-and-simpsons-paradox-in-r/</link>
		
		<dc:creator><![CDATA[R on Stats and R]]></dc:creator>
		<pubDate>Thu, 19 Nov 2026 00:00:00 +0000</pubDate>
				<category><![CDATA[R bloggers]]></category>
		<guid isPermaLink="false">https://statsandr.com/blog/why-the-overall-rate-can-flip-weighted-means-and-simpson-s-paradox-in-r/</guid>

					<description><![CDATA[<div style = "width:60%; display: inline-block; float:left; ">
<p>Introduction<br />
The data<br />
An overall rate is a weighted mean<br />
The result depends on the reference mix<br />
When exactly does the comparison flip?<br />
Which rate should you report?<br />
References</p>
<p>Note: This post has been written in collaboration with the Easy Sta...</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/why-the-overall-rate-can-flip-weighted-means-and-simpsons-paradox-in-r/">Why the overall rate can flip: weighted means and Simpson’s paradox 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://statsandr.com/blog/why-the-overall-rate-can-flip-weighted-means-and-simpson-s-paradox-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/why-the-overall-rate-can-flip-weighted-means-and-simpson-s-paradox-in-r/#introduction" id="toc-introduction" rel="nofollow" target="_blank">Introduction</a></li>
<li><a href="https://statsandr.com/blog/why-the-overall-rate-can-flip-weighted-means-and-simpson-s-paradox-in-r/#the-data" id="toc-the-data" rel="nofollow" target="_blank">The data</a></li>
<li><a href="https://statsandr.com/blog/why-the-overall-rate-can-flip-weighted-means-and-simpson-s-paradox-in-r/#an-overall-rate-is-a-weighted-mean" id="toc-an-overall-rate-is-a-weighted-mean" rel="nofollow" target="_blank">An overall rate is a weighted mean</a></li>
<li><a href="https://statsandr.com/blog/why-the-overall-rate-can-flip-weighted-means-and-simpson-s-paradox-in-r/#the-result-depends-on-the-reference-mix" id="toc-the-result-depends-on-the-reference-mix" rel="nofollow" target="_blank">The result depends on the reference mix</a></li>
<li><a href="https://statsandr.com/blog/why-the-overall-rate-can-flip-weighted-means-and-simpson-s-paradox-in-r/#when-exactly-does-the-comparison-flip" id="toc-when-exactly-does-the-comparison-flip" rel="nofollow" target="_blank">When exactly does the comparison flip?</a></li>
<li><a href="https://statsandr.com/blog/why-the-overall-rate-can-flip-weighted-means-and-simpson-s-paradox-in-r/#which-rate-should-you-report" id="toc-which-rate-should-you-report" rel="nofollow" target="_blank">Which rate should you report?</a></li>
<li><a href="https://statsandr.com/blog/why-the-overall-rate-can-flip-weighted-means-and-simpson-s-paradox-in-r/#references" id="toc-references" rel="nofollow" target="_blank">References</a></li>
</ul>
</div>

<p><img src="https://i2.wp.com/statsandr.com/blog/why-the-overall-rate-can-flip-weighted-means-and-simpson-s-paradox-in-r/images/why-the-overall-rate-can-flip-weighted-means-and-simpson-s-paradox-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 the Easy Stat Calc Team.</em></p>
<div id="introduction" class="section level1">
<h1>Introduction</h1>
<p>Most readers learn that an overall average is “just the average”. The trouble starts when the data come in subgroups. An overall rate is not the plain average of the subgroup rates. It is a <strong>weighted mean</strong> of them, and the weights are the subgroup sizes. Change the weights and the answer changes, sometimes enough to reverse a comparison.</p>
<p>That reversal is known as Simpson’s paradox. The classic illustration is the 1973 graduate admissions data from the University of California, Berkeley <span class="citation">(<a href="https://statsandr.com/blog/why-the-overall-rate-can-flip-weighted-means-and-simpson-s-paradox-in-r/#ref-bickel1975sex" rel="nofollow" target="_blank">Bickel et al. 1975</a>)</span>, which ship with R as <code>UCBAdmissions</code>. This article does not stop at the familiar “women do better inside departments” table. It asks three questions the table leaves open:</p>
<ol style="list-style-type: decimal">
<li>How much does the re-weighted result depend on <strong>which applicant mix</strong> we pick as the reference?</li>
<li>At exactly what point does a small advantage inside every subgroup get cancelled out by differences in subgroup mix, and how often does a sample of a given size show the flip near that point?</li>
<li>When is the overall rate the right number, and when is the subgroup rate the right number?</li>
</ol>
<p>Everything below uses base R, except for the plot, which is made with the <a href="https://statsandr.com/blog/graphics-in-r-with-ggplot2/" rel="nofollow" target="_blank"><code>{ggplot2}</code> package</a>. A seed is set at the start of the simulation code to ensure reproducibility.</p>
</div>
<div id="the-data" class="section level1">
<h1>The data</h1>
<p><code>UCBAdmissions</code> is a 2 x 2 x 6 table: admission status, gender and department (the six largest departments, labelled A to F). We separate admitted counts from totals and compute department-level rates.</p>
<pre>adm &lt;- UCBAdmissions[&quot;Admitted&quot;, , ] # admitted, by gender x department
tot &lt;- apply(UCBAdmissions, c(2, 3), sum) # all applicants, by gender x department
rate &lt;- adm / tot # admission rate, by gender x department

overall &lt;- rowSums(adm) / rowSums(tot)
round(100 * overall, 1)
##   Male Female 
##   44.5   30.4</pre>
<p>Across these six departments, men were admitted at 44.5% and women at 30.4%. Now look inside each department.</p>
<pre>round(100 * rate, 1)
##         Dept
## Gender      A    B    C    D    E    F
##   Male   62.1 63.0 36.9 33.1 27.7  5.9
##   Female 82.4 68.0 34.1 34.9 23.9  7.0
tot
##         Dept
## Gender     A   B   C   D   E   F
##   Male   825 560 325 417 191 373
##   Female 108  25 593 375 393 341</pre>
<p>Women have the higher admission rate in four of the six departments (A, B, D and F). Men lead in C and E, by small margins. Yet the overall rate for women is 14 points lower. The explanation is in the applicant counts: 825 of the 933 applicants to department A were men, and department A admits many applicants, while most women applied to departments C to F, where admission is much harder.</p>
<pre>round(100 * prop.table(tot, 1)[, &quot;A&quot;], 1) # share of each gender&#39;s applicants who applied to A
##   Male Female 
##   30.7    5.9</pre>
<p>About 31% of the men applied to department A, against 6% of the women.</p>
</div>
<div id="an-overall-rate-is-a-weighted-mean" class="section level1">
<h1>An overall rate is a weighted mean</h1>
<p>If department <em>i</em> has admission rate <span class="math inline">\(r_i\)</span> and a share <span class="math inline">\(w_i\)</span> of the applicants, the overall rate is</p>
<p><span class="math display">\[\text{overall} = \sum_i w_i \, r_i .\]</span></p>
<p>In R this is <code>weighted.mean(rate, weights)</code>. With each gender’s <em>own</em> applicant counts as weights it reproduces the overall rates exactly (for a quick check outside R, readers can also use a <a href="https://easystatcalc.com/weighted-average-calculator/" rel="nofollow" target="_blank">weighted average calculator</a>).</p>
<pre>round(100 * c(
  Men = weighted.mean(rate[&quot;Male&quot;, ], tot[&quot;Male&quot;, ]),
  Women = weighted.mean(rate[&quot;Female&quot;, ], tot[&quot;Female&quot;, ])
), 1)
##   Men Women 
##  44.5  30.4</pre>
<p>The question is what happens when both genders are weighted by the <em>same</em> mix, so that we compare like with like.</p>
</div>
<div id="the-result-depends-on-the-reference-mix" class="section level1">
<h1>The result depends on the reference mix</h1>
<p>There is no single correct “same mix”. We can use the men’s applicant mix, the women’s mix, the combined mix, or equal weights. Each gives a different answer, so it is worth showing all of them rather than one re-weighted figure.</p>
<pre>wm &lt;- function(w) {
  c(
    Men = weighted.mean(rate[&quot;Male&quot;, ], w),
    Women = weighted.mean(rate[&quot;Female&quot;, ], w)
  )
}

mixes &lt;- rbind(
  &quot;Own mix (observed)&quot; = c(
    weighted.mean(rate[&quot;Male&quot;, ], tot[&quot;Male&quot;, ]),
    weighted.mean(rate[&quot;Female&quot;, ], tot[&quot;Female&quot;, ])
  ),
  &quot;Men&#39;s mix&quot; = wm(tot[&quot;Male&quot;, ]),
  &quot;Women&#39;s mix&quot; = wm(tot[&quot;Female&quot;, ]),
  &quot;Combined mix&quot; = wm(colSums(tot)),
  &quot;Equal weights&quot; = wm(rep(1, 6))
)
colnames(mixes) &lt;- c(&quot;Men&quot;, &quot;Women&quot;)

data.frame(round(100 * mixes, 1),
  Gap = round(100 * (mixes[, &quot;Women&quot;] - mixes[, &quot;Men&quot;]), 1)
)
##                     Men Women   Gap
## Own mix (observed) 44.5  30.4 -14.2
## Men&#39;s mix          44.5  51.6   7.1
## Women&#39;s mix        30.2  30.4   0.1
## Combined mix       38.7  43.0   4.3
## Equal weights      38.1  41.7   3.6</pre>
<p>The gap (women minus men, in percentage points) moves from -14.2 with the observed mixes to +4.3 with the combined mix, +3.6 with equal weights, +7.1 with the men’s mix, and almost nothing (+0.1) with the women’s mix. Only the weights changed, never the department rates.</p>
<p>Most of this comes from one department. Department A has by far the largest gap in favour of women (82.4% vs 62.1%, about 20 points, against 5 points or less elsewhere) and holds 21% of all applicants. Under the combined mix it contributes 4.2 of the 4.3 points. Its weight also explains the spread between mixes: 31% of the men’s applicants went to department A, but only 6% of the women’s. Leave it out and re-weight the other five departments by their combined mix:</p>
<pre>w5 &lt;- colSums(tot)[2:6]
round(100 * c(
  Men = weighted.mean(rate[&quot;Male&quot;, 2:6], w5),
  Women = weighted.mean(rate[&quot;Female&quot;, 2:6], w5)
), 1)
##   Men Women 
##  32.7  32.8</pre>
<p>Without department A both rates are about 33% (32.7% and 32.8%). So the headline “women lead” under the combined and men’s mixes is largely a department A result, and a reader who sees a single re-weighted figure would not know that.</p>
</div>
<div id="when-exactly-does-the-comparison-flip" class="section level1">
<h1>When exactly does the comparison flip?</h1>
<p>The Berkeley data are one table. To study the mechanism we build a small model with two groups of applicants, A and B (like the two genders above), and two departments, an easy one and a hard one:</p>
<table>
<thead>
<tr class="header">
<th></th>
<th>Easy department</th>
<th>Hard department</th>
</tr>
</thead>
<tbody>
<tr class="odd">
<td>Group A admission rate</td>
<td>72%</td>
<td>22%</td>
</tr>
<tr class="even">
<td>Group B admission rate</td>
<td>70%</td>
<td>20%</td>
</tr>
</tbody>
</table>
<p>Group A beats group B by 2 points in both departments. The overall rate of a group is</p>
<p><span class="math display">\[\begin{gathered}
\text{overall} = \text{easy rate} - g \times {} \\
(\text{share applying to the hard department}),
\end{gathered}\]</span></p>
<p>where <span class="math inline">\(g\)</span> is the gap between the easy and the hard department rates (here 0.50 for both groups). Writing <span class="math inline">\(p_A\)</span> and <span class="math inline">\(p_B\)</span> for the shares of group A’s and group B’s applicants who apply to the hard department, group A is behind overall exactly when</p>
<p><span class="math display">\[0.02 < g \times (p_A - p_B) \quad\Longleftrightarrow\quad p_A - p_B > \frac{0.02}{g}.\]</span></p>
<p>So the flip point depends on two things only: the size of the advantage inside the departments (0.02) and the gap between the departments’ admission rates (<span class="math inline">\(g\)</span>). Here it is 0.02 / 0.50 = 0.04. If group B sends 10% of its applicants to the hard department, group A is behind overall once more than 14% of A’s applicants go there.</p>
<pre>easy &lt;- c(A = 0.72, B = 0.70)
hard &lt;- c(A = 0.22, B = 0.20)
pB &lt;- 0.10 # share of group B applying to the hard department
gap &lt;- unname(easy[&quot;A&quot;] - hard[&quot;A&quot;]) # 0.50 (same for both groups)
threshold &lt;- 0.02 / gap
c(threshold = threshold, flip_when_pA_above = pB + threshold)
##          threshold flip_when_pA_above 
##               0.04               0.14</pre>
<p>The formula gives the flip point for the <em>true</em> rates. It does not tell us how often a <strong>sample</strong> of a given size shows the flip near that point. This probability can be computed exactly from binomial distributions, but a simulation shows it more simply: draw how many applicants of each group choose the hard department, then draw the admissions, and record how often the observed overall rate of A is below that of B.</p>
<pre>set.seed(2026) # for reproducible results

sim_flip &lt;- function(n, delta, reps = 10000) {
  pA &lt;- pB + delta
  hA &lt;- rbinom(reps, n, pA) # group A applicants to the hard department
  hB &lt;- rbinom(reps, n, pB)
  aA &lt;- rbinom(reps, hA, hard[&quot;A&quot;]) + rbinom(reps, n - hA, easy[&quot;A&quot;]) # admitted from A
  aB &lt;- rbinom(reps, hB, hard[&quot;B&quot;]) + rbinom(reps, n - hB, easy[&quot;B&quot;])
  mean(aA &lt; aB) # share of samples where A is below B
}

deltas &lt;- c(0, 0.02, 0.04, 0.06, 0.08, 0.12) # p_A - p_B
ns &lt;- c(100, 400, 1600) # applicants per group

res &lt;- sapply(ns, function(n) sapply(deltas, function(dl) sim_flip(n, dl)))
dimnames(res) &lt;- list(paste0(&quot;delta=&quot;, deltas), paste0(&quot;n=&quot;, ns))
round(res, 3)
##            n=100 n=400 n=1600
## delta=0    0.351 0.266  0.110
## delta=0.02 0.412 0.370  0.270
## delta=0.04 0.470 0.489  0.487
## delta=0.06 0.533 0.600  0.717
## delta=0.08 0.595 0.703  0.877
## delta=0.12 0.699 0.873  0.990
library(ggplot2)

res_long &lt;- data.frame(
  delta = rep(deltas, times = ncol(res)),
  n     = factor(rep(colnames(res), each = nrow(res)), levels = colnames(res)),
  share = as.vector(res)
)

ggplot(res_long, aes(x = delta, y = share, colour = n, shape = n)) +
  geom_vline(xintercept = threshold, linetype = &quot;dashed&quot;, colour = &quot;grey40&quot;) +
  annotate(&quot;text&quot;,
    x = threshold, y = 1, label = &quot;threshold&quot;,
    hjust = -0.1, colour = &quot;grey40&quot;
  ) +
  geom_line(linewidth = 0.8) +
  geom_point(size = 2.5) +
  geom_text(
    data = subset(res_long, delta == max(delta)), aes(label = n),
    hjust = -0.3, size = 3.5, colour = &quot;grey20&quot;, show.legend = FALSE
  ) +
  scale_colour_manual(values = c(&quot;#6da7ec&quot;, &quot;#2a78d6&quot;, &quot;#104281&quot;)) +
  scale_x_continuous(breaks = deltas, expand = expansion(mult = c(0.05, 0.2))) +
  ylim(0, 1) +
  labs(
    x = &quot;Difference in share applying to the hard department&quot;,
    y = &quot;Share of samples where A is below B&quot;,
    colour = &quot;Applicants per group&quot;, shape = &quot;Applicants per group&quot;
  ) +
  theme_minimal() +
  theme(legend.position = &quot;top&quot;, panel.grid.minor = element_blank())</pre>
<p><img src="https://i1.wp.com/statsandr.com/blog/why-the-overall-rate-can-flip-weighted-means-and-simpson-s-paradox-in-r/index_files/figure-html/plot-1.png?w=450&#038;ssl=1" alt="" style="display: block; margin: auto;" data-recalc-dims="1" /></p>
<p>Three things the simulation shows:</p>
<ol style="list-style-type: decimal">
<li><strong>At the threshold the result is a coin flip for every sample size.</strong> At a difference of 0.04, A is below B in about 47% to 49% of samples whether n is 100, 400 or 1,600. The share is slightly under 50% because samples where A and B admit exactly the same number are not counted as a flip.</li>
<li><strong>Below the threshold, small samples get it wrong often.</strong> With identical mixes (difference 0), group A is truly better in both departments, yet with 100 applicants per group, A is below B in 35% of samples. With 1,600 it drops to 11%.</li>
<li><strong>Above the threshold, larger samples make the flip almost certain.</strong> At a difference of 0.12 the flip shows in 70% of samples with n = 100 and in 99% with n = 1,600.</li>
</ol>
<p>So a larger sample sharpens whichever side of the threshold the true mix lies on. It does not move the threshold itself.</p>
</div>
<div id="which-rate-should-you-report" class="section level1">
<h1>Which rate should you report?</h1>
<p>The statistics do not choose between the department-level and the overall rate. The question does.</p>
<ul>
<li><strong>Department rates</strong> describe how each department treats the applicants it receives. They are the natural numbers if the question is whether a department’s admission decisions favour one gender.</li>
<li><strong>The overall rate</strong> also reflects where people choose to apply. It is the natural number if the question is what share of each gender’s applicants ended up admitted, whatever the reason for the difference.</li>
</ul>
<p>The Berkeley data alone cannot settle whether there was discrimination. The data are for one admission cycle, six departments and two recorded genders. The department rates show no systematic advantage for men. They do not show why women applied to the harder departments in larger numbers, or whether things that happen before an application (advising, funding, prior opportunities) played a role. Those are causal questions, and answering them takes assumptions and information beyond a table of counts.</p>
<p>The practical habit that follows from this is simple. When you see an overall rate for a group, ask which weights produced it, say which reference mix you used for any comparison, and show how the result changes when the mix changes.</p>
<p>Thanks for reading.</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 id="references" class="section level1 unnumbered">
<h1>References</h1>
<div id="refs" class="references csl-bib-body hanging-indent">
<div id="ref-bickel1975sex" class="csl-entry">
Bickel, Peter J, Eugene A Hammel, and J William O’Connell. 1975. <span>“Sex Bias in Graduate Admissions: Data from Berkeley: Measuring Bias Is Harder Than Is Usually Assumed, and the Evidence Is Sometimes Contrary to Expectation.”</span> <em>Science</em> 187 (4175): 398–404. <a href="https://doi.org/10.1126/science.187.4175.398" rel="nofollow" target="_blank">https://doi.org/10.1126/science.187.4175.398</a>.
</div>
</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://statsandr.com/blog/why-the-overall-rate-can-flip-weighted-means-and-simpson-s-paradox-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/why-the-overall-rate-can-flip-weighted-means-and-simpsons-paradox-in-r/">Why the overall rate can flip: weighted means and Simpson’s paradox in R</a>]]></content:encoded>
					
		
		<enclosure url="" length="0" type="" />

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

					<description><![CDATA[<div style = "width:60%; display: inline-block; float:left; ">
<p>olsrr 0.7.1 is on CRAN. olsrr provides tools for building and checking ordinary least squares regression models in R: regression summaries, variable selection, heteroskedasticity and normality tests, collinearity diagnostics, influence measures and residual plots, all built around lm() objects.<br />
We don’t usually write about patch releases, but this one deserves ...</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/olsrr-0-7-1/">olsrr 0.7.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://blog.rsquaredacademy.com/posts/olsrr-0-7-1/"> 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://i2.wp.com/blog.rsquaredacademy.com/img/olsrr-0-7-1.png?w=578&#038;ssl=1" class="img-fluid" style="width:100.0%" alt="olsrr hex logo next to the tagline Tools for building and checking OLS regression models in R, the line 0.7.1, corrected test results, the package name olsrr and olsrr.rsquaredacademy.com" data-recalc-dims="1"></p>
<style>
.ba-card{display:grid;grid-template-columns:1fr 1fr;gap:0;border:1px solid #d0d7de;border-radius:8px;overflow:hidden;margin:1rem 0 .5rem;font-size:.92rem}
.ba-card>div{padding:.75rem 1rem}
.ba-card .ba-before{background:#fff5f5;border-right:1px solid #d0d7de}
.ba-card .ba-after{background:#f3fbf5}
.ba-card h5{margin:0 0 .4rem;font-size:.8rem;letter-spacing:.04em;text-transform:uppercase;color:#57606a}
.ba-card code{font-size:.88rem}
.ba-card table{margin:0;width:100%}
.ba-card td{padding:.15rem .4rem;border:0}
.ba-card .chg{font-weight:700;background:#fff3b0;border-radius:3px;padding:0 .2rem}
.ba-call{font-size:.85rem;color:#57606a;margin:-.25rem 0 1rem}
.ba-note{font-size:.88rem;color:#57606a;border-left:3px solid #d0d7de;padding-left:.75rem;margin:.5rem 0 1.25rem}
@media (max-width:600px){.ba-card{grid-template-columns:1fr}.ba-card .ba-before{border-right:0;border-bottom:1px solid #d0d7de}}
</style>
<p><code>olsrr</code> 0.7.1 is on CRAN. <code>olsrr</code> provides tools for building and checking ordinary least squares regression models in R: regression summaries, variable selection, heteroskedasticity and normality tests, collinearity diagnostics, influence measures and residual plots, all built around <code>lm()</code> objects.</p>
<p>We don’t usually write about patch releases, but this one deserves a post:</p>
<ul>
<li>Several test and summary results change: Holm-adjusted Breusch-Pagan <img src="https://latex.codecogs.com/png.latex?p">-values, the Cramér–von Mises normality test, and the residual MSE/RMSE in model summaries. If you report these numbers, please re-run your analyses.</li>
<li>Every calculation and plot was checked against base R and reference packages (<code>car</code>, <code>lmtest</code> and <code>nortest</code>) for this release.</li>
<li>It is the first <code>olsrr</code> post since our <a href="https://blog.rsquaredacademy.com/posts/introducing-olsrr/index.html" rel="nofollow" target="_blank">introduction in 2019</a>, so it also covers what has been added since then.</li>
</ul>
<p><strong>Who should read what:</strong> if you report Holm-adjusted Breusch-Pagan <img src="https://latex.codecogs.com/png.latex?p">-values, Cramér–von Mises normality tests or MSE/RMSE from <code>olsrr</code>, read Behaviour changes first. Everyone else can skip to What’s 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;olsrr&quot;)</pre>
</details>
</div>
<p>You can see a full list of changes in the <a href="https://github.com/rsquaredacademy/olsrr/releases/tag/v0.7.1" rel="nofollow" target="_blank">release notes</a>.</p>
<section id="behaviour-changes" class="level2">
<h2 class="anchored" data-anchor-id="behaviour-changes">Behaviour changes</h2>
<p>These fixes change numbers you may already have in reports. In each case 0.7.1 now agrees with the base R or reference implementation, so the new values are the ones to use.</p>
<div class="ba-note">
<p>How we checked: every number in this post was re-run on CRAN <code>olsrr</code> 0.7.0 and 0.7.1, and the release passed an independent audit against base R, <code>car</code>, <code>lmtest</code> and <code>nortest</code> before it was submitted.</p>
</div>
<section id="breusch-pagan-test-holm-adjusted-p-values" class="level3">
<h3 class="anchored" data-anchor-id="breusch-pagan-test-holm-adjusted-p-values">Breusch-Pagan test: Holm-adjusted p-values</h3>
<p>With <code>ols_test_breusch_pagan(..., rhs = TRUE, multiple = TRUE, p.adj = &quot;holm&quot;)</code>, version 0.7.0 sorted the raw <img src="https://latex.codecogs.com/png.latex?p">-values and multiplied them by reversed ranks without the cumulative-maximum step of Holm’s procedure. A predictor could keep an adjusted <img src="https://latex.codecogs.com/png.latex?p">-value that was too small and be wrongly flagged at <img src="https://latex.codecogs.com/png.latex?%07lpha%20=%200.05">. Version 0.7.1 uses <code>stats::p.adjust(p, &quot;holm&quot;)</code>. In this three-predictor example the raw <img src="https://latex.codecogs.com/png.latex?p">-values are <code>0.0465</code>, <code>1.07e-05</code> and <code>0.0410</code>:</p>
<div class="cell">
<details open="" class="code-fold">
<summary>Code</summary>
<pre>set.seed(15)
n &lt;- 60
z &lt;- rnorm(n)
d &lt;- data.frame(x1 = z + rnorm(n), x2 = z + rnorm(n), x3 = z + rnorm(n))
d$y &lt;- rnorm(n) * exp(0.55 * z)

m_bp &lt;- lm(y ~ x1 + x2 + x3, data = d)
ols_test_breusch_pagan(m_bp, rhs = TRUE, multiple = TRUE, p.adj = &quot;holm&quot;)</pre>
</details>
<div class="cell-output cell-output-stdout">
<pre>
 Breusch Pagan Test for Heteroskedasticity
 -----------------------------------------
 Ho: the variance is constant            
 Ha: the variance is not constant        

       Data         
 -------------------
 Response : y 
 Variables: x1 x2 x3 

           Test Summary (Holm's p values)           
 -------------------------------------------------
  Variable           chi2       df         p       
 -------------------------------------------------
  x1                3.962893     1    8.192284e-02 
  x2               19.381555     1    3.211077e-05 
  x3                4.177610     1    8.192284e-02 
 -------------------------------------------------
  simultaneous     21.479644     3    8.369002e-05 
 -------------------------------------------------</pre>
</div>
</div>
<div class="ba-card" aria-label="Before and after: ols_test_breusch_pagan(m_bp, rhs = TRUE, multiple = TRUE, p.adj = " holm")"="">
<div class="ba-before"><h5 class="anchored">olsrr 0.7.0</h5>
<table class="caption-top table">
<tbody>
<tr class="odd">
<td>x1</td>
<td><span class="chg">0.0465</span></td>
</tr>
<tr class="even">
<td>x2</td>
<td>3.21e-05</td>
</tr>
<tr class="odd">
<td>x3</td>
<td>0.0819</td>
</tr>
</tbody>
</table>
</div>
<div class="ba-after"><h5 class="anchored">olsrr 0.7.1</h5>
<table class="caption-top table">
<tbody>
<tr class="odd">
<td>x1</td>
<td><span class="chg">0.0819</span></td>
</tr>
<tr class="even">
<td>x2</td>
<td>3.21e-05</td>
</tr>
<tr class="odd">
<td>x3</td>
<td>0.0819</td>
</tr>
</tbody>
</table>
</div>
</div>
<p class="ba-call">Same call on both CRAN versions: <code>ols_test_breusch_pagan(m_bp, rhs = TRUE, multiple = TRUE, p.adj = &quot;holm&quot;)</code>. Changed values are highlighted.</p>
<details>
<summary>
Code that produced both values
</summary>
<pre># Run once with each version, e.g. in two sessions:
# remotes::install_version(&quot;olsrr&quot;, &quot;0.7.0&quot;)   # then
# install.packages(&quot;olsrr&quot;)                    # 0.7.1
library(olsrr)
set.seed(15)
n &lt;- 60
z &lt;- rnorm(n)
d &lt;- data.frame(x1 = z + rnorm(n), x2 = z + rnorm(n), x3 = z + rnorm(n))
d$y &lt;- rnorm(n) * exp(0.55 * z)
m_bp &lt;- lm(y ~ x1 + x2 + x3, data = d)
ols_test_breusch_pagan(m_bp, rhs = TRUE, multiple = TRUE, p.adj = &quot;holm&quot;)$p</pre>
</details>
<p>In 0.7.0, <code>x1</code> remained below <code>0.05</code> (<code>0.0465</code>) even though <code>x3</code> had a smaller raw <img src="https://latex.codecogs.com/png.latex?p">-value and adjusted to <code>0.0819</code>. In 0.7.1, <code>x1</code> is <code>0.0819</code>, matching <code>stats::p.adjust()</code>.</p>
<p><strong>What to do:</strong> re-run any Holm-adjusted Breusch-Pagan tests; the 0.7.1 values match <code>stats::p.adjust()</code>.</p>
</section>
<section id="normality-test-cramérvon-mises" class="level3">
<h3 class="anchored" data-anchor-id="normality-test-cramérvon-mises">Normality test: Cramér–von Mises</h3>
<p>In 0.7.0, <code>ols_test_normality()</code> compared the Cramér–von Mises statistic with a standard uniform distribution instead of a normal distribution with mean and standard deviation estimated from the residuals, so it rejected normality for almost any regression. Version 0.7.1 calls <code>nortest::cvm.test()</code>:</p>
<div class="cell">
<details open="" class="code-fold">
<summary>Code</summary>
<pre>model &lt;- lm(mpg ~ disp + hp + wt + qsec, data = mtcars)
ols_test_normality(model)</pre>
</details>
<div class="cell-output cell-output-stdout">
<pre>-----------------------------------------------
       Test             Statistic       pvalue  
-----------------------------------------------
Shapiro-Wilk              0.9366         0.0600 
Kolmogorov-Smirnov        0.1152         0.7464 
Cramer-von Mises          0.0764         0.2230 
Anderson-Darling          0.5859         0.1188 
-----------------------------------------------</pre>
</div>
</div>
<div class="ba-card" aria-label="Before and after: ols_test_normality(lm(mpg ~ disp + hp + wt + qsec, mtcars))">
<div class="ba-before"><h5 class="anchored">olsrr 0.7.0</h5>
<table class="caption-top table">
<tbody>
<tr class="odd">
<td>Cramér–von Mises W</td>
<td><span class="chg">2.8122</span></td>
</tr>
<tr class="even">
<td>p-value</td>
<td><span class="chg">0.0000</span></td>
</tr>
</tbody>
</table>
</div>
<div class="ba-after"><h5 class="anchored">olsrr 0.7.1</h5>
<table class="caption-top table">
<tbody>
<tr class="odd">
<td>Cramér–von Mises W</td>
<td><span class="chg">0.0764</span></td>
</tr>
<tr class="even">
<td>p-value</td>
<td><span class="chg">0.2230</span></td>
</tr>
</tbody>
</table>
</div>
</div>
<p class="ba-call">Same call on both CRAN versions: <code>ols_test_normality(lm(mpg ~ disp + hp + wt + qsec, mtcars))</code>. Changed values are highlighted.</p>
<details>
<summary>
Code that produced both values
</summary>
<pre># Run once with each version, e.g. in two sessions:
# remotes::install_version(&quot;olsrr&quot;, &quot;0.7.0&quot;)   # then
# install.packages(&quot;olsrr&quot;)                    # 0.7.1
library(olsrr)
model &lt;- lm(mpg ~ disp + hp + wt + qsec, data = mtcars)
ols_test_normality(model)$cramer</pre>
</details>
<p>In 0.7.1, the Cramér–von Mises result (<code>p = 0.2230</code>) agrees with <code>nortest::cvm.test(residuals(model))</code> and aligns qualitatively with the Shapiro-Wilk (<code>0.0600</code>) and Anderson-Darling (<code>0.1188</code>) tests on the same residuals. (See What’s next about the Kolmogorov-Smirnov row.)</p>
<p><strong>What to do:</strong> treat earlier Cramér–von Mises rejections from <code>olsrr</code> as unreliable and re-run the test.</p>
</section>
<section id="residual-mse-and-rmse" class="level3">
<h3 class="anchored" data-anchor-id="residual-mse-and-rmse">Residual MSE and RMSE</h3>
<p>In 0.7.0, <code>ols_regress()</code> and <code>ols_model_performance()</code> divided the residual sum of squares by <img src="https://latex.codecogs.com/png.latex?n"> rather than by the residual degrees of freedom (<a href="https://github.com/rsquaredacademy/olsrr/issues/221" rel="nofollow" target="_blank">#221</a>, reported by <a href="https://github.com/viqule11" rel="nofollow" target="_blank">@viqule11</a>). For <code>lm(mpg ~ disp + hp + wt + qsec, data = mtcars)</code> (<img src="https://latex.codecogs.com/png.latex?n%20=%2032">, 27 residual degrees of freedom) that gave <code>MSE = 5.8011</code> and <code>RMSE = 2.4085</code>. Version 0.7.1 reports <code>MSE = 6.8754</code> and <code>RMSE = 2.6221</code>, matching the ANOVA residual mean square and <code>summary(model)$sigma</code>.</p>
<div class="ba-card" aria-label="Before and after: ols_regress(lm(mpg ~ disp + hp + wt + qsec, mtcars))">
<div class="ba-before"><h5 class="anchored">olsrr 0.7.0</h5>
<table class="caption-top table">
<tbody>
<tr class="odd">
<td>MSE</td>
<td><span class="chg">5.8011</span></td>
</tr>
<tr class="even">
<td>RMSE</td>
<td><span class="chg">2.4085</span></td>
</tr>
</tbody>
</table>
</div>
<div class="ba-after"><h5 class="anchored">olsrr 0.7.1</h5>
<table class="caption-top table">
<tbody>
<tr class="odd">
<td>MSE</td>
<td><span class="chg">6.8754</span></td>
</tr>
<tr class="even">
<td>RMSE</td>
<td><span class="chg">2.6221</span></td>
</tr>
</tbody>
</table>
</div>
</div>
<p class="ba-call">Same call on both CRAN versions: <code>ols_regress(lm(mpg ~ disp + hp + wt + qsec, mtcars))</code>. Changed values are highlighted.</p>
<details>
<summary>
Code that produced both values
</summary>
<pre># Run once with each version, e.g. in two sessions:
# remotes::install_version(&quot;olsrr&quot;, &quot;0.7.0&quot;)   # then
# install.packages(&quot;olsrr&quot;)                    # 0.7.1
library(olsrr)
model &lt;- lm(mpg ~ disp + hp + wt + qsec, data = mtcars)
r &lt;- ols_regress(model)
c(mse = r$mse, rmse = r$rmse)</pre>
</details>
<p><strong>What to do:</strong> expect slightly larger MSE and RMSE values; they now match base R.</p>
</section>
</section>
<section id="whats-new-since-2019" class="level2">
<h2 class="anchored" data-anchor-id="whats-new-since-2019">What’s new since 2019</h2>
<section id="stepwise-selection-with-locked-predictors" class="level3">
<h3 class="anchored" data-anchor-id="stepwise-selection-with-locked-predictors">Stepwise Selection with Locked Predictors</h3>
<p>Between versions 0.6.0 and 0.7.1, the variable selection family expanded to cover <img src="https://latex.codecogs.com/png.latex?p">-values, AIC, SBC (BIC), Sawa’s BIC (<code>sbic</code>), <img src="https://latex.codecogs.com/png.latex?R%5E2">, and adjusted <img src="https://latex.codecogs.com/png.latex?R%5E2">. All forward, backward, and both-direction selectors now accept <code>include</code> and <code>exclude</code> arguments (by name or column index) so baseline covariates or confounders stay in the model throughout selection.</p>
<p>On the <code>surgical</code> dataset, locking <code>age</code> and <code>alc_heavy</code> via <code>include</code> keeps both predictors in the base model (Step 0, <code>AIC = 795.956</code>) and through every subsequent addition and removal step, even though <code>age</code> itself has <img src="https://latex.codecogs.com/png.latex?p%20=%200.473"> in the final fit:</p>
<div class="cell">
<details open="" class="code-fold">
<summary>Code</summary>
<pre>m_surg &lt;- lm(
  y ~ bcs + pindex + enzyme_test + liver_test + age + gender + alc_mod + alc_heavy,
  data = surgical
)
ols_step_both_aic(m_surg, include = c(&quot;age&quot;, &quot;alc_heavy&quot;))</pre>
</details>
<div class="cell-output cell-output-stdout">
<pre>
                                Stepwise Summary                                
------------------------------------------------------------------------------
Step    Variable             AIC        SBC       SBIC        R2       Adj. R2 
------------------------------------------------------------------------------
 0      Base Model         795.956    803.912    637.696    0.17900    0.14680 
 1      liver_test (+)     763.110    773.055    606.421    0.56938    0.54354 
 2      enzyme_test (+)    752.416    764.350    596.755    0.65959    0.63180 
 3      pindex (+)         737.680    751.603    585.012    0.75030    0.72429 
 4      bcs (+)            732.494    748.406    581.938    0.78142    0.75351 
 5      liver_test (-)     732.339    746.262    580.934    0.77382    0.75026 
------------------------------------------------------------------------------

Final Model Output 
------------------

                           Model Summary                            
-------------------------------------------------------------------
R                         0.880       RMSE                 198.590 
R-Squared                 0.774       MSE                39438.163 
Adj. R-Squared            0.750       Coef. Var             28.286 
Pred R-Squared            0.688       AIC                  732.339 
MAE                     140.528       SBC                  746.262 
-------------------------------------------------------------------
 RMSE: Root Mean Square Error 
 MSE: Mean Square Error 
 MAE: Mean Absolute Error 
 AIC: Akaike Information Criteria 
 SBC: Schwarz Bayesian Criteria 

                                 ANOVA                                  
-----------------------------------------------------------------------
                   Sum of                                              
                  Squares        DF    Mean Square      F         Sig. 
-----------------------------------------------------------------------
Regression    6476488.730         5    1295297.746    32.844    0.0000 
Residual      1893031.807        48      39438.163                     
Total         8369520.537        53                                    
-----------------------------------------------------------------------

                                      Parameter Estimates                                        
------------------------------------------------------------------------------------------------
      model         Beta    Std. Error    Std. Beta      t        Sig         lower       upper 
------------------------------------------------------------------------------------------------
(Intercept)    -1237.653       225.517                 -5.488    0.000    -1691.085    -784.221 
        age       -1.787         2.473       -0.050    -0.723    0.473       -6.759       3.184 
  alc_heavy      306.655        73.188        0.303     4.190    0.000      159.500     453.809 
enzyme_test       11.244         1.314        0.601     8.555    0.000        8.601      13.887 
     pindex       10.062         1.633        0.428     6.163    0.000        6.779      13.344 
        bcs       81.587        17.870        0.329     4.566    0.000       45.657     117.516 
------------------------------------------------------------------------------------------------</pre>
</div>
</div>
</section>
<section id="ten-panel-diagnostic-grid" class="level3">
<h3 class="anchored" data-anchor-id="ten-panel-diagnostic-grid">Ten-Panel Diagnostic Grid</h3>
<p><code>ols_plot_diagnostics()</code> gathers ten residual, fit, leverage, and influence views for an <code>lm</code> object: residuals vs fitted values, deleted studentized residuals vs predicted values, studentized residuals vs leverage, normal Q-Q plot, actual vs fitted values, Cook’s D chart, centered fit spread, residual spread, residual histogram, and residual box plot.</p>
<p>Calling <code>ols_plot_diagnostics(model)</code> directly pages the panels in 2×2 grids (and in 0.7.1 draws cleanly inside scripts, functions, and loops as well as at the top level). Setting <code>print_plot = FALSE</code> returns the ten <code>ggplot</code> objects without drawing them first, so they can be arranged in a single layout:</p>
<div class="cell">
<details open="" class="code-fold">
<summary>Code</summary>
<pre>model &lt;- lm(mpg ~ disp + hp + wt + qsec, data = mtcars)
panels &lt;- ols_plot_diagnostics(model, print_plot = FALSE)
gridExtra::grid.arrange(grobs = panels, ncol = 2, top = &quot;Regression Diagnostics&quot;)</pre>
</details>
<div class="cell-output-display">
<div>
<figure class="figure">
<p><img src="https://i1.wp.com/blog.rsquaredacademy.com/posts/olsrr-0-7-1/index_files/figure-html/diag-grid-1.png?w=450&#038;ssl=1" class="img-fluid figure-img" alt="Ten-panel regression diagnostic grid for mpg ~ disp + hp + wt + qsec on mtcars, arranged in five rows of two panels: Residual vs Fitted Values, Deleted Studentized Residual vs Predicted Values, Outlier and Leverage Diagnostics, Normal Q-Q Plot, Actual vs Fitted for mpg, Cook's D Chart, centered fit spread and residual spread plots, Residual Histogram with normal curve, and Residual Box Plot."  data-recalc-dims="1"></p>
</figure>
</div>
</div>
</div>
</section>
<section id="model-performance-and-multi-model-comparison" class="level3">
<h3 class="anchored" data-anchor-id="model-performance-and-multi-model-comparison">Model Performance and Multi-Model Comparison</h3>
<p>Added in 0.7.0 and refined in 0.7.1, <code>ols_model_performance()</code> reports fit metrics for a single model, while <code>ols_compare_model_performance()</code> places competing models side by side across <img src="https://latex.codecogs.com/png.latex?R%5E2">, adjusted <img src="https://latex.codecogs.com/png.latex?R%5E2">, predicted <img src="https://latex.codecogs.com/png.latex?R%5E2">, AIC, SBC, SBIC, RMSE, and residual standard error (<code>sigma</code>):</p>
<div class="cell">
<details open="" class="code-fold">
<summary>Code</summary>
<pre>m1 &lt;- lm(mpg ~ wt + hp, data = mtcars)
m2 &lt;- lm(mpg ~ wt + hp + qsec, data = mtcars)
m3 &lt;- lm(mpg ~ wt + hp + qsec + disp, data = mtcars)

ols_compare_model_performance(m1, m2, m3)</pre>
</details>
<div class="cell-output cell-output-stdout">
<pre>  name        r2    r2_adj   r2_pred      aic      sbc     sbic     rmse
1   m1 0.8267855 0.8148396 0.7810871 156.6523 162.5153 66.43956 2.593412
2   m2 0.8347678 0.8170643 0.7819955 157.1426 164.4713 67.43259 2.577785
3   m3 0.8351443 0.8107212 0.7710297 159.0696 167.8640 70.04081 2.622095
     sigma
1 2.593412
2 2.577785
3 2.622095</pre>
</div>
</div>
</section>
<section id="weighted-linear-regression-in-ols_regress" class="level3">
<h3 class="anchored" data-anchor-id="weighted-linear-regression-in-ols_regress">Weighted Linear Regression in <code>ols_regress()</code></h3>
<p>In 0.7.1, <code>ols_regress()</code> supports weighted linear models fitted with <code>lm(..., weights = ...)</code>, matching base R’s <code>summary()</code>, <code>anova()</code>, and <code>confint()</code> for coefficient estimates, standard errors, <img src="https://latex.codecogs.com/png.latex?t">-statistics, confidence intervals, <img src="https://latex.codecogs.com/png.latex?R%5E2">, residual standard error, the ANOVA table, standardized betas, and weighted predicted <img src="https://latex.codecogs.com/png.latex?R%5E2">:</p>
<div class="cell">
<details open="" class="code-fold">
<summary>Code</summary>
<pre>d_wt &lt;- mtcars
d_wt$w &lt;- seq_len(nrow(d_wt)) / 8

m_w1 &lt;- lm(mpg ~ wt + hp, data = d_wt, weights = w)
ols_regress(m_w1)</pre>
</details>
<div class="cell-output cell-output-stdout">
<pre>                         Model Summary                          
---------------------------------------------------------------
R                       0.917       RMSE                 3.876 
R-Squared               0.841       MSE                 15.027 
Adj. R-Squared          0.830       Coef. Var           19.295 
Pred R-Squared          0.786       AIC                167.360 
MAE                     1.953       SBC                173.223 
---------------------------------------------------------------
 RMSE: Root Mean Square Error 
 MSE: Mean Square Error 
 MAE: Mean Absolute Error 
 AIC: Akaike Information Criteria 
 SBC: Schwarz Bayesian Criteria 

                               ANOVA                                 
--------------------------------------------------------------------
                Sum of                                              
               Squares        DF    Mean Square      F         Sig. 
--------------------------------------------------------------------
Regression    2308.267         2       1154.134    76.806    0.0000 
Residual       435.769        29         15.027                     
Total         2744.036        31                                    
--------------------------------------------------------------------

                                  Parameter Estimates                                    
----------------------------------------------------------------------------------------
      model      Beta    Std. Error    Std. Beta      t        Sig      lower     upper 
----------------------------------------------------------------------------------------
(Intercept)    37.938         1.545                 24.560    0.000    34.779    41.098 
         wt    -4.102         0.613       -0.666    -6.691    0.000    -5.355    -2.848 
         hp    -0.030         0.008       -0.345    -3.678    0.001    -0.047    -0.013 
----------------------------------------------------------------------------------------</pre>
</div>
</div>
</section>
</section>
<section id="other-improvements" class="level2">
<h2 class="anchored" data-anchor-id="other-improvements">Other improvements</h2>
<ul>
<li><code>ols_press()</code> weights the squared deleted residuals for weighted models, so <code>ols_pred_rsq()</code> no longer moves towards 1 when the weights are rescaled. For the weighted model shown above, multiplying the weights by 10 changed predicted <img src="https://latex.codecogs.com/png.latex?R%5E2"> from <code>0.9077</code> to <code>0.9908</code> in 0.7.0; in 0.7.1 both are <code>0.7859</code>.</li>
<li><code>ols_plot_resid_hist()</code> draws the bars with the same breaks as the normal curve. Previously the curve could be drawn at about half its correct height (<code>0.54</code> of the expected peak for <code>lm(hwy ~ displ + cty + year, data = ggplot2::mpg)</code>).</li>
<li><code>ols_plot_comp_plus_resid()</code> keeps every predictor for single-predictor and no-intercept models; 0.7.0 dropped a column and plotted a single point.</li>
<li><code>ols_test_outlier()</code> caps Bonferroni-adjusted <img src="https://latex.codecogs.com/png.latex?p">-values at 1 (0.7.0 could report values such as <code>6.62</code>).</li>
<li>Information criteria count parameters with the model rank, which fixes factor predictors and rank-deficient models; <code>ols_aic(corrected = TRUE)</code> matches the AICc formula (<a href="https://github.com/rsquaredacademy/olsrr/issues/224" rel="nofollow" target="_blank">#224</a>, <a href="https://github.com/rsquaredacademy/olsrr/issues/170" rel="nofollow" target="_blank">#170</a>, reported by <a href="https://github.com/comatrion" rel="nofollow" target="_blank">@comatrion</a>), and Mallows’ <img src="https://latex.codecogs.com/png.latex?C_p"> is correct for factor predictors (<a href="https://github.com/rsquaredacademy/olsrr/issues/92" rel="nofollow" target="_blank">#92</a>, reported by <a href="https://github.com/cccfran" rel="nofollow" target="_blank">@cccfran</a>) and in <code>ols_step_all_possible()</code> (<a href="https://github.com/rsquaredacademy/olsrr/issues/215" rel="nofollow" target="_blank">#215</a>, reported by <a href="https://github.com/LSantanaZA" rel="nofollow" target="_blank">@LSantanaZA</a>).</li>
<li>Stepwise selection handles transformed and factor predictors in refits (<a href="https://github.com/rsquaredacademy/olsrr/issues/244" rel="nofollow" target="_blank">#244</a>, <a href="https://github.com/rsquaredacademy/olsrr/issues/246" rel="nofollow" target="_blank">#246</a>), forward selection on saturated models (<a href="https://github.com/rsquaredacademy/olsrr/issues/199" rel="nofollow" target="_blank">#199</a>, reported by <a href="https://github.com/hirscht" rel="nofollow" target="_blank">@hirscht</a>), ties (<a href="https://github.com/rsquaredacademy/olsrr/issues/206" rel="nofollow" target="_blank">#206</a>, reported by <a href="https://github.com/kaygmz" rel="nofollow" target="_blank">@kaygmz</a>) and aliased terms (<a href="https://github.com/rsquaredacademy/olsrr/issues/172" rel="nofollow" target="_blank">#172</a>, reported by <a href="https://github.com/yayyb" rel="nofollow" target="_blank">@yayyb</a>).</li>
<li>Models fitted with <code>na.action = na.exclude</code> or with weights are handled consistently across plots and tests; diagnostics whose formulas assume unweighted least squares now stop with a clear error for weighted fits (<a href="https://github.com/rsquaredacademy/olsrr/issues/236" rel="nofollow" target="_blank">#236</a>).</li>
</ul>
</section>
<section id="whats-next" class="level2">
<h2 class="anchored" data-anchor-id="whats-next">What’s next</h2>
<p>Two issues remain open and will be fixed in 0.7.2. The Kolmogorov-Smirnov row of <code>ols_test_normality()</code> is not Lilliefors-corrected, so its <img src="https://latex.codecogs.com/png.latex?p">-value is too large when the mean and standard deviation are estimated from the residuals (<a href="https://github.com/rsquaredacademy/olsrr/issues/254" rel="nofollow" target="_blank">#254</a>). Until then, use the Shapiro-Wilk, Cramér–von Mises or Anderson-Darling rows, or call <code>nortest::lillie.test(residuals(model))</code>. Two panels of <code>ols_plot_diagnostics()</code> also share the title “Residual Fit Spread Plot” (<a href="https://github.com/rsquaredacademy/olsrr/issues/253" rel="nofollow" target="_blank">#253</a>); the plotted values and axis labels are correct.</p>
</section>
<section id="acknowledgements" class="level2">
<h2 class="anchored" data-anchor-id="acknowledgements">Acknowledgements</h2>
<p>A big thank you to everyone who contributed to <code>olsrr</code> since 2019 by opening issues, reporting bugs and sending pull requests: <a href="https://github.com/AminHP" rel="nofollow" target="_blank">@AminHP</a>, <a href="https://github.com/aravindhebbali" rel="nofollow" target="_blank">@aravindhebbali</a>, <a href="https://github.com/ashimkapoor" rel="nofollow" target="_blank">@ashimkapoor</a>, <a href="https://github.com/bappa10085" rel="nofollow" target="_blank">@bappa10085</a>, <a href="https://github.com/ButlerMSDA" rel="nofollow" target="_blank">@ButlerMSDA</a>, <a href="https://github.com/CarlosJara72" rel="nofollow" target="_blank">@CarlosJara72</a>, <a href="https://github.com/comatrion" rel="nofollow" target="_blank">@comatrion</a>, <a href="https://github.com/davidreilly007" rel="nofollow" target="_blank">@davidreilly007</a>, <a href="https://github.com/DrMondesire" rel="nofollow" target="_blank">@DrMondesire</a>, <a href="https://github.com/grantbrown" rel="nofollow" target="_blank">@grantbrown</a>, <a href="https://github.com/hirscht" rel="nofollow" target="_blank">@hirscht</a>, <a href="https://github.com/hkincaid" rel="nofollow" target="_blank">@hkincaid</a>, <a href="https://github.com/iankelk" rel="nofollow" target="_blank">@iankelk</a>, <a href="https://github.com/jmberros" rel="nofollow" target="_blank">@jmberros</a>, <a href="https://github.com/jorgevallejo" rel="nofollow" target="_blank">@jorgevallejo</a>, <a href="https://github.com/jst04004" rel="nofollow" target="_blank">@jst04004</a>, <a href="https://github.com/jtheog" rel="nofollow" target="_blank">@jtheog</a>, <a href="https://github.com/kaygmz" rel="nofollow" target="_blank">@kaygmz</a>, <a href="https://github.com/linusjf" rel="nofollow" target="_blank">@linusjf</a>, <a href="https://github.com/LSantanaZA" rel="nofollow" target="_blank">@LSantanaZA</a>, <a href="https://github.com/modche" rel="nofollow" target="_blank">@modche</a>, <a href="https://github.com/Molina-Valero" rel="nofollow" target="_blank">@Molina-Valero</a>, <a href="https://github.com/mwm-cbus" rel="nofollow" target="_blank">@mwm-cbus</a>, <a href="https://github.com/njrockwood" rel="nofollow" target="_blank">@njrockwood</a>, <a href="https://github.com/paleolimbot" rel="nofollow" target="_blank">@paleolimbot</a>, <a href="https://github.com/PsychlytxTD" rel="nofollow" target="_blank">@PsychlytxTD</a>, <a href="https://github.com/qwertytam" rel="nofollow" target="_blank">@qwertytam</a>, <a href="https://github.com/sblanco74" rel="nofollow" target="_blank">@sblanco74</a>, <a href="https://github.com/sckott" rel="nofollow" target="_blank">@sckott</a>, <a href="https://github.com/SunsetBlvd" rel="nofollow" target="_blank">@SunsetBlvd</a>, <a href="https://github.com/tikuma-lsuhsc" rel="nofollow" target="_blank">@tikuma-lsuhsc</a>, <a href="https://github.com/vasili111" rel="nofollow" target="_blank">@vasili111</a>, <a href="https://github.com/viqule11" rel="nofollow" target="_blank">@viqule11</a>, <a href="https://github.com/williamlai2" rel="nofollow" target="_blank">@williamlai2</a>, and <a href="https://github.com/yayyb" rel="nofollow" target="_blank">@yayyb</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/olsrr-0-7-1/"> 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/olsrr-0-7-1/">olsrr 0.7.1</a>]]></content:encoded>
					
		
		<enclosure url="https://blog.rsquaredacademy.com/img/olsrr-0-7-1.png" length="0" type="image/png" />

		<post-id xmlns="com-wordpress:feed-additions:1">404977</post-id>	</item>
		<item>
		<title>&#034;You get a free drink if you order a Burger or a Salad and a Dessert.&#034;</title>
		<link>https://www.r-bloggers.com/2026/11/you-get-a-free-drink-if-you-order-a-burger-or-a-salad-and-a-dessert/</link>
		
		<dc:creator><![CDATA[Jerry Tuttle]]></dc:creator>
		<pubDate>Tue, 17 Nov 2026 00:13:05 +0000</pubDate>
				<category><![CDATA[R bloggers]]></category>
		<guid isPermaLink="false">http://www.r-bloggers.com/?guid=ac1ed2a99803403feb7b140b0023b6d1</guid>

					<description><![CDATA[<div style = "width:60%; display: inline-block; float:left; ">
<p>     <br />
  A restaurant advertises, "You get a free drink if you order a Burger or a Salad and a Dessert." Suppose you only order a Burger. Should the restaurant give you a free drink? </p>
<p>    &#038;nb...</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/you-get-a-free-drink-if-you-order-a-burger-or-a-salad-and-a-dessert/">"You get a free drink if you order a Burger or a Salad and a Dessert."</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/you-get-free-drink-if-you-order-burger.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>
  
      
  A restaurant advertises, &#8220;You get a free drink if you order a Burger or a Salad and a Dessert.&#8221; Suppose you only order a Burger. Should the restaurant give you a free drink? <p>
  
  <div class="separator" style="clear: both;"><a href="https://i1.wp.com/blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEgGLuPGemW8FLmHzKy0OrHa_FwzfmNLcUqcigAzX82AuwoeFBf9QURG7uj2zX5jVhGKzH5aKJShN1Lei3tvPtlKnaek-aRHzQtffxBIcX_s28T1N-0UV_ROqLRjV8jW4JvtQzdU8OqhRJx7hk_Hdw7Z5-nlqrOzlC-vxzILD4ULdEjEaMtWOHTL31e7fCA/s1536/burger_or_salad.png?ssl=1" style="display: block; padding: 1em 0; text-align: center; " rel="nofollow" target="_blank"><img alt="" border="0" width="400" data-original-height="1024" data-original-width="450" src="https://i0.wp.com/blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEgGLuPGemW8FLmHzKy0OrHa_FwzfmNLcUqcigAzX82AuwoeFBf9QURG7uj2zX5jVhGKzH5aKJShN1Lei3tvPtlKnaek-aRHzQtffxBIcX_s28T1N-0UV_ROqLRjV8jW4JvtQzdU8OqhRJx7hk_Hdw7Z5-nlqrOzlC-vxzILD4ULdEjEaMtWOHTL31e7fCA/s400/burger_or_salad.png?resize=400%2C1024&#038;ssl=1" data-recalc-dims="1"/></a></div>
  
  
       
  Employee #1 says, &#8220;Burger alone gets the free drink!&#8221; Employee #2 says, &#8220;No, you need dessert too!&#8221; <p>
  
  
     
  How different is this question than the calculation of 1 + 2 * 3 ?  Many people would do the calculation left to right and get 9.  Mathematics has established conventions for the order of operation rules (remember the acronym PEMDAS, or BODMAS?), such as parentheses P come first (evaluate expressions inside parentheses first), and multiplication M precedes (is performed before) addition A.  Under those rules, math people would do the calculation as 1 + 2 * 3 = 1 + (2 * 3) and calculate it as 7.  <p>
  
       
  The burger question essentially asks, which operation takes precedence, OR or AND?  Should we interpret A or B and C as (A or B) and C, or else as A or (B and C)? Unlike mathematical notation, ordinary English does not necessarily provide an unambigious answer.<p>
 
  
     
  Although the burger question sounds silly, what if we asked an A or B and C in a web search? &#8220;Please provide a list of businesses offering services involving cats or dogs and providing instruction&#8221;?  Or what if your homeowners insurance policy contained a policy exclusion that is of the form A or B and C?  <p>
  

     
  For convenience, let&#8217;s call the burger A, the salad B, and the dessert C.
  In the original example, you only order a burger, so let&#8217;s agree that A = True, B = False, and C = False. <p>
  
       
  To a non-math person,  A or B and C is probably ambiguous.  Such a person might evaluate it left to right.  Then A or B and C becomes (A or B) and C = (True or False) and False = True and False = False, so no free drink. Or, maybe the common customer expectation is that they deserve the free drink, which essentially says AND has precedence over OR, so A or (B and C) = True or (False and False) = True or False = True, so yes a free drink.  <p>
  
     
  A court might rule in favor of the common customer expectation, partucularly if the restaurant&#8217;s wording is considered misleading.  If the restaurant wrote a confusing promotion, the customer may get the benefit of the doubt.  
  In insurance law there is a legal principle that when the policy was written solely by the insurer, ambiguities are interpreted strictly in favor of the policyholder. <p>
  
     
  What would Microsoft Excel say?  You can enter TRUE in cell A1, and FALSE in cells B1 and C1. Excel has AND and OR functions.  But you can not normally test precedence because Excel forces you to nest one function inside the other, so you force the priority.  What you can do is use the fact that TRUE equals 1 and FALSE equals 0, and that AND is similar to multiplication while OR is similar to addition.  So if cell D1 contains the formula = (A1 + B1 * C1) > 0  the result is TRUE, so yes a free drink. <p>
  
      
  Programming languages have their own precedence rules, but both R and Python give precedence to AND over OR. <p>
  
      
  Bottom line:  The restaurant&#8217;s wording is ambiguous when viewed as a logical expression. A math  or programming person would give AND precedence over OR, interpreting the offer as A or (B and C).  That means the burger alone gets a free drink.  Interestingly, this may also be what the ordinary customer would understand from the wording, although they might arrive at that interpretation therough ordinary English rather than mathematical rules.   <p>
  
      
  The lesson:  Don&#8217;t leave the interpretation of AND and OR to chance.  Use parentheses, or rewrite the sentence to make the intention unmistakenable. <p>
  
      
   The following code examples demonstrate actual programming precedence.

  
<pre>

# calculate A or B and C:
# In R:
A &lt;- TRUE
B &lt;- FALSE
C &lt;- FALSE
print(A | B &#038; C)   # result is TRUE

# In Python:
A = True
B = False
C = False
print(A or B and C)   # result is True

</pre><p>
  
</font>
<font size = 1>
Cartoon from Microsoft Copilot<br>
Survey:  https://docs.google.com/forms/d/e/1FAIpQLSf69ub5jZ493HFBkZCg23_lBT_-vNafy0SAS4kik2q7q2Eq_g/viewform
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/you-get-free-drink-if-you-order-burger.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/you-get-a-free-drink-if-you-order-a-burger-or-a-salad-and-a-dessert/">"You get a free drink if you order a Burger or a Salad and a Dessert."</a>]]></content:encoded>
					
		
		<enclosure url="" length="0" type="" />

		<post-id xmlns="com-wordpress:feed-additions:1">404916</post-id>	</item>
		<item>
		<title>smooth in Python: TBATS implementation</title>
		<link>https://www.r-bloggers.com/2026/11/smooth-in-python-tbats-implementation/</link>
		
		<dc:creator><![CDATA[Ivan Svetunkov]]></dc:creator>
		<pubDate>Mon, 16 Nov 2026 09:05:50 +0000</pubDate>
				<category><![CDATA[R bloggers]]></category>
		<guid isPermaLink="false">https://openforecast.org/?p=4717</guid>

					<description><![CDATA[<p>TBATS is a popular exponential smoothing model for data with complex seasonality: long seasonal periods, fractional ones (e.g. 52.18 weeks in a year, as I discussed in my previous post), and several of them at once. It models seasonality with harmonics and includes a Box-Cox transformation, ETS level and trend, ...</p>
<strong>Continue reading</strong>: <a href="https://www.r-bloggers.com/2026/11/smooth-in-python-tbats-implementation/">smooth in Python: TBATS implementation</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://openforecast.org/2026/11/16/smooth-in-python-tbats-implementation/"> Archives R - OpenForecast</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>TBATS is a popular exponential smoothing model for data with complex seasonality: long seasonal periods, fractional ones (e.g. 52.18 weeks in a year, as I <a href="https://openforecast.org/2026/11/09/the-problem-with-weekly-seasonality/" rel="nofollow" target="_blank">discussed in my previous post</a>), and several of them at once. It models seasonality with harmonics and includes a Box-Cox transformation, ETS level and trend, and ARMA errors (<a href="https://doi.org/10.1198/jasa.2011.tm09771" rel="nofollow" target="_blank">De Livera, Hyndman &#038; Snyder, 2011</a>).</p>
<p>But the original formulation has an issue. Its ARMA part sits in the error term, which then updates all the other states, including the level. So, the level and the ARMA compete for the same dynamics, and as the AR parameter approaches one, the permanent effect of a shock on the level grows without limit.</p>
<p>Claude and I have now implemented TBATS in the smooth package for Python (and R), reusing the core of ADAM. Without ARMA, it is exactly the original model (to rounding error). But ARMA is now a separate component: the level keeps its share of every shock, and the effect of ARMA decays over time, as it should.</p>
<p>The ADAM framework also brings several features that other implementations don’t have:</p>
<ol>
<li>Explanatory variables, e.g. promotions or prices;</li>
<li>Non-normal distributions, selected automatically;</li>
<li>Treatment of missing values (e.g. weeks with stockouts);</li>
<li>An occurrence model for intermittent demand.</li>
</ol>
<p>These are not bells and whistles: real demand data has promotions, gaps and zeros, and a model that cannot handle them pushes you into pre-processing hacks.</p>
<p>Here is an example on weekly sales with two promotional campaigns:</p>
<pre>from fcompdata import PromoData
from smooth import TBATS

model = TBATS(lags=[1, 52], h=13, holdout=True)
model.fit(PromoData.y, X=PromoData.xreg)
print(model)
fc = model.predict(h=13, interval=&quot;prediction&quot;, level=0.95)</pre>
<p>The function selects the number of harmonics, the trend, the ARMA orders and the distribution automatically, and the effects of the promotions are estimated jointly with everything else.</p>
<p>Does it work? I compared it with <code>forecast::tbats()</code> in R and <code>AutoTBATS</code> from <code>statsforecast</code> for Python (<a href="https://entrylib.org/p/2026.000007" rel="nofollow" target="_blank">paper</a>), here are the main findings:</p>
<ul>
<li>On 414 hourly series from M4, smooth was more accurate (mean RMSSE of 0.829 vs 0.909 and 1.063), its 95% prediction intervals had better coverage, and it was about 1.7 times faster than <code>forecast::tbats()</code>.</li>
<li>On 370 hourly series of electricity demand, the accuracy was a tie (0.795 vs 0.799 and 0.795), but smooth had better coverage and was again faster.</li>
<li>Also, when I switched to the Normal distribution, the model became even faster, but its 95% intervals covered fewer values than they should, so the automatic selection of distribution seems to help.</li>
</ul>
<p>The table in this post summarises the results. The details are <a href="https://entrylib.org/p/2026.000007" rel="nofollow" target="_blank">here</a>.</p>
<p>Try it: <code>pip install smooth</code><br />
<a href="https://github.com/openforecast-org/smooth/wiki/TBATS" rel="nofollow" target="_blank">Documentation</a></p>
<p>Message <a href="https://openforecast.org/2026/11/16/smooth-in-python-tbats-implementation/" rel="nofollow" target="_blank">smooth in Python: TBATS implementation</a> first appeared on <a href="https://openforecast.org/" rel="nofollow" target="_blank">OpenForecast</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://openforecast.org/2026/11/16/smooth-in-python-tbats-implementation/"> Archives R - OpenForecast</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/smooth-in-python-tbats-implementation/">smooth in Python: TBATS implementation</a>]]></content:encoded>
					
		
		<enclosure url="" length="0" type="" />

		<post-id xmlns="com-wordpress:feed-additions:1">404913</post-id>	</item>
		<item>
		<title>Interim Analysis: My Messy Notes</title>
		<link>https://www.r-bloggers.com/2026/11/interim-analysis-my-messy-notes/</link>
		
		<dc:creator><![CDATA[r on Everyday Is A School Day]]></dc:creator>
		<pubDate>Sun, 15 Nov 2026 00:00:00 +0000</pubDate>
				<category><![CDATA[R bloggers]]></category>
		<guid isPermaLink="false">https://www.kenkoonwong.com/blog/interim-analysis/</guid>

					<description><![CDATA[<div style = "width:60%; display: inline-block; float:left; ">
Why can’t we just peek at our data with α = 0.05 every time? 🤔 Gotta see it to believe it! Simulating the inflated error, seeing why it’s not Bonferroni, and rebuilding O’Brien-Fleming &#038; Lan-DeMets boundaries to match gsDesign. Hope it’s not an il...</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/interim-analysis-my-messy-notes/">Interim Analysis: My Messy Notes</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/interim-analysis/"> 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>Why can’t we just peek at our data with α = 0.05 every time? <img src="https://s.w.org/images/core/emoji/13.0.0/72x72/1f914.png" alt="🤔" class="wp-smiley" style="height: 1em; max-height: 1em;" /> Gotta see it to believe it! Simulating the inflated error, seeing why it’s not Bonferroni, and rebuilding O’Brien-Fleming &#038; Lan-DeMets boundaries to match gsDesign. Hope it’s not an illusion of learning <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>
</blockquote>
<p><img src="https://i0.wp.com/www.kenkoonwong.com/blog/interim-analysis/interim-analysis.png?w=578&#038;ssl=1" alt="" data-recalc-dims="1"></p>




<h2 id="motivations">Motivations
  <a href="https://www.kenkoonwong.com/blog/interim-analysis/#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’ve always heard “interim analysis” thrown around in trial papers but never really understood what’s happening under the hood. Why can’t we just peek at 1.96 every time? And isn’t this just Bonferroni? Turns out it’s not! Let’s dig in and simulate our way to understanding.</p>




<h2 id="objectives">Objectives:
  <a href="https://www.kenkoonwong.com/blog/interim-analysis/#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/interim-analysis/#what" rel="nofollow" target="_blank">What Is Interim Analysis?</a></li>
<li>
<a href="https://www.kenkoonwong.com/blog/interim-analysis/#obrien" rel="nofollow" target="_blank">What’s O’Brien-Fleming Method?</a></li>
<li>
<a href="https://www.kenkoonwong.com/blog/interim-analysis/#code" rel="nofollow" target="_blank">How To Perform It?</a></li>
<li>
<a href="https://www.kenkoonwong.com/blog/interim-analysis/#scratch" rel="nofollow" target="_blank">How To Do It From Scratch?</a>
<ul>
<li>
<a href="https://www.kenkoonwong.com/blog/interim-analysis/#obrien-method" rel="nofollow" target="_blank">O’Brien-Fleming Method</a></li>
<li>
<a href="https://www.kenkoonwong.com/blog/interim-analysis/#lan" rel="nofollow" target="_blank">Lan De Mat &#038; Obrien Fleming Method</a></li>
<li>
<a href="https://www.kenkoonwong.com/blog/interim-analysis/#compare" rel="nofollow" target="_blank">Comparison</a></li>
</ul>
</li>
<li>
<a href="https://www.kenkoonwong.com/blog/interim-analysis/#opportunities" rel="nofollow" target="_blank">Opportunities For Improvement</a></li>
<li>
<a href="https://www.kenkoonwong.com/blog/interim-analysis/#lessons" rel="nofollow" target="_blank">Lessons Learnt</a></li>
</ul>




<h2 id="what">What Is Interim Analysis?
  <a href="https://www.kenkoonwong.com/blog/interim-analysis/#what" 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>An interim analysis is a planned look at the data half way through a study, before all participants have been enrolled or followed up. They do it for practical and ethical reasons: if a treatment is clearly working, or clearly harmful, it isn’t right to keep randomizing people to the worse option, and if it’s clearly going nowhere, they can save time and resources by stopping early. The catch is that every extra look is another chance to find a “significant” result purely by luck. Peeking twice at the usual 5% threshold pushes the false-positive rate up. Interim analysis methods, such as O’Brien-Fleming boundaries, fix this by setting a stricter bar at the early looks so that the overall error rate stays at 5%.</p>
<p>Now you know me, I’m the see it to believe kind of person. Let’s try to simulate this with multiple trials and see if that’s true</p>
<pre>library(tidyverse)
n &lt;- 500
prob &lt;- 0.5
peek &lt;- c(n/2,n)
zscore_vec &lt;- c()
trial &lt;- 100000
count_false &lt;- vector(mode = &quot;numeric&quot;, length = trial)

for (trial_i in 1:trial) {
  # for reproducibility
  set.seed(trial_i)
  
  # get sim data
  control &lt;- rbinom(n,1,prob)
  rx &lt;- rbinom(n,1,prob)
  
  # look at when n is 250, and when n is 500
  for (i in 1:length(peek)) {
    m  &lt;- peek[i]
    pA &lt;- mean(rx[1:m])
    pB &lt;- mean(control[1:m])
    p_pool &lt;- (pA + pB) / 2
    se &lt;- sqrt(p_pool * (1 - p_pool) * (2 / m))
    
    # calculate z score
    zscore_vec[i] &lt;- abs(pA - pB) / se
  }
  # record zscore if &gt; 1.96 (~pval 0.05)
  if (any(zscore_vec &gt; 1.96)) { count_false[trial_i] &lt;- 1 }
}

# what percent of family-wise error?
(val &lt;- count_false |&gt; mean())

## [1] 0.08952
</pre><p>Lots of code, I hope some of the comments on the codes are self-explanatory. So we basically simulated a no difference result of 2 groups. We used zscore of 1.96 which is our 5% alpha to see if any of these z scores were above the threshold (it’s not supposed to, remember, there is no difference in this truth!). We expect it to be ~5% but we got 8.952% instead! Wow! That’s 3.952% higher than our threshold, not good! <img src="https://s.w.org/images/core/emoji/13.0.0/72x72/1f914.png" alt="🤔" class="wp-smiley" style="height: 1em; max-height: 1em;" /></p>
<blockquote>
<p>Note to self: The confusion of false postive/discovery/family-wise examples. If you test 90 placebo and 10 real rx and get 15 “significants”, 5 of them wrong: the <code>false positive rate</code> is 5/90 (how often placebos get credit) aka (1 &#8211; specificity), the <code>false discovery rate</code> is 5/15 (how many of your hits are wrong) aka (1 &#8211; ppv [aka precision]), and the <code>family-wise error rate</code> is the chance of getting even one false hit across the whole set, which is what interim analysis controls across looks.</p>
</blockquote>
<p>wow, doesn’t that remind us of something here? Multiplicity, yea? Maybe, kind of. Now, what if we’re being conservative like bonferonni and split that 5% twice? and see how much false positive did we get?</p>
<pre>count_false &lt;- vector(mode = &quot;numeric&quot;, length = trial)

for (trial_i in 1:trial) {
  # for reproducibility
  set.seed(trial_i)
  
  # get sim data
  control &lt;- rbinom(n,1,prob)
  rx &lt;- rbinom(n,1,prob)
  
  # look at when n is 250, and when n is 500
  for (i in 1:length(peek)) {
    m  &lt;- peek[i]
    pA &lt;- mean(rx[1:m])
    pB &lt;- mean(control[1:m])
    p_pool &lt;- (pA + pB) / 2
    se &lt;- sqrt(p_pool * (1 - p_pool) * (2 / m))
    
    # calculate z score
    zscore_vec[i] &lt;- abs(pA - pB) / se
  }
  # record zscore if &gt; 2.24, two tails with two looks (divide 5% to 2)
  if (any(zscore_vec &gt; 2.24)) { count_false[trial_i] &lt;- 1 }
}

# what percent of family wise error rate?
(val &lt;- count_false |&gt; mean())

## [1] 0.04093
</pre><p>What !?!?! 4.093% !?! It’s a bit lower than expected and we may be wasting 0.907% of our threshold! This is also not good! If there truly is a signal, we may be missing it because we are being too conservative. So, what if we use the O’Brien-Fleming method to set our threshold? Let’s see how that works out.</p>




<h2 id="obrien">What’s O’Brien-Fleming Method?
  <a href="https://www.kenkoonwong.com/blog/interim-analysis/#obrien" 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>O’Brien-Fleming is a way of setting stopping boundaries for interim analyses, and it’s the most widely used method in clinical trials. The idea is to be very strict early and lenient late. At the first look, when you have little data, you need overwhelming evidence to stop, a z-score of about 2.80 (pval = 0.005110261) with two looks. By the final analysis, the bar drops back to about 1.98 (pval = 0.04770353), barely above the usual 1.96. Because so little alpha is spent early, the trial almost never stops on a fluke, and the final analysis keeps nearly all of its power. <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;" /> Let’s take a look of its family wise error rate like before</p>
<pre>count_false &lt;- vector(mode = &quot;numeric&quot;, length = trial)

for (trial_i in 1:trial) {
  # for reproducibility
  set.seed(trial_i)
  
  # get sim data
  control &lt;- rbinom(n,1,prob)
  rx &lt;- rbinom(n,1,prob)
  
  # look at when n is 250, and when n is 500
  for (i in 1:length(peek)) {
    m  &lt;- peek[i]
    pA &lt;- mean(rx[1:m])
    pB &lt;- mean(control[1:m])
    p_pool &lt;- (pA + pB) / 2
    se &lt;- sqrt(p_pool * (1 - p_pool) * (2 / m))
    
    # calculate z score
    zscore_vec[i] &lt;- abs(pA - pB) / se
  }
  # record zscore if &gt; O&#39;Brien-Fleming, two looks, notice the zscores are no longer 1.96
  bounds &lt;- c(2.80, 1.98) 
  if (any(zscore_vec &gt; bounds)) {count_false[trial_i] &lt;- 1}
}

# what percent of family wise error?
(val &lt;- count_false |&gt; mean())

## [1] 0.0489
</pre><p>Alright! That’s much better! <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;" /> Closer to the 5%. As I was learning this, I just realized that this is very different from multiplicity because the second look technically is correlated to the first look because it looks at the same data again! The two looks share half their data, so their z-scores have a correlation of √0.5 ≈ 0.71. Bonferroni treats them as if they were barely related, so it over-adjusts. <img src="https://s.w.org/images/core/emoji/13.0.0/72x72/1f914.png" alt="🤔" class="wp-smiley" style="height: 1em; max-height: 1em;" /> Wow, that totally makes sense now! Ok, now how do we get sample calculation + obrien fleming method with <code>gsDesign</code>? 
<a href="https://www.kenkoonwong.com/blog/interim-analysis/#scratch" rel="nofollow" target="_blank">Take note below, the history of obrien-fleming and Lan De Mat</a></p>




<h2 id="code">How To Perform It?
  <a href="https://www.kenkoonwong.com/blog/interim-analysis/#code" 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>Let’s say we want to design a RCT of cefdinir vs cephalexin. Looking at 
<a href="https://academic.oup.com/ofid/article/12/10/ofaf501/8277239?login=false" rel="nofollow" target="_blank">this study</a>, without adjustment, cefdinir had a 23.4% treatment failure compared to cephalexin 12.5%. With 80% power, what sample size, what’s the upper boundary of z score we need if we want 3 looks on our interim analyses?</p>
<pre>library(gsDesign)
p1 &lt;- 0.234
p2 &lt;- 0.125

# fixed design: total sample size, both groups together
(n_fix &lt;- nBinomial(p1 = p1, p2 = p2, alpha = 0.025, beta = 0.2))

## [1] 386.8202
</pre><p>Total sample size needed is 386.820172, will have to divide this by 2. Let’s have gsDesign tell us the upper boundary zscore and when to look.</p>
<pre># group sequential: 3 equally spaced looks, O&#39;Brien-Fleming spending
d &lt;- gsDesign(k = 3, test.type = 2, alpha = 0.025, beta = 0.2,
              n.fix = n_fix, sfu = sfLDOF)

sample &lt;- d$n.I / 2           
bound &lt;- d$upper$bound           
pval &lt;- 2 * (1 - pnorm(d$upper$bound))  
(table &lt;- tibble(number_per_group=sample,zscore_needed=bound,p_value=pval))

## # A tibble: 3 × 3
##   number_per_group zscore_needed  p_value
##              &lt;dbl&gt;         &lt;dbl&gt;    &lt;dbl&gt;
## 1             65.3          3.71 0.000207
## 2            131.           2.51 0.0120  
## 3            196.           1.99 0.0463
</pre><p>Per group, we will need the above numbers to take a peek. Hooray! Now we kind of understand the surface of the goal and why we need to do this so we don’t inflate our family-wise error rate. Now, let’s try to do this from scratch and see if we can get the same numbers as <code>gsDesign</code> did. Take note that this time we will be using the first simulate DGP with no diff, not the cefdinir study.</p>




<h2 id="scratch">How To Do It From Scratch?
  <a href="https://www.kenkoonwong.com/blog/interim-analysis/#scratch" 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>So who came up with what? <img src="https://s.w.org/images/core/emoji/13.0.0/72x72/1f914.png" alt="🤔" class="wp-smiley" style="height: 1em; max-height: 1em;" /> O’Brien and Fleming came first (1979). Their idea: be super strict early when data is thin, and relax at the end. Every boundary is just one number c divided by √t, and you search for the c that keeps the family-wise error at 5%. Simple, but you had to fix when you’d look ahead of time. Then Lan and DeMets came along (1983) and said, “great idea, but what if we can’t stick to the schedule?” So they made the spending function: decide how much of the 5% you’ve used up at any point, and each look only spends its share. Same strict-early shape, but now you can peek whenever you need to. That’s what gsDesign’s sfLDOF does, and why everyone just calls it “O’Brien-Fleming” anyway! <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>
<p>Too many words? Yea, I know how you feel. Let’s break things down and code it to understand it.</p>
<p>Let’s start with the simplest O’Brien-Fleming method. We will simulate 3 looks at n=500, with 100,000 trials first and calculate the zscores for each look.</p>
<pre>n &lt;- 500
prob &lt;- 0.5
trial &lt;- 100000
k &lt;- 3
zscore_mat &lt;- matrix(nrow = trial, ncol = k)
gp &lt;- round(n/k)
peek &lt;- c(gp, gp*2, n)

for (trial_i in 1:trial) {
  # for reproducibility
  set.seed(trial_i)
  
  # get sim data
  control &lt;- rbinom(n,1,prob)
  rx &lt;- rbinom(n,1,prob)
  
  # peek at respective k
  for (i in 1:k) {
    m  &lt;- peek[i]
    pA &lt;- mean(rx[1:m])
    pB &lt;- mean(control[1:m])
    p_pool &lt;- (pA + pB) / 2
    se &lt;- sqrt(p_pool * (1 - p_pool) * (2 / m))
    
    # calculate z score, record it
    zscore_mat[trial_i, i] &lt;- abs(pA - pB) / se
  }
}
</pre>



<h3 id="obrien-method">O’Brien-Fleming Method
  <a href="https://www.kenkoonwong.com/blog/interim-analysis/#obrien-method" 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>
<ol>
<li>Start with final z score, let’s choose 1.96 as a guess and search upwards.</li>
<li>Then back calculate second and first look by dividing by square root of information fraction (t). For example, if we have 3 looks, the first look will be 1/3 of the information, second look will be 2/3 of the information and final look will be 3/3 of the information.</li>
<li>Then calculate the total family wise error rates for each trial and call it <code>alpha_final</code>.</li>
<li>Then look at the simulated data and filter out <code>alpha_final</code> between 0.045 and 0.05, then see what z scores for first and second look.</li>
</ol>
<pre># obrien fleming
df &lt;- data.frame(zscore_mat) |&gt;
  as_tibble()

final_z_seq &lt;- seq(1.96, 2.5, 0.001)
t2_z_s_seq &lt;- final_z_seq / sqrt(2/3)
t1_z_s_seq &lt;- final_z_seq / sqrt(1/3)

for (i in 1:length(final_z_seq)) {

# record 1 if zscore passes the respective threshold for each look
alpha_final &lt;- df |&gt;
  mutate(crossed = case_when(
    X3 &gt; final_z_seq[i] ~ 1,
    X2 &gt; t2_z_s_seq[i] ~ 1,
    X1 &gt; t1_z_s_seq[i] ~ 1,
    TRUE ~ 0
  )) |&gt;
  pull(crossed) |&gt;
  mean()

if (alpha_final &lt; 0.05 &#038; alpha_final &gt;= 0.045) { print(paste0(&quot;total alpha: &quot;, alpha_final ,&quot; .found it, it&#39;s on &quot;,i, &quot; &quot;, t1_z_s_seq[i], &quot; &quot;, t2_z_s_seq[i], &quot; &quot;,final_z_seq[i])) }
}

## [1] &quot;total alpha: 0.0494499999999998 .found it, it&#39;s on 65 3.50567083451941 2.47888361969658 2.024&quot;
## [1] &quot;total alpha: 0.0463299999999999 .found it, it&#39;s on 66 3.50740288532698 2.48010836456797 2.025&quot;
## [1] &quot;total alpha: 0.0454099999999999 .found it, it&#39;s on 67 3.50913493613455 2.48133310943936 2.026&quot;
</pre><p>Nice! That worked! Alright, now let’s look at the Lan De Mat & Obrien Fleming method. The idea is to calculate the alpha spent at each look and then find the z scores for each look.</p>




<h3 id="lan">Lan De Mat & Obrien Fleming Method
  <a href="https://www.kenkoonwong.com/blog/interim-analysis/#lan" 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>So Lan De Mat introduced spend function, which makes the O’Brien-Fleming method more flexible. The idea is to calculate the alpha spent at each look and then find the z scores for each look. The formula for the spend function is <code>2 - 2 * pnorm(qnorm(1 - alpha/2) / sqrt(t))</code>. 
<a href="https://academic.oup.com/biomet/article-abstract/70/3/659/247777" rel="nofollow" target="_blank">here</a> is the paper that derives it, might be a good blog post next time to learn. For now we’ll take it as is and roll with it. The idea is that it’s the chance a random walk crosses a fixed line by time t (the reflection principle)</p>
<ol>
<li>Calculate spending for look 1 with the formula. (note the alpha here is 0.025 for one tail). This spending will be in percentage (like p val).</li>
<li>Sort descending of the first look zscore from our simulation data, then remove the spending percentage of the first look, but record the first zscore value (that would be our first z score on first look). Save into a new dataframe. PS: this is like saying, I’m OK with the false positive of these much on first look.</li>
<li>Calculate the spending for look 2 with the formula, the subtract the first look spending.</li>
<li>Sort descending of the second look zscore of the new dataframe, then record the second zscore value, and remove the spending percentage of the second look on the new dataframe.</li>
<li>Calculate the spending for look 3 (which is 0.025), then subtract of the third look spending to second+one (cumulative) look spending, then do the same as above, record zscore and filter out the rest based on spending 3 percentage.</li>
</ol>
<p>Wow, ok too many words above. Use code to help understand.</p>
<pre># calc spend1 
t &lt;- 1/3                                   
alpha &lt;- 0.025                                 
spend1 &lt;- 2 - 2 * pnorm(qnorm(1 - alpha/2) / sqrt(t))

# filter for those X1 with less than zscore1
df1 &lt;- data.frame(zscore_mat) |&gt;
  as_tibble() |&gt;
  arrange(desc(X1)) |&gt;
  slice(round(spend1*trial*2+1):trial)

zscore1 &lt;- data.frame(zscore_mat) |&gt;
  as_tibble() |&gt;
  arrange(desc(X1)) |&gt;
  slice_head(n = round(spend1*trial*2)) |&gt;
  slice_tail(n = 1) |&gt;
  pull(X1)

# calc spend2
t &lt;- 2/3
spend2_cum &lt;- 2 - 2 * pnorm(qnorm(1 - alpha/2) / sqrt(t))   
spend2 &lt;- spend2_cum - spend1                                

# find how many to look at 
head_num &lt;- round(spend2 * 2 * trial)                                             

# head of however many false positive allowed
zscore2 &lt;- df1 |&gt;
  arrange(desc(X2)) |&gt; 
  slice_head(n = head_num) |&gt;
  slice_tail(n = 1) |&gt;
  pull(X2)

df2 &lt;- df1 |&gt;
  arrange(desc(X2)) |&gt;
  slice((head_num+1):nrow(df1))

# calc spend3
spend3 &lt;- alpha - spend2_cum      
head_num &lt;- round(spend3 * 2 * trial)                

zscore3 &lt;- df2 |&gt;
  arrange(desc(X3)) |&gt;
  slice(head_num) |&gt;
  pull(X3)

zscore1 ; zscore2 ; zscore3

## [1] 3.612396

## [1] 2.480686

## [1] 2.023874
</pre><p>Alright, not too shabby. Looks OK. Let’s use new data to calculate our total family wise error rate.</p>
<pre>### check family wise error
count_false &lt;- vector(mode = &quot;numeric&quot;, length = trial)

for (trial_i in 1:trial) {
  # for reproducibility
  set.seed(trial_i + trial)
  
  # get sim data
  control &lt;- rbinom(n,1,prob)
  rx &lt;- rbinom(n,1,prob)
  
  # peek at respective k
  for (i in 1:length(peek)) {
    m  &lt;- peek[i]
    pA &lt;- mean(rx[1:m])
    pB &lt;- mean(control[1:m])
    p_pool &lt;- (pA + pB) / 2
    se &lt;- sqrt(p_pool * (1 - p_pool) * (2 / m))
    
    # calculate z score
    zscore_vec[i] &lt;- abs(pA - pB) / se
  }
  # new bounds we found 
  bounds &lt;- c(zscore1, zscore2, zscore3) 
  if (any(zscore_vec &gt; bounds)) {count_false[trial_i] &lt;- 1}
}

# what percent of family wise error?
(val &lt;- count_false |&gt; mean())

## [1] 0.05027
</pre><p>Sweet! <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;" /> Alright, let’s see how the professionals do it?</p>
<pre>## gsDesign
d0 &lt;- gsDesign(k = 3, test.type = 2, alpha = 0.025, sfu = sfLDOF)
d0$upper$bound      

## [1] 3.710303 2.511427 1.993048
</pre>



<h3 id="compare">Comparison
  <a href="https://www.kenkoonwong.com/blog/interim-analysis/#compare" 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 put them all on a table</p>
<table>
<thead>
<tr>
<th style="text-align:right">look</th>
<th style="text-align:right">O’Brien-Fleming sim</th>
<th style="text-align:right">O’Brien-Fleming gsDesign</th>
<th style="text-align:right">Lan-DeMets sim</th>
<th style="text-align:right">Lan-DeMets gsDesign</th>
</tr>
</thead>
<tbody>
<tr>
<td style="text-align:right">1</td>
<td style="text-align:right">3.51</td>
<td style="text-align:right">3.47</td>
<td style="text-align:right">3.61</td>
<td style="text-align:right">3.71</td>
</tr>
<tr>
<td style="text-align:right">2</td>
<td style="text-align:right">2.48</td>
<td style="text-align:right">2.45</td>
<td style="text-align:right">2.48</td>
<td style="text-align:right">2.51</td>
</tr>
<tr>
<td style="text-align:right">3</td>
<td style="text-align:right">2.02</td>
<td style="text-align:right">2.00</td>
<td style="text-align:right">2.02</td>
<td style="text-align:right">1.99</td>
</tr>
</tbody>
</table>
<p>Not bad at all! <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;" /> Our sims land within about 0.1 of the professionals on both methods. The small gaps are from our binary outcome ?maybe. The z-scores come in little jumps, so we can’t hit the boundaries exactly. Also, take note that we got here by brute-force simulation, not the real math. gsDesign uses the multivariate normal distribution with the correlation matrix between looks (remember sqrt(t1/t2)?) to calculate these boundaries exactly. That’s a project for next time!</p>




<h2 id="opportunities">Opportunities For Improvement
  <a href="https://www.kenkoonwong.com/blog/interim-analysis/#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>Calculate the boundaries exactly with mvtnorm::pmvnorm (no simulation noise)</li>
<li>Simulate power under a real effect, not just the null</li>
<li>Add a futility boundary (test.type = 4) to stop when it’s clearly going nowhere</li>
<li>Look at how stopping early overestimates the effect size</li>
<li>Use a continuous outcome to get rid of the binary lumpiness</li>
<li>Learn derivation of reflection principle behind the Lan-DeMets formula</li>
</ul>




<h2 id="lessons">Lessons learnt
  <a href="https://www.kenkoonwong.com/blog/interim-analysis/#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 the simple interim analysses</li>
<li>learnt basic <code>gsDesign</code></li>
<li>learnt that alpha borrowing in interim analyses is not the same as multiplicity, because the second look is correlated to the first look. Bonferroni treats them as if they were barely related, so it over-adjusts. <img src="https://s.w.org/images/core/emoji/13.0.0/72x72/1f914.png" alt="🤔" class="wp-smiley" style="height: 1em; max-height: 1em;" /></li>
<li>learnt interim analyses true zscore estimation requires multivariate normal distribution</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/interim-analysis/"> 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/interim-analysis-my-messy-notes/">Interim Analysis: My Messy Notes</a>]]></content:encoded>
					
		
		<enclosure url="" length="0" type="" />

		<post-id xmlns="com-wordpress:feed-additions:1">404902</post-id>	</item>
		<item>
		<title>pyr.js: Python and R in HTML pages, with one script tag</title>
		<link>https://www.r-bloggers.com/2026/11/pyr-js-python-and-r-in-html-pages-with-one-script-tag/</link>
		
		<dc:creator><![CDATA[T. Moudiki]]></dc:creator>
		<pubDate>Sun, 15 Nov 2026 00:00:00 +0000</pubDate>
				<category><![CDATA[R bloggers]]></category>
		<guid isPermaLink="false">https://thierrymoudiki.github.io//blog/2026/11/15/python/r/javascript/pyr_js</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-pages-with-one-script-tag/">pyr.js: Python and R in HTML pages, with one script tag</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/15/python/r/javascript/pyr_js"> 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>What if you could put <strong>Python</strong> or <strong>R</strong> code in an HTML page, double-click the file, and have it run? No server, no build step, no install, and nothing sent anywhere: everything runs in the browser.</p>

<p>That’s what <a href="https://github.com/Techtonique/pyr.js" rel="nofollow" target="_blank"><code>pyr.js</code></a> does. I built it this week with Claude (Anthropic’s AI assistant), which wrote the code and tests from my design decisions and verified everything in a headless browser. The heavy lifting is done by <a href="https://pyodide.org/" rel="nofollow" target="_blank">Pyodide</a> (Python compiled to WebAssembly) and <a href="https://docs.r-wasm.org/webr/latest/" rel="nofollow" target="_blank">webR</a> (same thing for R). <code>pyr.js</code> is the glue: a single file, about 460 lines you can actually read, that finds the Python and R code in your page and connects it to your HTML.</p>

<h2 id="a-first-example">A first example</h2>

<p>Save this as an <code>.html</code> file and open it in your browser:</p>

<pre>&lt;script src=&quot;https://cdn.jsdelivr.net/gh/Techtonique/pyr.js@v0.1.0/pyr.js&quot;&gt;&lt;/script&gt;

&lt;p id=&quot;count&quot;&gt;count = 0&lt;/p&gt;
&lt;button py-click=&quot;add_one()&quot; py-out=&quot;count&quot;&gt;Add&lt;/button&gt;

&lt;script type=&quot;text/python&quot;&gt;
count = 0

def add_one():
    global count
    count += 1
    return f&quot;count = {count}&quot;
&lt;/script&gt;
</pre>

<p><code>py-click</code> runs Python when the button is clicked, and <code>py-out</code> says where the result goes. Any DOM event works the same way (<code>py-input</code>, <code>py-change</code>, …), and for R, it’s <code>r-click</code>, <code>r-input</code>, and so on. R’s printed output and plots show up directly in the page:</p>

<pre>&lt;label&gt;Points: &lt;input type=&quot;range&quot; min=&quot;10&quot; max=&quot;500&quot; value=&quot;100&quot;
       r-input=&quot;hist(rnorm(as.numeric(.value)))&quot; r-out=&quot;plot&quot;&gt;&lt;/label&gt;
&lt;div id=&quot;plot&quot;&gt;&lt;/div&gt;
</pre>

<p>Here, <code>.value</code> (<code>_value</code> in Python) holds the slider’s current value, and the histogram is redrawn as you move it.</p>

<h2 id="python-and-r-compute-javascript-draws">Python and R compute, JavaScript draws</h2>

<p>My favorite part: results can be passed as <strong>data</strong> to any JavaScript chart library. In a <a href="https://thierrymoudiki.github.io/blog/2026/09/27/python/r/javascript/analytics-pipeline" rel="nofollow" target="_blank">previous post</a>, I used <a href="https://observablehq.github.io/plot/" rel="nofollow" target="_blank">Observable Plot</a> and <a href="https://www.highcharts.com/" rel="nofollow" target="_blank">Highcharts</a> for dashboards. With <code>pyr.js</code>, <code>py-then</code> / <code>r-then</code> hand the result to a function of your choice. An R data frame arrives as an array of rows, ready to plot:</p>

<pre>&lt;script src=&quot;https://cdn.jsdelivr.net/npm/d3@7.9.2/dist/d3.min.js&quot;&gt;&lt;/script&gt;
&lt;script src=&quot;https://cdn.jsdelivr.net/npm/@observablehq/plot@0.6.19/dist/plot.umd.min.js&quot;&gt;&lt;/script&gt;
&lt;script src=&quot;https://cdn.jsdelivr.net/gh/Techtonique/pyr.js@v0.1.0/pyr.js&quot;&gt;&lt;/script&gt;
&lt;script&gt;
  function draw(rows, el) {
    el.replaceChildren(Plot.dot(rows, { x: &quot;wt&quot;, y: &quot;mpg&quot;, stroke: &quot;cyl&quot; }).plot());
  }
&lt;/script&gt;

&lt;script type=&quot;text/r&quot;&gt;
cars &lt;- function() {
  d &lt;- mtcars
  d$cyl &lt;- factor(paste(d$cyl, &quot;cylinders&quot;))   # factors arrive as text
  d[, c(&quot;wt&quot;, &quot;mpg&quot;, &quot;cyl&quot;)]
}
&lt;/script&gt;

&lt;div r-ready=&quot;cars()&quot; r-then=&quot;draw&quot; r-out=&quot;chart&quot;&gt;&lt;/div&gt;
&lt;div id=&quot;chart&quot;&gt;&lt;/div&gt;
</pre>

<p>The same works with Python: lists of dicts, numpy arrays and pandas DataFrames are converted for you. Here’s the Observable Plot example from the repository, with a Python random walk (redrawn by a slider) and the R data frame above:</p>

<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>

<h2 id="how-fast-is-it">How fast is it?</h2>

<p>The first visit downloads the engines (several MB for Python, cached by the browser afterwards), and starting Python takes about 3 seconds. Nothing magical so far.</p>

<p>The interesting part: when <code>pyr.js</code> is hosted on the same site as your pages, Python runs in a <em>shared worker</em>. Other tabs of the site, and even page reloads, reuse the interpreter that’s already running: in my tests (Chromium), the page was ready in <strong>under 0.1 second</strong> instead of 3. Each tab still has its own variables, and a reload still starts the page fresh. For R, webR doesn’t allow this (yet), so it starts with each page.</p>

<p>There’s also a <em>live editing</em> mode for development: put your Python code in a <code>.py</code> file, add <code>data-watch</code> to the script tag, and your changes apply to the running page as soon as you save, without reloading.</p>

<h2 id="privacy">Privacy</h2>

<p>pyr.js sends nothing anywhere. No analytics, no telemetry: your code and your data stay in the visitor’s browser. The only network requests are for the engines themselves and the packages your code imports.</p>

<h2 id="try-it">Try it</h2>

<p>The repository is on <a href="https://github.com/Techtonique/pyr.js" rel="nofollow" target="_blank">GitHub</a> (MIT license), with <strong>four examples</strong>: the basics, <a href="https://observablehq.com/@observablehq/plot-gallery" rel="nofollow" target="_blank">Observable Plot</a>, <a href="https://www.highcharts.com/" rel="nofollow" target="_blank">Highcharts</a> and live editing. The README explains the rest (attributes, data conversion, self-hosting the engines, pinning a version with an <code>integrity</code> hash). Feedback, issues and stars are welcome!</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/15/python/r/javascript/pyr_js"> 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-pages-with-one-script-tag/">pyr.js: Python and R in HTML pages, with one script tag</a>]]></content:encoded>
					
		
		<enclosure url="" length="0" type="" />

		<post-id xmlns="com-wordpress:feed-additions:1">404899</post-id>	</item>
		<item>
		<title>Introducing PLaMo-based AI translation for Bioconductor lessons</title>
		<link>https://www.r-bloggers.com/2026/11/introducing-plamo-based-ai-translation-for-bioconductor-lessons/</link>
		
		<dc:creator><![CDATA[Kozo Nishida]]></dc:creator>
		<pubDate>Fri, 13 Nov 2026 00:00:00 +0000</pubDate>
				<category><![CDATA[R bloggers]]></category>
		<guid isPermaLink="false">https://blog.bioconductor.org/posts/2026-11-13-ai-translation/</guid>

					<description><![CDATA[<div style = "width:60%; display: inline-block; float:left; ">
<p>In the report on our Japanese workshops, I explained why our Crowdin integration had become difficult to maintain. Keeping executable R Markdown lessons in sync required file conversions, translation synchronisation and reconstruction of buildab...</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/introducing-plamo-based-ai-translation-for-bioconductor-lessons/">Introducing PLaMo-based AI translation for Bioconductor lessons</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.bioconductor.org/posts/2026-11-13-ai-translation/"> Bioconductor community 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>In the <a href="https://blog.bioconductor.org/posts/2026-11-12-japanese-carpentries-workshops/" rel="nofollow" target="_blank">report on our Japanese workshops</a>, I explained why our Crowdin integration had become difficult to maintain. Keeping executable R Markdown lessons in sync required file conversions, translation synchronisation and reconstruction of buildable lessons. I remain grateful for Crowdin’s support. We are now moving to PLaMo-based AI translation directly in the lesson repositories, with code and markup protected and community review on GitHub.</p>
<p>I am introducing a new AI-assisted translation workflow in the <a href="https://github.com/bioconductor-translations" rel="nofollow" target="_blank">bioconductor-translations</a> organisation, built around PLaMo 3 Translate and review on GitHub. The first lesson is <a href="https://carpentries-incubator.github.io/bioc-intro/" rel="nofollow" target="_blank"><em>Introduction to data analysis with R and Bioconductor</em></a>, with published editions in Japanese, Spanish, Simplified Chinese, French and Urdu. These editions are open for community review and improvement.</p>
<section id="what-is-plamo-3-translate" class="level2">
<h2 class="anchored" data-anchor-id="what-is-plamo-3-translate">What is PLaMo 3 Translate?</h2>
<p>PLaMo 3 Translate is a family of large language models developed by Preferred Networks (PFN) specifically for translation. PFN’s November 5, 2026 technical article, <a href="https://www.preferred.jp/en/blog/tech/plamo-3-translate-weight-release" rel="nofollow" target="_blank"><em>PLaMo 3 Translate: World-Class Translation with Open Weights—Here’s How We Built It</em></a>, explains the development process and the release of downloadable model weights.</p>
<p>PFN trains the models on source–translation pairs and further refines them to prefer better translations. Smaller models also learn from the 31B model through distillation. The family supports 53 languages and can take surrounding context and a glossary into account. These features fit our lesson workflow: we can supply nearby explanations and preferred technical terminology when translating a passage.</p>
<p>The models come in four sizes: 0.8B, 2B, 8B and 31B parameters. Our workflow uses <a href="https://huggingface.co/pfnet/plamo-3-translate-8b-MLX-4bit" rel="nofollow" target="_blank"><code>pfnet/plamo-3-translate-8b-MLX-4bit</code></a>, the 8B model in a 4-bit MLX format that reduces memory use for local generation on Apple silicon Macs. The model weights are distributed under the PLaMo Community License.</p>
</section>
<section id="explore-the-five-language-editions" class="level2">
<h2 class="anchored" data-anchor-id="explore-the-five-language-editions">Explore the five language editions</h2>
<p>The introductory lesson covers organising data in spreadsheets, using R and RStudio, manipulating data with <code>dplyr</code>, and visualising data. Each language edition has a lesson website for learners and a repository for contributors:</p>
<table class="caption-top table">
<thead>
<tr class="header">
<th style="text-align: left;">Language</th>
<th style="text-align: left;">Read the lesson</th>
<th style="text-align: left;">Contribute on GitHub</th>
</tr>
</thead>
<tbody>
<tr class="odd">
<td style="text-align: left;">Japanese</td>
<td style="text-align: left;"><a href="https://bioconductor-translations.github.io/bioc-intro-plamo3translate-ja/" rel="nofollow" target="_blank">Japanese lesson</a></td>
<td style="text-align: left;"><a href="https://github.com/bioconductor-translations/bioc-intro-plamo3translate-ja" rel="nofollow" target="_blank">bioc-intro-plamo3translate-ja</a></td>
</tr>
<tr class="even">
<td style="text-align: left;">Spanish</td>
<td style="text-align: left;"><a href="https://bioconductor-translations.github.io/bioc-intro-plamo3translate-es/" rel="nofollow" target="_blank">Spanish lesson</a></td>
<td style="text-align: left;"><a href="https://github.com/bioconductor-translations/bioc-intro-plamo3translate-es" rel="nofollow" target="_blank">bioc-intro-plamo3translate-es</a></td>
</tr>
<tr class="odd">
<td style="text-align: left;">Simplified Chinese</td>
<td style="text-align: left;"><a href="https://bioconductor-translations.github.io/bioc-intro-plamo3translate-zh-hans/" rel="nofollow" target="_blank">Simplified Chinese lesson</a></td>
<td style="text-align: left;"><a href="https://github.com/bioconductor-translations/bioc-intro-plamo3translate-zh-hans" rel="nofollow" target="_blank">bioc-intro-plamo3translate-zh-hans</a></td>
</tr>
<tr class="even">
<td style="text-align: left;">French</td>
<td style="text-align: left;"><a href="https://bioconductor-translations.github.io/bioc-intro-plamo3translate-fr/" rel="nofollow" target="_blank">French lesson</a></td>
<td style="text-align: left;"><a href="https://github.com/bioconductor-translations/bioc-intro-plamo3translate-fr" rel="nofollow" target="_blank">bioc-intro-plamo3translate-fr</a></td>
</tr>
<tr class="odd">
<td style="text-align: left;">Urdu</td>
<td style="text-align: left;"><a href="https://bioconductor-translations.github.io/bioc-intro-plamo3translate-ur/" rel="nofollow" target="_blank">Urdu lesson</a></td>
<td style="text-align: left;"><a href="https://github.com/bioconductor-translations/bioc-intro-plamo3translate-ur" rel="nofollow" target="_blank">bioc-intro-plamo3translate-ur</a></td>
</tr>
</tbody>
</table>
<p>Our Crowdin project also received Portuguese translation contributions, and I am grateful to everyone who contributed them. I am sorry that Portuguese is not included among these editions: the PLaMo translation model we currently use does not support Portuguese, which is absent from its <a href="https://huggingface.co/pfnet/plamo-3-translate-8b#supported-languages" rel="nofollow" target="_blank">supported-language list</a>.</p>
<p>Translation coverage and review are still in progress. Some setup pages and interface labels remain in English. At the time of writing, the published Urdu episodes are available, but that repository’s <a href="https://github.com/bioconductor-translations/bioc-intro-plamo3translate-ur/blob/main/translation/config.json" rel="nofollow" target="_blank">updater configuration</a> and translation guide still refer to Japanese and need adaptation before being used to regenerate Urdu text.</p>
</section>
<section id="how-the-translation-system-works" class="level2">
<h2 class="anchored" data-anchor-id="how-the-translation-system-works">How the translation system works</h2>
<div id="fig-translation-workflow" class="quarto-float quarto-figure quarto-figure-center anchored" alt="Workflow diagram: English lesson prose either reuses matching translation memory or is translated locally by PLaMo using a glossary and context. Protected code and lesson markup bypass generation. The reassembled lessons undergo structure checks, community review and a build. Reviewed corrections are saved to translation memory." data-fig-align="center">
<figure class="quarto-float quarto-float-fig figure">
<div aria-describedby="fig-translation-workflow-caption-0ceaefa1-69ba-4598-a22c-09a6ac19f8ca">
<img src="https://i0.wp.com/blog.bioconductor.org/posts/2026-11-13-ai-translation/translation-workflow.jpg?w=450&#038;ssl=1" class="img-fluid quarto-figure quarto-figure-center figure-img" alt="Workflow diagram: English lesson prose either reuses matching translation memory or is translated locally by PLaMo using a glossary and context. Protected code and lesson markup bypass generation. The reassembled lessons undergo structure checks, community review and a build. Reviewed corrections are saved to translation memory."  data-recalc-dims="1">
</div>
<figcaption class="quarto-float-caption-bottom quarto-float-caption quarto-float-fig" id="fig-translation-workflow-caption-0ceaefa1-69ba-4598-a22c-09a6ac19f8ca">
Figure 1: Matching passages reuse translation memory; new or changed prose is translated with PLaMo. Protected code and markup rejoin the text before structural checks, community review and a lesson build.
</figcaption>
</figure>
</div>
<ol type="1">
<li><strong>Read an English source revision.</strong> The translator reads the upstream lesson’s R Markdown files from a Git revision without checking it out over the translated working files.</li>
<li><strong>Reuse matching translations.</strong> Each translation repository stores its versioned translation memory in <code>translation/seed-cache.json</code>. This JSON file stores previous translations and review statuses by source passage and episode. Matching records can be reused, while new or changed prose is sent to the model.</li>
<li><strong>Guide terminology and protect structure.</strong> A language-specific glossary and contextual guidance help disambiguate terms. Code blocks, inline code, link destinations and lesson markup are protected during translation, and structural checks run before lesson files are replaced.</li>
<li><strong>Review and build.</strong> Maintainers inspect the translated text and memory changes, build the lesson, and commit the reviewed result. The translator itself does not commit or push changes.</li>
</ol>
<section id="shared-terminology-in-glossary.json" class="level3">
<h3 class="anchored" data-anchor-id="shared-terminology-in-glossary.json">Shared terminology in glossary.json</h3>
<p>Each repository keeps its preferred terminology in <code>translation/glossary.json</code>. For example, the Japanese repository’s <a href="https://github.com/bioconductor-translations/bioc-intro-plamo3translate-ja/blob/main/translation/glossary.json" rel="nofollow" target="_blank">translation/glossary.json</a> contains <code>source</code> and <code>target</code> term pairs, mapping “data frame” to “データフレーム” and keeping “Bioconductor” unchanged. The translator passes these pairs to the model to guide terminology consistently across episodes. Contributors can propose glossary changes through pull requests. A glossary change requires fresh generation for machine records on the next update; matching <code>reviewed</code> records retain their wording, so terminology corrections must also be applied to the reviewed translation memory where needed.</p>
</section>
<section id="update-a-translation-yourself" class="level3">
<h3 class="anchored" data-anchor-id="update-a-translation-yourself">Update a translation yourself</h3>
<p>To update a translation yourself, follow <code>translation/README.md</code> in the repository for your language. These documents cover environment setup, fetching the English source, previewing changes, generating translations, reviewing the results and building the lesson:</p>
<ul>
<li>Japanese: <a href="https://github.com/bioconductor-translations/bioc-intro-plamo3translate-ja/blob/main/translation/README.md" rel="nofollow" target="_blank">translation/README.md</a></li>
<li>Spanish: <a href="https://github.com/bioconductor-translations/bioc-intro-plamo3translate-es/blob/main/translation/README.md" rel="nofollow" target="_blank">translation/README.md</a></li>
<li>Simplified Chinese: <a href="https://github.com/bioconductor-translations/bioc-intro-plamo3translate-zh-hans/blob/main/translation/README.md" rel="nofollow" target="_blank">translation/README.md</a></li>
<li>French: <a href="https://github.com/bioconductor-translations/bioc-intro-plamo3translate-fr/blob/main/translation/README.md" rel="nofollow" target="_blank">translation/README.md</a></li>
</ul>
<p>For Urdu, the updater configuration and documentation caveat above still applies.</p>
<p>For example, in the Japanese repository, after configuring the upstream remote as described in its guide, a maintainer can run:</p>
<pre>git fetch upstream main
uv run --locked scripts/translate.py --source-ref upstream/main --dry-run
uv run --locked scripts/translate.py --source-ref upstream/main --update-memory
git diff -- episodes translation
Rscript scripts/build.R</pre>
<p>The dry run shows which passages can be reused and which need translation, without generating new text or writing lesson files. The <code>--update-memory</code> option saves new translation records to <code>translation/seed-cache.json</code> and source provenance to <code>translation/source-manifest.json</code> for review. The local runtime cache under <code>.cache/translation/</code> is ignored by Git. Other editions may use a different remote name, so follow <code>translation/README.md</code> in the repository you are updating.</p>
<p>The translator also checks for local edits and stops before overwriting an edited lesson. Small build adaptations are recorded separately with checks against the expected source. Images, datasets and episode ordering still need separate maintenance when the English lesson changes.</p>
</section>
</section>
<section id="local-generation-reusable-community-knowledge" class="level2">
<h2 class="anchored" data-anchor-id="local-generation-reusable-community-knowledge">Local generation, reusable community knowledge</h2>
<p>The workflow pins the model revision and locks its Python dependencies, recording the source revision and model provenance with the translation resources.</p>
<p>Generating new translations with the current implementation requires an Apple silicon Mac, Python 3.12 and <code>uv</code>; the first model download is about 6 GB. Planning updates and replaying cached translations can run with Python 3.12 alone on other platforms. Reading lessons and contributing a review on GitHub require no model installation.</p>
<p>The translation memory gives community review a lasting role. You can inspect the records in the Japanese translation repository’s <a href="https://github.com/bioconductor-translations/bioc-intro-plamo3translate-ja/blob/main/translation/seed-cache.json" rel="nofollow" target="_blank">translation/seed-cache.json</a>. Newly generated records are marked <code>machine</code>. After checking a record in <code>translation/seed-cache.json</code>, a reviewer can mark it <code>reviewed</code> so that its wording is retained for matching source text in the same episode and language pair, even when model or glossary settings change. The French translation repository’s <a href="https://github.com/bioconductor-translations/bioc-intro-plamo3translate-fr/blob/main/translation/README.md" rel="nofollow" target="_blank">translation/README.md</a> explains this review process.</p>
</section>
<section id="help-make-the-lessons-better" class="level2">
<h2 class="anchored" data-anchor-id="help-make-the-lessons-better">Help make the lessons better</h2>
<p>A successful build shows that the lesson can be rendered, but readers and instructors still need to check its meaning. A translation can sound fluent while changing an exercise condition, using an unfamiliar technical term, or losing an important distinction. The Simplified Chinese translation repository’s <a href="https://github.com/bioconductor-translations/bioc-intro-plamo3translate-zh-hans/blob/main/translation/README.md" rel="nofollow" target="_blank">translation/README.md</a> explicitly identifies its initial translation memory as machine generated and needing review.</p>
<p>If you use one of these languages, please try an episode and compare it with the English lesson. We especially welcome help with:</p>
<ul>
<li><strong>Language and terminology:</strong> suggest clearer explanations and vocabulary familiar to your local research community.</li>
<li><strong>Exercises and teaching:</strong> check that questions, solutions and instructor notes preserve the original learning goals.</li>
<li><strong>Corrections that carry forward:</strong> help maintainers update the glossary, context guidance and translation memory alongside the lesson text.</li>
</ul>
<p>Open an issue in the relevant repository with the episode name, the passage you are referring to, and a suggested correction or explanation. Pull requests are welcome too; please follow that repository’s contribution and translation guides. If you are interested in reviewing translations, adding support for another language, or translating another lesson, join the discussion in the #documentation-translation channel on the <a href="https://chat.bioconductor.org/" rel="nofollow" target="_blank">Bioconductor community chat</a>.</p>
<p>Thank you to the original lesson authors and maintainers, and to everyone translating, reviewing and teaching these materials. This work builds on the community’s translation efforts described in the Japanese workshop report and is supported by the <a href="https://bioconductor.org/developers/developer-champions-program/" rel="nofollow" target="_blank">Bioconductor Developer Champions Program</a>.</p>


</section>

<p>
© 2026 Bioconductor. Content is published under <a href="https://creativecommons.org/licenses/by/4.0/" rel="nofollow" target="_blank">Creative Commons CC-BY-4.0 License</a> for the text and <a href="https://opensource.org/licenses/BSD-3-Clause" rel="nofollow" target="_blank">BSD 3-Clause License</a> for any code. | <a href="https://www.r-bloggers.com/" rel="nofollow" target="_blank">R-Bloggers</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://blog.bioconductor.org/posts/2026-11-13-ai-translation/"> Bioconductor community 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/introducing-plamo-based-ai-translation-for-bioconductor-lessons/">Introducing PLaMo-based AI translation for Bioconductor lessons</a>]]></content:encoded>
					
		
		<enclosure url="https://blog.bioconductor.org/posts/2026-11-13-ai-translation/translation-workflow.jpg" length="0" type="image/jpeg" />

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