<p><div><div><div><div data-show-faces="false" data-height="21" data-width="100" data-layout="button_count" data-send="true" data-href="https://www.r-bloggers.com/quick-significance-calculations-for-a-b-tests-in-r/"></div></div><div></div></div><div></div></div>
<div>
(This article was first published on <strong><a href="http://www.win-vector.com/blog/2018/10/quick-significance-calculations-for-a-b-tests-in-r/"> R – Win-Vector Blog</a></strong>, and kindly contributed to <a rel="nofollow" href="https://www.r-bloggers.com/">R-bloggers)</a> </div>
<h2>Introduction</h2>
<p>Let’s take a quick look at a very important and common experimental problem: checking if the difference in success rates of two <a rel="nofollow" href="https://en.wikipedia.org/wiki/Binomial_distribution" target="_blank">Binomial experiments</a> is statistically significant. This can arise in A/B testing situations such as online advertising, sales, and manufacturing.</p>
<p>We already share a <a rel="nofollow" href="http://www.win-vector.com/blog/2016/02/free-video-course-applied-bayesian-ab-testing-in-r/" target="_blank">free video course on a Bayesian treatment of planning and evaluating A/B tests</a> (including a <a rel="nofollow" href="https://github.com/WinVector/CampaignPlanner_v3" target="_blank">free Shiny application</a>). Let’s now take a look at the should be simple task of simply building a summary statistic that includes a classic frequentist significance.</p>
<p><span></span></p>
<p>
<p>Suppose our data comes from collecting outcomes from two processes: A and B, and is as follows.</p>
<div>
<pre><code><span># build example data</span>
<span>set.seed</span>(<span>2018</span>)
A &lt;-<span> </span><span>rep</span>(<span>0</span>, <span>2000</span>)
A[<span>sample.int</span>(<span>length</span>(A), <span>823</span>)] &lt;-<span> </span><span>1</span>
B &lt;-<span> </span><span>rep</span>(<span>0</span>, <span>100</span>)
B[<span>sample.int</span>(<span>length</span>(B), <span>55</span>)] &lt;-<span> </span><span>1</span></code></pre>
</div>
<div>
<pre><code><span># summarize data</span>
(kA &lt;-<span> </span><span>sum</span>(A))</code></pre>
</div>
<pre><code>## [1] 823</code></pre>
<div>
<pre><code>(nA &lt;-<span> </span><span>length</span>(A))</code></pre>
</div>
<pre><code>## [1] 2000</code></pre>
<div>
<pre><code>(kB &lt;-<span> </span><span>sum</span>(B))</code></pre>
</div>
<pre><code>## [1] 55</code></pre>
<div>
<pre><code>(nB &lt;-<span> </span><span>length</span>(B))</code></pre>
</div>
<pre><code>## [1] 100</code></pre>
<div>
<pre><code>(abs_rate_difference &lt;-<span> </span><span>abs</span>(nB*kA -<span> </span>nA*kB)/(nA*nB))</code></pre>
</div>
<pre><code>## [1] 0.1385</code></pre>
<div>
<pre><code>df &lt;-<span> </span><span>data.frame</span>(
  <span>outcome =</span> <span>c</span>(A, B), 
  <span>treatment =</span> <span>c</span>(<span>rep</span>(<span>&quot;A&quot;</span>, <span>length</span>(A)), 
                <span>rep</span>(<span>&quot;B&quot;</span>, <span>length</span>(B))),
  <span>stringsAsFactors =</span> <span>FALSE</span>)
<span>table</span>(df)</code></pre>
</div>
<pre><code>##        treatment
## outcome    A    B
##       0 1177   45
##       1  823   55</code></pre>
<p>A natural question is: how likely is such a large difference of success rates assuming a null-hypothesis that both processes are in fact the same and generating 1’s at the common observed rate? This is a classic frequentist significance question.</p>
<h2>The <code>sigr</code> philosophy</h2>
<p>The philosophy of the the <a rel="nofollow" href="https://cran.r-project.org/package=sigr" target="_blank"><code>sigr</code></a> <a rel="nofollow" href="https://www.r-project.org/" target="_blank"><code>R</code></a> package is that each common statistical test should be a &quot;one liner&quot; that properly performs and formats a test. That is not to say statistical tests are easy to understand, they can in fact be difficult. It is the intent that performing and reporting the test should not <em>add</em> to the difficulty of finding, applying, and reporting the correct test.</p>
<p>So with correct documentation, training, and thought one can (with a reasonable effort) find, understand, and apply a correct test in a manner that <em>appears</em> effortless a-posteriori.</p>
<p>In the case of comparing rates of two Binomial experiments (the correct formulation of comparing rates in an A/B test) we say our mental handbook now includes <code>sigr::Bernoulli_diff_stat()</code> as the correct test.</p>
<h2>The <code>sigr::Bernoulli_diff_stat()</code> solution</h2>
<p>With the <a rel="nofollow" href="https://cran.r-project.org/package=sigr" target="_blank"><code>sigr</code></a> <a rel="nofollow" href="https://www.r-project.org/" target="_blank"><code>R</code></a> package we can answer the question directly with the difference in <a rel="nofollow" href="https://winvector.github.io/sigr/reference/Bernoulli_diff_stat.html" target="_blank">Bernoulli processes difference statistic</a>. Frequentest summaries are supposed to be easy and quick to derive, and here is the difference in rates of Binomial processes as a one-liner.</p>
<div>
<pre><code><span>library</span>(<span>&quot;sigr&quot;</span>)

