<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/tips-for-ab-testing-with-r/"></div></div><div></div></div><div></div></div>
<div>
(This article was first published on <strong><a href="https://www.inwt-statistics.com/read-blog/ab-testing.html"> INWT-Blog-RBloggers</a></strong>, and kindly contributed to <a rel="nofollow" href="https://www.r-bloggers.com/">R-bloggers)</a> </div>
<div>
<p>Which layout of an advertisement leads to more clicks? Would a different color or position of the purchase button lead to a higher conversion rate? Does a special offer really attract more customers – and which of two phrasings would be better?</p>
<p>For a long time, people have trusted their gut feeling to answer these questions. Today all these questions could be answered by conducting an A/B test. For this purpose, visitors of a website are randomly assigned to one of two groups between which the target metric (i.e. click-through rate, conversion rate…) can then be compared. Due to this randomization, the groups do not systematically differ in all other relevant dimensions. This means: If your target metric takes a significantly higher value in one group, you can be quite sure that it is because of your treatment and not because of any other variable.</p>
<p>In comparison to other methods, conducting an A/B test does not require extensive statistical knowledge. Nevertheless, some caveats have to be taken into account.</p>
</div>
<div>
<p>When making a statistical decision, there are two possible errors (see also table 1): A Type I error means that we observe a significant result although there is no real difference between our groups. A Type II error means that we do not observe a significant result although there is in fact a difference. The Type I error can be controlled and set to a fixed number in advance, e.g., at 5%, often denoted as α or the significance level. The Type II error in contrast cannot be controlled directly. It decreases with the sample size and the magnitude of the actual effect. When, for example, one of the designs performs way better than the other one, it’s more likely that the difference is actually detected by the test in comparison to a situation where there is only a small difference with respect to the target metric. Therefore, the required sample size can be <a rel="nofollow" href="http://www.evanmiller.org/ab-testing/sample-size.html" target="_blank">computed in advance</a>, given α and the minimum effect size you want to be able to detect (statistical power analysis). Knowing the average traffic on the website you can get a rough idea of the time you have to wait for the test to complete. Setting the rule for the end of the test in advance is often called “fixed-horizon testing”.</p>
</div>
<pre><div> <div> <table><caption>Table 1: Overview over possible errors and correct decisions in statistical tests</caption> <thead> <tr> <td></td> <td></td> <td colspan="2">Effect really exists</td> </tr> <tr> <td></td> <td></td> <td>No</td> <td>Yes</td> </tr> </thead> <tbody> <tr> <td rowspan="2">Statistical test is significant</td> <td>No</td> <td>True negative</td> <td>Type II error (false negative)</td> </tr> <tr> <td>Yes</td> <td>Type I error (false positive)</td> <td>True positive</td> </tr> </tbody> </table> </div> </div></pre>
<div>
<p>Statistical tests generally provide the <em>p-value</em> which reflects the probability of obtaining the observed result (or an even more extreme one) just by chance, given that there is no effect. If the p-value is smaller than α, the result is denoted as “significant”.</p>
<p>When running an A/B test you may not always want to wait until the end but take a look from time to time to see how the test performs. What if you suddenly observe that your p-value has already fallen below your significance level – doesn’t that mean that the winner has already been identified and you could stop the test? Although this conclusion is very appealing, it can also be very wrong. The p-value fluctuates strongly during the experiment and even if the p-value at the end of the fixed-horizon is substantially larger than α, it can go below α at some point during the experiment. This is the reason why looking at your p-value several times is a little bit like cheating, because it makes your actual probability of a Type I error substantially larger than the α you chose in advance. This is called “α inflation”. At best you only change the color or position of a button although it does not have any impact. At worst, your company provides a special offer which causes costs but actually no gain. The more often you check your p-value during the data collection, the more likely you are to draw wrong conclusions. In short: As attractive as it may seem, don’t stop your A/B test early just because you are observing a significant result. In fact you can prove that if you increase your time horizon to infinity, you are guaranteed to get a significant p-value at some point in time.</p>
</div>
<div>
<p>The following code simulates some data and plots the course of the p-value during the test. (For the first samples which are still very small R returns a warning that the chi square approximation may be incorrect.)</p>
</div>
<pre><pre><code>library(timeDate) library(ggplot2) # Choose parameters: pA &lt;- 0.05 # True click through rate for group A pB &lt;- 0.08 # True click through rate for group B nA &lt;- 500 # Number of cases for group A nB &lt;- 500 # Number of cases for group B alpha &lt;- 0.05 # Significance level # Simulate data: data &lt;- data.frame(group = rep(c(&quot;A&quot;, &quot;B&quot;), c(nA, nB)),                    timestamp = sample(seq(as.timeDate('2016-06-02'),                                           as.timeDate('2016-06-09'), by = 1), nA+nB),                    clickedTrue = as.factor(c(rbinom(n = nA, size = 1, prob = pA),                                              rbinom(n = nB, size = 1, prob = pB)))) # Order data by timestamp data &lt;- data[order(data$GMT.x..i..), ] levels(data$clickedTrue) &lt;- c(&quot;0&quot;, &quot;1&quot;) # Compute current p-values after every observation: pValues &lt;- c() index &lt;- c() for (i in 50:dim(data)[1]){   presentData &lt;- table(data$group[1:i], data$clickedTrue[1:i])   if (all(rowSums(presentData) > 0)){     pValues &lt;- c(pValues, prop.test(presentData)$p.value)     index &lt;- c(index, i)} } results &lt;- data.frame(index = index,                       pValue = pValues) # Plot the p-values: ggplot(results, aes(x = index, y = pValue)) +   geom_line() +   geom_hline(aes(yintercept = alpha)) +   scale_y_continuous(name = &quot;p-value&quot;, limits = c(0,1)) +   scale_x_continuous(name = &quot;Observed data points&quot;) +   theme(text = element_text(size=20))</code></pre></pre>
<div>
<p>The figure below shows an example with 500 observations and true rates of 5% in both groups, i.e., no actual difference. You can see that the p-value nevertheless crosses the threshold several times, but finally takes a very high value. By stopping this test early, it would have been very likely to draw a wrong conclusion.</p>
</div>
<div>
<h5>Example for the course of a p-value for two groups with no actual difference</h5>
<figure> <img alt="Example for the course of the p-value during a test" src="https://i1.wp.com/www.inwt-statistics.com/assets/images/e/examplePValue-8416878e.png?resize=320%2C208&ssl=1" data-recalc-dims="1"> </figure>
</div>
<div>
<p>The following code shows you how to test the difference between two rates in R, e.g., click-through rates or conversion rates. You can apply the code to your own data by replacing the URL to the example data with your file path. To test the difference between two proportions, you can use the function prop.test which is equivalent to <a rel="nofollow" href="https://en.wikipedia.org/wiki/Pearson%27s_chi-squared_test" target="_blank">Pearson’s chi-squared test</a>. For small samples you should use Fisher’s exact test instead. Prop.test returns a p-value and a confidence interval for the difference between the two rates. The interpretation of a 95% confidence interval is as follows: When conducting such an analysis many times, then 95% of the displayed confidence intervals would contain the true difference. Afterwards you can also take a look at the fluctuations of the p-value during the tests by using the code from above.</p>
</div>
<pre><pre><code>library(readr) # Specify file path: dataPath &lt;-   &quot;https://www.inwt-statistics.de/files/INWT/downloads/exampleDataABtest.csv&quot; # Read data data &lt;- read_csv(file = dataPath)  # Inspect structure of the data str(data)  ## Classes 'tbl_df', 'tbl' and 'data.frame':    1000 obs. of  3 variables: ##  $ group      : chr  &quot;A&quot; &quot;A&quot; &quot;A&quot; &quot;B&quot; ... ##  $ time       : POSIXct, format: &quot;2016-06-02 02:17:53&quot; &quot;2016-06-02 03:03:54&quot; ... ##  $ clickedTrue: int  0 0 1 0 0 0 0 0 0 0 ... # Change the column names names(data) &lt;- c(&quot;group&quot;, &quot;time&quot;, &quot;clickedTrue&quot;)  # Change type of group to factor  data$group &lt;- as.factor(data$group)  # Change type of click through variable to factor data$clickedTrue &lt;- as.factor(data$clickedTrue)  levels(data$clickedTrue) &lt;- c(&quot;0&quot;, &quot;1&quot;) # Compute frequencies and conduct test for proportions  # (Frequency table with successes in the first column) freqTable &lt;- table(data$group, data$clickedTrue)[, c(2,1)]  # print frequency table freqTable  ##     ##       1   0 ##   A  20 480 ##   B  40 460 # Conduct significance test prop.test(freqTable, conf.level = .95) ##  ##  2-sample test for equality of proportions with continuity ##  correction ##  ## data:  freqTable ## X-squared = 6.4007, df = 1, p-value = 0.01141 ## alternative hypothesis: two.sided ## 95 percent confidence interval: ##  -0.071334055 -0.008665945 ## sample estimates: ## prop 1 prop 2  ##   0.04   0.08</code></pre></pre>
<div>
<p>There are some more pitfalls, but most of them can easily be avoided. First, as a counterpart of stopping your test early because of a significant result, you could gather more data after the planned end of the test because the results have not yet become significant. This would likewise lead to an α inflation. A second, similar problem arises when running several tests at once: The probability to achieve a false-positive result would then be α for <em>each</em> of the tests. The overall probability that <em>at least one</em> of the results is false-positive is much larger. So always keep in mind that some of the significant results may have been caused by chance. Third, you can also get into trouble when you reach the required sample size very fast and stop the test after a few hours already. You should always consider that the behavior of the users in this specific time slot might not be representative for the general case. To avoid this, you should plan the duration of the test so that it covers at least 24 hours or a week when customers are behaving different at the weekend than on a typical work day. A fourth caveat concerns a rather moral issue: When users discover they are part of an experiment and suffer from disadvantages as a result, they might rightly become angry. (This problem will probably not arise due to a different-colored button, but maybe because of <a rel="nofollow" href="https://en.wikipedia.org/wiki/Amazon.com_controversies#Differential_pricing" target="_blank">different prices</a> or special offers.)</p>
<p>If you are willing to invest some more time, you may want to learn about <a rel="nofollow" href="http://pages.optimizely.com/rs/optimizely/images/stats_engine_technical_paper.pdf" target="_blank">techniques to avoid α inflation when conducting multiple tests or stopping your test as soon as the p-value crosses a certain threshold</a>. In addition, there are techniques to include previous knowledge in your computations with <a rel="nofollow" href="https://cdn2.hubspot.net/hubfs/310840/VWO_SmartStats_technical_whitepaper.pdf" target="_blank">Bayesian approaches</a>. The latter is especially useful when you have rather small samples, but previous knowledge about the values that your <span>target metric</span> usually takes.</p>
</div>
	<p>
<div>
<div>To <strong>leave a comment</strong> for the author, please follow the link and comment on their blog: <strong><a href="https://www.inwt-statistics.com/read-blog/ab-testing.html"> INWT-Blog-RBloggers</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/bXpdgBHwR38" height="1"></a></div>