s &lt;-<span> </span><span>Bernoulli_diff_stat</span>(kA, nA, kB, nB)
<span>print</span>(s)</code></pre>
</div>
<pre><code>## [1] &quot;Bernoulli difference test: (A=823/2000=0.4115, B=55/100=0.55, post 0.1385 two sided; p=0.006062).&quot;</code></pre>
<p>The above is deliberately concise. It assumes we (and our partners) know exactly the test we want and quickly applies and formats (without explanation). We emphasize critical thought and explanation are critical in statistical testing- they are just not part of the test. We also say a longer test procedure (say 5, 10, or 20 lines of code) steals attention from thinking <em>about</em> the experiment. What we suggest is having concise and correct testing code ready, and leaving more time for considering (and confirming) we have in fact applied an appropriate test.</p>
<p>In addition to a formatted presentation the <code>Bernoulli_diff_stat()</code> returns a number of useful values.</p>
<div>
<pre><code>s$probi                <span># assumed common rate</span></code></pre>
</div>
<pre><code>## [1] 0.4180952</code></pre>
<div>
<pre><code>s$test_rate_difference <span># difference in rates we are testing for</span></code></pre>
</div>
<pre><code>## [1] 0.1385</code></pre>
<div>
<pre><code>s$pValue               <span># estimated p-value/significance</span></code></pre>
</div>
<pre><code>## [1] 0.006062159</code></pre>
<p>The small p-value indicates that a difference of this magnitude (0.1385) is unlikely under the null-assumption that both processes were in fact identical with a common success-rate (rate of <code>1</code>‘s in each output) of 0.418095.</p>
<p><code>Bernoulli_diff_stat()</code> is a deterministic and exact statistical test when <code>max(nA, nB) %% min(nA, nB) == 0</code>. It has minimal assumptions/approximations as it is directly testing a difference in scaled Binomial/Bernoulli processes. When <code>max(nA, nB) %% min(nA, nB) != 0</code> the test gives a range of answers:</p>
<div>
<pre><code><span>Bernoulli_diff_stat</span>(<span>824</span>, <span>2001</span>, <span>55</span>, <span>100</span>)</code></pre>
</div>
<pre><code>## [1] &quot;Bernoulli difference test: (A~824/2001=0.4118, B=55/100=0.55, post 0.1382 two sided; pL=0.005978, pH=0.006067).&quot;</code></pre>
<p>The range is formed by alternately truncating and extending the longer process to get the required divisibility property. The reported range is tight when <code>max(nA, nB) / min(nA, nB)</code> is large. Being a statistic of discrete summaries <code>Bernoulli_diff_stat()</code> is sensitive to end-effects (the p-value moves up and down as exact counts move in and out of rate-defined intervals).</p>
<h2>Simulation estimate</h2>
<p>One could try to estimate the significance in difference in rates directly through re-sampling or simulation techniques. Obviously estimating small significances is going to be computationally expensive.</p>
<div>
<pre><code><span>set.seed</span>(<span>2018</span>)

n_runs &lt;-<span> </span><span>100</span>
run_size &lt;-<span> </span><span>10000</span> 
mk_resample &lt;-<span> </span>function(A, B, run_size) {
  <span>force</span>(A)
  <span>force</span>(B)
  kA &lt;-<span> </span><span>sum</span>(A)
  nA &lt;-<span> </span><span>length</span>(A)
  kB &lt;-<span> </span><span>sum</span>(B)
  nB &lt;-<span> </span><span>length</span>(B)
  univ &lt;-<span> </span><span>c</span>(A, B)
  nU &lt;-<span> </span><span>length</span>(univ)
  <span>force</span>(run_size)
  <span># integer to avoid rounding issues</span>
  abs_rate_difference_times_nab &lt;-<span> </span><span>abs</span>(nB*kA -<span> </span>nA*kB)

  function(...) {
    nge &lt;-<span> </span><span>0</span>
    for(i in <span>seq_len</span>(run_size)) {
      sA &lt;-<span> </span>univ[<span>sample.int</span>(nU, nA, <span>replace =</span> <span>TRUE</span>)]
      sB &lt;-<span> </span>univ[<span>sample.int</span>(nU, nB, <span>replace =</span> <span>TRUE</span>)]
      obs &lt;-<span> </span><span>abs</span>(nB*<span>sum</span>(sA) -<span> </span>nA*<span>sum</span>(sB))
      nge &lt;-<span> </span>nge +<span> </span>(obs>=abs_rate_difference_times_nab)
    }
    nge
  }
}
f &lt;-<span> </span><span>mk_resample</span>(A, B, run_size)

cl &lt;-<span> </span>parallel::<span>makeCluster</span>(parallel::<span>detectCores</span>())
res &lt;-<span> </span><span>as.numeric</span>(parallel::<span>parLapply</span>(cl, <span>seq_len</span>(n_runs), f))
parallel::<span>stopCluster</span>(cl)

k &lt;-<span> </span><span>sum</span>(res)
n &lt;-<span> </span>n_runs*run_size
<span>print</span>(k/n) <span># empiricl estimate of p-value/</span></code></pre>
</div>
<pre><code>## [1] 0.006011</code></pre>
<p>We can, with a quick appeal to another canned test (<code>wrapBinomTestS()</code>), check if our original theoretical p-value (<code>s$pValue =</code> 0.00606216) is compatible with the empirical estimate of the same.</p>
<div>
<pre><code><span>wrapBinomTestS</span>(k, n, <span>p =</span> s$pValue)</code></pre>
</div>
<pre><code>## [1] &quot;Exact binomial test: (6011/1e+06=0.006011~c(0.95)[0.00586, 0.006164], two.sided 0.006062; p=n.s.).&quot;</code></pre>
<p>The &quot;<code>p=n.s.</code>&quot; means the <code>Bernoulli_diff_stat()</code> value is close the the empirical value (as we want).</p>
<h2>Other estimates</h2>
<p>A common (and useful) way to estimate the difference in Bernoulli/Binomial rates is to leave out some domain knowledge to convert to a nearly equivalent problem that itself has a ready-made test. Two common such relaxations are forgetting that the process is Bernoulli/Binomial 0/1 and using general t-test to compare means, or switching from a test of differences of rates and appealing to a Fischer Test of independence between process label and outcome marks (a related but different question).</p>
<h3>t-test estimate</h3>
<p>If we ignore the fact that the Binomial process generates only 0/1 we can use a classic t-test to estimate the significance of the observed difference.</p>
<div>
<pre><code>ttest &lt;-<span> </span><span>wrapTTest</span>(A, B)
<span>print</span>(ttest)</code></pre>
</div>
<pre><code>## [1] &quot;Welch Two Sample t-test, two.sided: (t=-2.705, df=108.8, p=0.007925).&quot;</code></pre>
<p>Notice the t-test is not in the confidence interval of empirical estimates of the differences in rates significance.</p>
<div>
<pre><code><span>wrapBinomTestS</span>(k, n, <span>p =</span> ttest$tt$p.value)</code></pre>
</div>
<pre><code>## [1] &quot;Exact binomial test: (6011/1e+06=0.006011~c(0.95)[0.00586, 0.006164], two.sided 0.007925; p&lt;1e-05).&quot;</code></pre>
<p>One could work further on the above by adding &quot;continuity corrections&quot; (which is really just a vainglorious way of say &quot;shifting boundaries by 0.5&quot;) and so on, but we feel running an exact test that matches the problem’s actual generative model (and actual distribution) is preferred.</p>
<h3>Fisher test estimate</h3>
<p>Or, if we ignore distinction between treatment and outcome we can use a Fisher independence test.</p>
<div>
<pre><code>tab_test &lt;-<span> </span><span>wrapFisherTest</span>(df, <span>&quot;treatment&quot;</span>, <span>&quot;outcome&quot;</span>)
<span>print</span>(tab_test)</code></pre>
</div>
<pre><code>## [1] &quot;Fisher's Exact Test for Count Data: (odds.ratio=1.747, p=0.00685).&quot;</code></pre>
<div>
<pre><code><span>wrapBinomTestS</span>(k, n, <span>p =</span> tab_test$ft$p.value)</code></pre>
</div>
<pre><code>## [1] &quot;Exact binomial test: (6011/1e+06=0.006011~c(0.95)[0.00586, 0.006164], two.sided 0.00685; p&lt;1e-05).&quot;</code></pre>
<p>Again, the Fisher test is not in the confidence interval of empirical estimates of the differences in rates significance.</p>
<h2>Conclusion</h2>
<p>All of the above estimation methods are standard and serviceable (give the same qualitative answer that the difference in rates is in fact significant).</p>
<p>However notice, neither of the t-test estimate or the Fisher test estimate were in the empirically estimated confidence interval of the exact quantitative value for the unknown significance.</p>
<p>Because <code>Bernoulli_diff_stat()</code> has a low degree of approximations and assumptions we feel it is easy to use and explain (where it applies, in particular when <code>max(nA, nB) %% min(nA, nB) == 0</code> or when <code>max(nA, nB) / min(nA, nB)</code> is large).</p>
<p><code>Bernoulli_diff_stat()</code> is new code (so we are still exploring corner cases), but is based on sound concepts (converting differences in rates into differences in counts, an idea inspired by Wald’s <em>Sequential Analysis</em>).</p>
<p>The above are all examples of the <code>sigr</code> package philosophy: correct and concise wrappers for important statistical tests. Link to the correct statistics found in <code>R</code> but try to stay out of the user’s way both in performing the test and reporting the test.</p>
	<p>
<div>
<div>To <strong>leave a comment</strong> for the author, please follow the link and comment on their blog: <strong><a href="http://www.win-vector.com/blog/2018/10/quick-significance-calculations-for-a-b-tests-in-r/"> R – Win-Vector Blog</a></strong>.</div>
<hr>
<a rel="nofollow" href="https://www.r-bloggers.com/">R-bloggers.com</a> offers <strong><a rel="nofollow" href="https://feedburner.google.com/fb/a/mailverify?uri=RBloggers">daily e-mail updates</a></strong> about <a rel="nofollow" href="https://www.r-project.org/" title="The R Project for Statistical Computing">R</a> news and <a rel="nofollow" href="https://www.r-bloggers.com/search/tutorial" title="R tutorials">tutorials</a> on topics such as: <a rel="nofollow" href="https://www.r-bloggers.com/search/data%20science" title="Data science">Data science</a>, <a rel="nofollow" href="https://www.r-bloggers.com/search/Big%20Data" title="Big Data">Big Data, <a rel="nofollow" href="https://www.r-users.com/" title="R jobs">R jobs</a>, visualization (<a rel="nofollow" href="https://www.r-bloggers.com/search/ggplot2" title="ggplot and ggplot2 tutorials">ggplot2</a>, <a rel="nofollow" href="https://www.r-bloggers.com/search/boxplot" title="Boxplots using lattice and ggplot2 tutorials">Boxplots</a>, <a rel="nofollow" href="https://www.r-bloggers.com/search/map" title="Maps and gis">maps</a>, <a rel="nofollow" href="https://www.r-bloggers.com/search/animation" title="Animation in R">animation</a>), programming (<a rel="nofollow" href="https://www.r-bloggers.com/search/RStudio" title="RStudio IDE for R">RStudio</a>, <a rel="nofollow" href="https://www.r-bloggers.com/search/sweave" title="Sweave and literate programming">Sweave</a>, <a rel="nofollow" href="https://www.r-bloggers.com/search/LaTeX" title="LaTeX in R">LaTeX</a>, <a rel="nofollow" href="https://www.r-bloggers.com/search/SQL" title="SQL and databases">SQL</a>, <a rel="nofollow" href="https://www.r-bloggers.com/search/eclipse" title="Eclipse IDE for R">Eclipse</a>, <a rel="nofollow" href="https://www.r-bloggers.com/search/git" title="git and github, Version Control System">git</a>, <a rel="nofollow" href="https://www.r-bloggers.com/search/hadoop" title="Large data in R using Hadoop">hadoop</a>, <a rel="nofollow" href="https://www.r-bloggers.com/search/Web+Scraping" title="Web Scraping of google, facebook, yahoo, twitter and more using R">Web Scraping</a>) statistics (<a rel="nofollow" href="https://www.r-bloggers.com/search/regression" title="Regressions and ANOVA analysis tutorials">regression</a>, <a rel="nofollow" href="https://www.r-bloggers.com/search/PCA" title="principal component analysis tutorial">PCA</a>, <a rel="nofollow" href="https://www.r-bloggers.com/search/time+series" title="Time series">time series</a>, <a rel="nofollow" href="https://www.r-bloggers.com/search/trading" title="finance trading">trading</a>) and more...
<img width="1" alt="" src="http://feeds.feedburner.com/~r/RBloggers/~4/me4KSd4g4BU" height="1"></a></div>